From 800e590f3ba8f3716557398ac56d9ed5f731e8e5 Mon Sep 17 00:00:00 2001 From: Christian Parpart Date: Fri, 27 Nov 2026 13:12:22 +0100 Subject: [PATCH 01/19] ci: indent build.yml's heredoc continuations by an even width editorconfig-checker refused three places in build.yml: two Python continuation lines and a Dockerfile's RUN continuation, each indented by an odd number of spaces where the file's indent_size is 2. Signed-off-by: Christian Parpart --- .github/workflows/build.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index fbf43ffc..664ba2d0 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -468,10 +468,10 @@ jobs: database, standard, *roots = sys.argv[1:] roots = tuple(os.path.realpath(root) + os.sep for root in roots) entries = [e for e in json.load(open(database)) - if os.path.realpath(os.path.join(e["directory"], e["file"])).startswith(roots)] + if os.path.realpath(os.path.join(e["directory"], e["file"])).startswith(roots)] flags = {"26": ("c++26", "c++2c")}[standard] wrong = [e["file"] for e in entries - if not any(f"-std={f}" in (e.get("command") or " ".join(e.get("arguments", []))) for f in flags)] + if not any(f"-std={f}" in (e.get("command") or " ".join(e.get("arguments", []))) for f in flags)] print(f"{len(entries)} compile(s) under {', '.join(roots)}; {len(wrong)} not compiled as C++{standard}") for path in wrong: print(f"::error::{path} is not compiled as C++{standard}") @@ -1335,8 +1335,8 @@ jobs: docker build -t core-cpp-vendored-smoke - <<'DOCKERFILE' FROM ubuntu:24.04 RUN apt-get update -q \ - && apt-get install -y -q --no-install-recommends g++-14 cmake ninja-build libssl-dev libsystemd-dev pkg-config \ - && rm -rf /var/lib/apt/lists/* + && apt-get install -y -q --no-install-recommends g++-14 cmake ninja-build libssl-dev libsystemd-dev pkg-config \ + && rm -rf /var/lib/apt/lists/* DOCKERFILE - name: The vendored copy configures, builds and verifies with no network From 89a0c6106cf1cc12db5e60ebfbdfc6de1d30b7e7 Mon Sep 17 00:00:00 2001 From: Christian Parpart Date: Fri, 27 Nov 2026 03:18:03 +0100 Subject: [PATCH 02/19] fix(build): configure as a subproject on a Clang without clang-scan-deps The root CMakeLists.txt's cmake_minimum_required(VERSION 3.25...3.31) sets CMP0155 NEW in core-cpp's scope, so from C++20 on every try_compile() there scans for module imports. As the top-level build CoreCppTopLevel.cmake turns that off, but as a subproject nothing did: a C++23 parent on a Clang with no clang-scan-deps stopped at find_package(Threads), the probe failing with exit 127 even though nobody asked for modules. core-cpp now sets CMP0155 OLD in its own directory scope. The parent's scope keeps its policy, a probe or target scans only when its CXX_SCAN_FOR_MODULES is ON, and so a parent's explicit CMAKE_CXX_SCAN_FOR_MODULES=ON still applies. core-cpp.module-scan (label hygiene) configures core-cpp top-level and as a subproject with a clang-scan-deps that does not exist, and asserts from the configure log that no probe ran it; a third case, the parent that asks for modules, must fail on the scanner, which is what makes the other two mean something. Without the policy line the subproject case fails. Also in this commit: - guard CMP0155 for the CMake 3.25 core-cpp still supports - the module-scan check skips its refused row below CMake 3.28 Signed-off-by: Christian Parpart --- .agent/reference/source-map.md | 4 + .agent/rules/build-and-toolchain.md | 13 ++ CMakeLists.txt | 13 ++ cmake/CoreCppTopLevel.cmake | 10 +- tests/CMakeLists.txt | 24 +++ .../cmake/check-cmake-hygiene-selftest.cmake | 5 +- tests/cmake/check-cmake-hygiene.cmake | 25 ++++ tests/cmake/check-module-scan.cmake | 137 ++++++++++++++++++ tests/consumer-module-scan/CMakeLists.txt | 31 ++++ 9 files changed, 256 insertions(+), 6 deletions(-) create mode 100644 tests/cmake/check-module-scan.cmake create mode 100644 tests/consumer-module-scan/CMakeLists.txt diff --git a/.agent/reference/source-map.md b/.agent/reference/source-map.md index b8c03256..c410ee9e 100644 --- a/.agent/reference/source-map.md +++ b/.agent/reference/source-map.md @@ -119,6 +119,8 @@ tests/ repositories it builds for the purpose check-install.cmake installs the build, consumes the package, and exports from a parent with CORE_CPP_INSTALL on and off + check-module-scan.cmake configures core-cpp top-level and as a subproject on a Clang + without clang-scan-deps, and a parent asking for modules consumer-shared/ ConsumerSmoke.hpp: the loopback echo and the core::log line the CPM and vendored consumer programs both run, so neither carries a copy consumer-cpm/ a consumer's own project, added to core-cpp with CPM: asserts that @@ -130,6 +132,8 @@ tests/ consumer-install/ a consumer of the INSTALLED package: find_package(core-cpp), core::net, and core::testing_main where the build installed it consumer-install-nested/ a parent exporting a target that links core-cpp's, as morph does + consumer-module-scan/ a C++23 parent that adds core-cpp and never asks for modules, as + Isoline does scripts/ tool-versions.py prints, installs or checks the pinned clang-format/clang-tidy clang-format.py formats or checks the C++ sources named, or --all, with the pinned build diff --git a/.agent/rules/build-and-toolchain.md b/.agent/rules/build-and-toolchain.md index d2b72ccc..f4c5e26d 100644 --- a/.agent/rules/build-and-toolchain.md +++ b/.agent/rules/build-and-toolchain.md @@ -204,6 +204,19 @@ presets, scripts and paths. `CMAKE_CXX_SCAN_FOR_MODULES` to OFF. Origin: core-cpp's first Portability run (FreeBSD 14.3, clang 19.1.7), reproduced on Linux by pointing `CMAKE_CXX_COMPILER_CLANG_SCAN_DEPS` at a missing file. + **As a subproject that default is not there**, and the root `CMakeLists.txt`'s + `cmake_minimum_required(VERSION 3.25...3.31)` sets CMP0155 NEW in core-cpp's scope, so a C++23 + parent's configure stopped at FindThreads with exit 127 (Isoline P18). The root sets + `cmake_policy(SET CMP0155 OLD)`: a directory policy, which the parent's scope does not see, under + which only a probe or target whose `CXX_SCAN_FOR_MODULES` is ON scans -- so a parent's explicit + `CMAKE_CXX_SCAN_FOR_MODULES=ON` still applies. `core-cpp.module-scan` configures both roles with + a missing scanner, and the parent that asks, which must fail. The line sits inside + `if(POLICY CMP0155)`: CMake 3.25 to 3.27 do not know the policy and refuse to configure on it, and + the hygiene check's `unguarded-policy` rule refuses a `cmake_policy(SET …)` without that guard. + **Dependencies core-cpp fetches as a subproject still scan**: each sets CMP0155 NEW with its own + `cmake_minimum_required`, and the top-level default does not reach them there. The check runs with + `CORE_CPP_FETCH_DEPS=OFF`, so a fetching subproject build on a Clang without clang-scan-deps is + unproven. - **Run clang-format and clang-tidy at the pinned version, in a build directory of their own.** An older clang-tidy is not a laxer one: it is silent about checks it does not have (a file clean under 18 arrived at CI with thirteen findings from 22). The PyPI wheel finds its diff --git a/CMakeLists.txt b/CMakeLists.txt index 81706ec5..ae4c77cd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,18 @@ # SPDX-License-Identifier: Apache-2.0 cmake_minimum_required(VERSION 3.25...3.31) +# core-cpp has no module units, so nothing in its directory scans for imports unless asked. On CMake +# 3.28 and later the range above sets CMP0155 NEW, under which every try_compile() of C++20 or later +# scans -- FindThreads among them -- and a Clang without clang-scan-deps then fails the configure +# with exit 127, even when core-cpp is a parent's subproject that never asked for modules. OLD scans +# only a target or probe whose CXX_SCAN_FOR_MODULES is ON, so a parent's CMAKE_CXX_SCAN_FOR_MODULES=ON +# is still honoured. A policy is directory state: the parent's scope keeps its own, and a dependency +# fetched here sets its own with its cmake_minimum_required(). CMake 3.25 to 3.27 know no CMP0155 and +# scan nothing unasked, so there is nothing to set; they refuse to configure on a policy they do not +# know, hence the guard (the hygiene check's unguarded-policy rule). tests/cmake/check-module-scan.cmake +# holds both roles. +if(POLICY CMP0155) + cmake_policy(SET CMP0155 OLD) +endif() # The version literal is the source of truth; a release tag must equal it. project(core-cpp diff --git a/cmake/CoreCppTopLevel.cmake b/cmake/CoreCppTopLevel.cmake index 51e4be4e..7d4fd24b 100644 --- a/cmake/CoreCppTopLevel.cmake +++ b/cmake/CoreCppTopLevel.cmake @@ -41,11 +41,11 @@ endif() set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) -# core-cpp has no module units, and core_cpp_apply_toolchain() turns scanning off on its own -# targets. A try_compile() has no such target: from C++20 on, CMake scans every probe of -# check_cxx_compiler_flag() and FindThreads, and where the compiler has no clang-scan-deps -# (FreeBSD's base clang) every probe then fails, the configure dropping the pedantic set and -# stopping at Threads. Off by default here, for the probes and the fetched dependencies alike. +# core-cpp has no module units. Its own targets and probes scan for none in either role: the root +# CMakeLists.txt sets CMP0155 OLD, and core_cpp_apply_toolchain() turns scanning off per target. A +# fetched dependency sets CMP0155 NEW again with its own cmake_minimum_required(), and from C++20 on +# its try_compile() probes then scan; where the compiler has no clang-scan-deps (FreeBSD's base +# clang) every one of them fails. This default reaches those too, so it is global, hence top-level. if(NOT DEFINED CMAKE_CXX_SCAN_FOR_MODULES) set(CMAKE_CXX_SCAN_FOR_MODULES OFF) endif() diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 607982c7..920eac35 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -376,6 +376,30 @@ set_tests_properties(core-cpp.install PROPERTIES LABELS "core-cpp;hygiene" TIMEOUT 600) +# core-cpp configures on a Clang without clang-scan-deps, top-level and as a subproject, and still +# scans when a parent asks: tests/cmake/check-module-scan.cmake says how. NOT `tree-level`: it asks +# this build's compiler. Bound from measurement: three configures, 2.5s under clang-debug; the +# bound is layering's, which configures real projects too and is as exposed to a cold runner. +add_test(NAME core-cpp.module-scan + COMMAND "${CMAKE_COMMAND}" + "-DSOURCE_DIR=${CORE_CPP_SOURCE_DIR}" + "-DWORK_DIR=${CMAKE_CURRENT_BINARY_DIR}/module-scan-check" + "-DCXX_COMPILER_ID=${CMAKE_CXX_COMPILER_ID}" + "-DCXX_FRONTEND=${CMAKE_CXX_COMPILER_FRONTEND_VARIANT}" + "-DTARGET_SYSTEM=${CMAKE_SYSTEM_NAME}" + "-DCXX_COMPILER=${CMAKE_CXX_COMPILER}" + "-DGENERATOR=${CMAKE_GENERATOR}" + "-DMAKE_PROGRAM=${CMAKE_MAKE_PROGRAM}" + "-DTOOLCHAIN_FILE=${CMAKE_TOOLCHAIN_FILE}" + "-DWITH_SYSTEMD=${CORE_CPP_WITH_SYSTEMD}" + "-DSKIP_EXIT_CODE=${CORE_CPP_SKIP_EXIT_CODE}" + -P "${CMAKE_CURRENT_SOURCE_DIR}/cmake/check-module-scan.cmake") +set_tests_properties(core-cpp.module-scan PROPERTIES + SKIP_RETURN_CODE ${CORE_CPP_SKIP_EXIT_CODE} + SKIP_REGULAR_EXPRESSION "check-module-scan: SKIPPED" + LABELS "core-cpp;hygiene" + TIMEOUT 120) + # The vendoring tool exports the file set of Part I §5 byte for byte, and refuses each way a copy # can stop being verbatim. Every case builds a git repository of its own; the tool's MODE=check # needs no git, and one case proves that by running it with an empty PATH. diff --git a/tests/cmake/check-cmake-hygiene-selftest.cmake b/tests/cmake/check-cmake-hygiene-selftest.cmake index f035534a..7fbb7164 100644 --- a/tests/cmake/check-cmake-hygiene-selftest.cmake +++ b/tests/cmake/check-cmake-hygiene-selftest.cmake @@ -19,7 +19,7 @@ endif() # A tree with nothing to refuse: "|". set(clean - "CMakeLists.txt|# SPDX-License-Identifier: Apache-2.0\noption(CORE_CPP_FOO \"x\" ON)\ninclude(CMakeDependentOption)\ninclude(\"\${CMAKE_CURRENT_LIST_DIR}/cmake/Foo.cmake\")\n" + "CMakeLists.txt|# SPDX-License-Identifier: Apache-2.0\nif(POLICY CMP0155)\n # why\n cmake_policy(SET CMP0155 OLD)\nendif()\noption(CORE_CPP_FOO \"x\" ON)\ninclude(CMakeDependentOption)\ninclude(\"\${CMAKE_CURRENT_LIST_DIR}/cmake/Foo.cmake\")\n" "cmake/Foo.cmake|# SPDX-License-Identifier: Apache-2.0\nfunction(core_cpp_foo)\nendfunction()\nset(CORE_CPP_FOO_DIR \"\" CACHE PATH \"x\")\n" "src/core/foo/CMakeLists.txt|# SPDX-License-Identifier: Apache-2.0\nadd_library(core-cpp-foo STATIC Foo.cpp)\ntarget_compile_options(core-cpp-foo PRIVATE -Wall)\n" "src/core/foo/Foo.cpp|// SPDX-License-Identifier: Apache-2.0\nnamespace core::foo {}\n" @@ -68,6 +68,9 @@ set(cases "untyped-library|src/core/foo/CMakeLists.txt|# SPDX-License-Identifier: Apache-2.0\nadd_library(x a.cpp)\n" "public-flags|src/core/foo/CMakeLists.txt|# SPDX-License-Identifier: Apache-2.0\nadd_library(x STATIC a.cpp)\ntarget_compile_options(x PUBLIC -Wall)\n" "source-glob|src/core/foo/CMakeLists.txt|# SPDX-License-Identifier: Apache-2.0\nfile(GLOB sources *.cpp)\n" + "unguarded-policy|CMakeLists.txt|# SPDX-License-Identifier: Apache-2.0\ncmake_policy(SET CMP0155 OLD)\n" + # Guarded by the wrong policy is no guard. + "unguarded-policy|CMakeLists.txt|# SPDX-License-Identifier: Apache-2.0\nif(POLICY CMP0167)\n cmake_policy(SET CMP0155 OLD)\nendif()\n" "include-by-name|CMakeLists.txt|# SPDX-License-Identifier: Apache-2.0\ninclude(CoreCppOptions)\n" "nolint|src/core/foo/Foo.cpp|// SPDX-License-Identifier: Apache-2.0\nnamespace core::foo {} // NOLINT\n" "diagnostic-pragma|src/core/foo/Foo.cpp|// SPDX-License-Identifier: Apache-2.0\n#pragma clang diagnostic ignored \"-Wshadow\"\n" diff --git a/tests/cmake/check-cmake-hygiene.cmake b/tests/cmake/check-cmake-hygiene.cmake index 1f292d05..e23d2d61 100644 --- a/tests/cmake/check-cmake-hygiene.cmake +++ b/tests/cmake/check-cmake-hygiene.cmake @@ -136,6 +136,14 @@ set(CORE_CPP_HYGIENE_PRIVATE_DIRECTORIES bsd darwin detail emscripten linux port set(CORE_CPP_HYGIENE_FORWARD_DECLARATION_REGEX "(class|struct|union|enum([ \t]+(class|struct))?)[ \t]+[A-Za-z_][A-Za-z0-9_]*([ \t]*:[ \t]*[A-Za-z_][A-Za-z0-9_:]*)?[ \t]*;") +# A rule over a line and the one before it: `cmake_policy(SET CMPnnnn …)` stands directly inside +# `if(POLICY CMPnnnn)`. cmake_minimum_required(VERSION 3.25...) admits a CMake older than the policy, +# and that CMake refuses to configure on a policy it does not know (CMP0155 is 3.28's). +set(CORE_CPP_HYGIENE_RULES ${CORE_CPP_HYGIENE_RULES} unguarded-policy) +set(CORE_CPP_HYGIENE_unguarded-policy_REASON + "a cmake_policy(SET CMPnnnn ...) is the first statement inside if(POLICY CMPnnnn): the minimum CMake this tree supports may not know the policy, and refuses to configure on one it does not know") +set(CORE_CPP_HYGIENE_POLICY_SET_REGEX "^[ \t]*cmake_policy[ \t]*\\([ \t]*SET[ \t]+(CMP[0-9]+)") + # The rule the allowlist itself answers to. set(CORE_CPP_HYGIENE_RULES ${CORE_CPP_HYGIENE_RULES} stale-allowlist) @@ -196,6 +204,7 @@ endforeach() # tests/wasi-unicode is the same kind of project for a WebAssembly guest: it sets the guest's # language mode (-fno-exceptions -fno-rtti) over everything it builds, libunicode included. core_cpp_hygiene_allow(global-cmake-variable tests/wasi-unicode/CMakeLists.txt "${_consumerProjectReason}") +core_cpp_hygiene_allow(global-cmake-variable tests/consumer-module-scan/CMakeLists.txt "${_consumerProjectReason}") core_cpp_hygiene_allow(unprefixed-function tests/consumer-cpm/CMakeLists.txt "${_consumerProjectReason}") core_cpp_hygiene_allow(unprefixed-function tests/consumer-wasm/CMakeLists.txt "${_consumerProjectReason}") core_cpp_hygiene_allow(diagnostic-pragma src/core/testing/SuppressWindowsDialogsAtStartup.cpp @@ -370,6 +379,8 @@ foreach(path IN LISTS scanned) set(expectedNamespace "core") endif() set(firstNamespaceSeen OFF) + # The last line that is neither blank nor a comment, for unguarded-policy. + set(previousStatement "") set(lineNumber 0) foreach(encoded IN LISTS lines) @@ -401,6 +412,20 @@ foreach(path IN LISTS scanned) endif() endif() + if(kind STREQUAL "cmake") + # Two ifs: arguments are expanded before a condition runs, so CMAKE_MATCH_1 is the policy + # only once the first MATCHES has set it. + if(line MATCHES "${CORE_CPP_HYGIENE_POLICY_SET_REGEX}") + set(policy "${CMAKE_MATCH_1}") + if(NOT previousStatement MATCHES "^[ \t]*if[ \t]*\\([ \t]*POLICY[ \t]+${policy}[ \t]*\\)[ \t]*$") + core_cpp_hygiene_refuse(unguarded-policy "${path}" ${lineNumber} "${line}") + endif() + endif() + if(NOT line MATCHES "^[ \t]*(#.*)?$") + set(previousStatement "${line}") + endif() + endif() + foreach(rule IN LISTS CORE_CPP_HYGIENE_RULES) if(NOT kind IN_LIST CORE_CPP_HYGIENE_${rule}_KIND) continue() diff --git a/tests/cmake/check-module-scan.cmake b/tests/cmake/check-module-scan.cmake new file mode 100644 index 00000000..74d0dece --- /dev/null +++ b/tests/cmake/check-module-scan.cmake @@ -0,0 +1,137 @@ +# SPDX-License-Identifier: Apache-2.0 +# +# core-cpp configures on a Clang that has no clang-scan-deps, as the top-level build and as a parent's +# subproject, because nothing in its scope scans for C++ module imports unless asked (the CMP0155 line +# of the root CMakeLists.txt, and CMAKE_CXX_SCAN_FOR_MODULES in cmake/CoreCppTopLevel.cmake). Without +# them every try_compile() of C++20 or later scans, FindThreads's among them, and the absent scanner +# fails the configure with exit 127. +# +# The scanner is made absent by naming one that does not exist: CMake's own lookup then never runs, +# which holds wherever this machine's Clang keeps its tools, and it is the state a parent is in whose +# Clang ships without the scanner. +# +# Usage: cmake -DSOURCE_DIR= -DWORK_DIR= -DCXX_COMPILER_ID= [-DCXX_COMPILER=] +# [-DCXX_FRONTEND=] [-DTARGET_SYSTEM=] [-DGENERATOR=] [-DMAKE_PROGRAM=] [-DTOOLCHAIN_FILE=] [-DWITH_SYSTEMD=ON|OFF] +# [-DSKIP_EXIT_CODE=] -P tests/cmake/check-module-scan.cmake + +cmake_minimum_required(VERSION 3.25) + +if(NOT DEFINED SKIP_EXIT_CODE OR SKIP_EXIT_CODE STREQUAL "") + set(SKIP_EXIT_CODE 77) +endif() +foreach(required SOURCE_DIR WORK_DIR CXX_COMPILER_ID) + if(NOT DEFINED ${required} OR "${${required}}" STREQUAL "") + message(FATAL_ERROR "check-module-scan: -D${required}=... is required") + endif() +endforeach() + +# GCC and MSVC scan with the compiler itself, so there is no separate tool to be missing; AppleClang +# has no module scanning in CMake at all. +if(NOT CXX_COMPILER_ID STREQUAL "Clang") + message(STATUS "check-module-scan: SKIPPED -- the compiler is ${CXX_COMPILER_ID}, whose scanning " + "needs no clang-scan-deps") + if(CMAKE_VERSION VERSION_GREATER_EQUAL 3.29) + cmake_language(EXIT ${SKIP_EXIT_CODE}) + endif() + return() +endif() + +# clang-cl is Clang behind the MSVC front end, and there the refused row configures too: a +# subproject that asks for modules is not refused for the absent scanner, so the passing rows could +# not show that it was consulted. Windows CI measured it; the check judges GNU-front-end Clang only. +# Emscripten's and WASI's Clang configure the refused row too, for the same want of proof. +if(TARGET_SYSTEM MATCHES "^(Emscripten|WASI)$") + message(STATUS "check-module-scan: SKIPPED -- ${TARGET_SYSTEM}'s Clang configures the refused row too, " + "so nothing here could prove the scanner was asked") + if(CMAKE_VERSION VERSION_GREATER_EQUAL 3.29) + cmake_language(EXIT ${SKIP_EXIT_CODE}) + endif() + return() +endif() +if(CXX_FRONTEND STREQUAL "MSVC") + message(STATUS "check-module-scan: SKIPPED -- clang-cl configures the refused row too, so nothing " + "here could prove the scanner was asked") + if(CMAKE_VERSION VERSION_GREATER_EQUAL 3.29) + cmake_language(EXIT ${SKIP_EXIT_CODE}) + endif() + return() +endif() + +file(REMOVE_RECURSE "${WORK_DIR}") +file(MAKE_DIRECTORY "${WORK_DIR}") + +set(scanner "${WORK_DIR}/no-scanner/clang-scan-deps") +set(configureArgs "-DCMAKE_CXX_COMPILER_CLANG_SCAN_DEPS=${scanner}") +if(GENERATOR) + list(APPEND configureArgs -G "${GENERATOR}") +endif() +if(MAKE_PROGRAM) + list(APPEND configureArgs "-DCMAKE_MAKE_PROGRAM=${MAKE_PROGRAM}") +endif() +if(CXX_COMPILER) + list(APPEND configureArgs "-DCMAKE_CXX_COMPILER=${CXX_COMPILER}") +endif() +if(TOOLCHAIN_FILE) + list(APPEND configureArgs "-DCMAKE_TOOLCHAIN_FILE=${TOOLCHAIN_FILE}") +endif() +# Each configure is afresh, so an option whose default needs a package this machine lacks +# (CORE_CPP_WITH_SYSTEMD) is forwarded as the build under test set it. +set(nestedArgs "") +set(topLevelArgs "") +if(NOT "${WITH_SYSTEMD}" STREQUAL "") + list(APPEND nestedArgs "-DNESTED_WITH_SYSTEMD=${WITH_SYSTEMD}") + list(APPEND topLevelArgs "-DCORE_CPP_WITH_SYSTEMD=${WITH_SYSTEMD}") +endif() + +# One row per configure: its name, the expected outcome, the source tree, and its own arguments +# ('|'-separated). The refused row is what proves the other two asked the question: with the +# scanner present, or not consulted, it would configure too. +set(cases + "subproject|pass|${SOURCE_DIR}/tests/consumer-module-scan|-DCORE_CPP_SOURCE_DIR=${SOURCE_DIR}|${nestedArgs}" + "top-level|pass|${SOURCE_DIR}|-DCORE_CPP_TESTING=OFF|-DCORE_CPP_WITH_TUI=OFF|-DCORE_CPP_WITH_TUI_OUTPUT=OFF|-DCORE_CPP_FETCH_DEPS=OFF|${topLevelArgs}") +# Before CMake 3.28, CMAKE_CXX_SCAN_FOR_MODULES scans nothing (module support was experimental), so a +# subproject asking for modules configures without the scanner and the refused row cannot fail there. +# The two passing rows still prove no probe needs the scanner; only the proof that it was asked is lost. +if(CMAKE_VERSION VERSION_GREATER_EQUAL 3.28) + list(APPEND cases + "subproject asking for modules|fail|${SOURCE_DIR}/tests/consumer-module-scan|-DCORE_CPP_SOURCE_DIR=${SOURCE_DIR}|-DCMAKE_CXX_SCAN_FOR_MODULES=ON|${nestedArgs}") +else() + message(STATUS "check-module-scan: the refused row is skipped -- CMake ${CMAKE_VERSION} scans for " + "modules from 3.28 on only") +endif() + +set(index 0) +foreach(case IN LISTS cases) + string(REPLACE "|" ";" fields "${case}") + list(POP_FRONT fields name expected source) + math(EXPR index "${index} + 1") + execute_process( + COMMAND "${CMAKE_COMMAND}" -S "${source}" -B "${WORK_DIR}/case-${index}" ${configureArgs} ${fields} + RESULT_VARIABLE rc OUTPUT_VARIABLE out ERROR_VARIABLE err) + if(expected STREQUAL "pass" AND NOT rc EQUAL 0) + message(FATAL_ERROR + "check-module-scan: the ${name} configure failed without clang-scan-deps (exit ${rc}):\n${out}\n${err}") + endif() + if(expected STREQUAL "fail" AND rc EQUAL 0) + message(FATAL_ERROR + "check-module-scan: the ${name} configure succeeded without clang-scan-deps, so the absent " + "scanner was never consulted and the passing cases prove nothing:\n${out}") + endif() + # What tells the outcomes apart is whether a probe ran the scanner, which the configure log + # records (CMake 3.26 on): a passing case never names it, and the refused one failed on it rather + # than on anything else. + set(configureLog "${WORK_DIR}/case-${index}/CMakeFiles/CMakeConfigureLog.yaml") + if(EXISTS "${configureLog}") + file(READ "${configureLog}" log) + string(FIND "${log}" "\"${scanner}\" -format=p1689" scanned) + if(expected STREQUAL "pass" AND NOT scanned EQUAL -1) + message(FATAL_ERROR "check-module-scan: a probe of the ${name} configure ran the scanner (${configureLog})") + endif() + if(expected STREQUAL "fail" AND scanned EQUAL -1) + message(FATAL_ERROR + "check-module-scan: the ${name} configure failed, but no probe ran the scanner, so it failed " + "for another reason (exit ${rc}):\n${out}\n${err}") + endif() + endif() + message(STATUS "check-module-scan: ${name}: as expected (exit ${rc})") +endforeach() diff --git a/tests/consumer-module-scan/CMakeLists.txt b/tests/consumer-module-scan/CMakeLists.txt new file mode 100644 index 00000000..1918df1f --- /dev/null +++ b/tests/consumer-module-scan/CMakeLists.txt @@ -0,0 +1,31 @@ +# SPDX-License-Identifier: Apache-2.0 +# +# A parent that adds core-cpp as a subproject and never asks for C++ modules: Isoline's shape. +# tests/cmake/check-module-scan.cmake configures it with a clang-scan-deps that does not exist, which +# core-cpp's configure must survive, and once more with CMAKE_CXX_SCAN_FOR_MODULES=ON, which it must +# not: the parent asked, so core-cpp's probes scan and the absent scanner fails them. +# +# cmake -S tests/consumer-module-scan -B -DCORE_CPP_SOURCE_DIR= [-DNESTED_WITH_SYSTEMD=ON|OFF] +cmake_minimum_required(VERSION 3.25...3.31) +project(core-cpp-consumer-module-scan LANGUAGES CXX) + +if(NOT EXISTS "${CORE_CPP_SOURCE_DIR}/cmake/CoreCppModules.cmake") + message(FATAL_ERROR + "consumer-module-scan: CORE_CPP_SOURCE_DIR ('${CORE_CPP_SOURCE_DIR}') is not a core-cpp source tree.") +endif() + +# A parent's own standard, as Isoline's is: below C++20 no probe scans, and the case would ask nothing. +set(CMAKE_CXX_STANDARD 23) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +# Nothing fetched: a check that runs in a ctest must not need the network. Options are normal +# variables, which core-cpp's option() calls honour (CMP0077). +set(CORE_CPP_TESTING OFF) +set(CORE_CPP_WITH_TUI OFF) +set(CORE_CPP_WITH_TUI_OUTPUT OFF) +set(CORE_CPP_FETCH_DEPS OFF) +# What the build under test chose: its default needs libsystemd, which a machine may lack. +if(DEFINED NESTED_WITH_SYSTEMD) + set(CORE_CPP_WITH_SYSTEMD ${NESTED_WITH_SYSTEMD}) +endif() +add_subdirectory("${CORE_CPP_SOURCE_DIR}" core-cpp EXCLUDE_FROM_ALL SYSTEM) From 9f13d06a3be0335ba458909d967aef5f5b97685f Mon Sep 17 00:00:00 2001 From: Christian Parpart Date: Fri, 27 Nov 2026 06:26:36 +0100 Subject: [PATCH 03/19] test: skip the seven Windows cases wine cannot hold Under wine, seven Windows cases fail on wine's own behaviour, not on a defect: wine's message tables word ERROR_FILE_NOT_FOUND and the German ERROR_INVALID_HANDLE otherwise (two systemErrorMessage cases); wine answers a name in the case it was asked for and lists a case-only rename under the old spelling (canonicalCasePath, the lettercase rename); its MSVC STL std::filesystem listing throws ERROR_MOD_NOT_FOUND (both nativeFileInfoProvider cases); and it reads the cycle counters it reports supported as 0. Each now skips under wine, detected by ntdll's wine_get_version, with its reason; native Windows still runs them. Signed-off-by: Christian Parpart --- .agent/reference/provenance.md | 3 +++ src/core/WideString_test.cpp | 12 ++++++++++++ src/core/platform/CMakeLists.txt | 13 ++++++++++++- src/core/platform/CpuCountersNative_test.cpp | 3 +++ src/core/platform/FileInfoProvider_test.cpp | 7 +++++++ src/core/platform/FileSystem_test.cpp | 4 ++++ src/core/platform/PathUtils_test.cpp | 3 +++ src/core/platform/PlatformTestSupport.hpp | 16 ++++++++++++++++ .../platform/posix/PlatformTestSupport.cpp | 14 ++++++++++++++ .../platform/windows/PlatformTestSupport.cpp | 19 +++++++++++++++++++ 10 files changed, 93 insertions(+), 1 deletion(-) create mode 100644 src/core/platform/PlatformTestSupport.hpp create mode 100644 src/core/platform/posix/PlatformTestSupport.cpp create mode 100644 src/core/platform/windows/PlatformTestSupport.cpp diff --git a/.agent/reference/provenance.md b/.agent/reference/provenance.md index 1ae15c25..164d819b 100644 --- a/.agent/reference/provenance.md +++ b/.agent/reference/provenance.md @@ -224,6 +224,9 @@ others in notes. | `src/core/net/windows/SshAgentEndpoint_test.cpp` | origin: core-cpp | - | - | defaultSshAgentEndpoint naming the Win32-OpenSSH pipe | | `src/core/PosixRandom.cpp` | origin: core-cpp | - | - | `getentropy()` in chunks of at most 256 bytes: Linux, Apple, the BSDs, illumos and Emscripten; its header is chosen by `__has_include()` (Apple, illumos), else `` | | `src/core/platform/Clock.cpp` | origin: core-cpp | - | - | `defaultSystemWallClock()`'s instance, out of line so that a shared build has one | +| `src/core/platform/PlatformTestSupport.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): `runsUnderWine` for the platform tests | +| `src/core/platform/posix/PlatformTestSupport.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): `runsUnderWine` on POSIX | +| `src/core/platform/windows/PlatformTestSupport.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): `runsUnderWine` on Windows | | `src/core/testing/windows/SuppressWindowsDialogs_test.cpp` | origin: core-cpp | - | - | 0.3.0: reads back from WerGetFlags that suppressWindowsDialogs() asked Windows Error Reporting for no UI | | `src/core/net/CallbackAllocation_test.cpp` | origin: core-cpp | - | - | 0.3.0 review: a drain-step callback that queues nothing costs no allocation, measured by replacing the global allocation functions, which is why it is a binary of its own | | `src/core/net/CompletionClaim_test.cpp` | origin: core-cpp | - | - | 0.4.0: the claim a frame-free completion queues for a chain nobody owns -- counted, armed, holding no reference -- and its free at teardown and take-back; a `[bench]` case for the completion path | diff --git a/src/core/WideString_test.cpp b/src/core/WideString_test.cpp index 619e0b76..c9d664f5 100644 --- a/src/core/WideString_test.cpp +++ b/src/core/WideString_test.cpp @@ -68,6 +68,13 @@ class ScopedThreadLanguages != 0; } +/// @return Whether the process runs under wine, whose ntdll alone exports `wine_get_version`. +[[nodiscard]] bool runsUnderWine() +{ + auto* const ntdll = GetModuleHandleW(L"ntdll.dll"); + return ntdll != nullptr && GetProcAddress(ntdll, "wine_get_version") != nullptr; +} + } // namespace TEST_CASE("toUtf8 converts empty text to empty text", "[WideString][windows]") @@ -141,6 +148,9 @@ TEST_CASE("toUtf16 refuses text that is not UTF-8", "[WideString][windows]") TEST_CASE("systemErrorMessage spells the system's message without its line break", "[WideString][windows]") { + if (runsUnderWine()) + SKIP("wine's message tables word the system's messages otherwise (File not found. for " + "ERROR_FILE_NOT_FOUND)"); if (!hasMessagesIn(MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US))) SKIP("the system has no US English messages to compare with"); auto const english = ScopedThreadLanguages { L"en-US\0" }; @@ -151,6 +161,8 @@ TEST_CASE("systemErrorMessage spells the system's message without its line break TEST_CASE("systemErrorMessage spells a message beyond ASCII in UTF-8", "[WideString][windows]") { + if (runsUnderWine()) + SKIP("wine's German message table words ERROR_INVALID_HANDLE otherwise"); // The German message holds a U+00FC, which FormatMessageA() spells in the ANSI code page: on a // CP-1252 host as the byte 0xFC, which UTF-8 has no reading for. The thread asks for German, as // a German user's does, and gets it where the system has it. diff --git a/src/core/platform/CMakeLists.txt b/src/core/platform/CMakeLists.txt index 1034826d..34661ba5 100644 --- a/src/core/platform/CMakeLists.txt +++ b/src/core/platform/CMakeLists.txt @@ -165,9 +165,18 @@ if(LINUX AND CORE_CPP_WITH_SYSTEMD AND TARGET core-cpp-platform) target_include_directories(core-cpp-platform PRIVATE ${_coreCppPlatformPowerIncludes}) endif() +# runsUnderWine() for the platform tests: one definition per platform, the POSIX one under Emscripten. +if(WIN32) + set(_coreCppPlatformTestSupport windows/PlatformTestSupport.cpp) +else() + set(_coreCppPlatformTestSupport posix/PlatformTestSupport.cpp) +endif() + core_cpp_add_test(platform SOURCES ${_coreCppPlatformSubsetTests} + PlatformTestSupport.hpp + ${_coreCppPlatformTestSupport} CpuCountersNative_test.cpp FileSystem_test.cpp LinuxPerfPlan_test.cpp @@ -187,4 +196,6 @@ core_cpp_add_test(platform windows/SystemPipeInheritance_test.cpp windows/WideEnvironment_test.cpp SOURCES_EMSCRIPTEN - ${_coreCppPlatformSubsetTests}) + ${_coreCppPlatformSubsetTests} + PlatformTestSupport.hpp + ${_coreCppPlatformTestSupport}) diff --git a/src/core/platform/CpuCountersNative_test.cpp b/src/core/platform/CpuCountersNative_test.cpp index 3664b695..6616f3b4 100644 --- a/src/core/platform/CpuCountersNative_test.cpp +++ b/src/core/platform/CpuCountersNative_test.cpp @@ -1,5 +1,6 @@ // SPDX-License-Identifier: Apache-2.0 #include +#include #include @@ -125,6 +126,8 @@ class SimulatedSource final: public ICpuCounterSource TEST_CASE("supported measures grow with the work", "[cpucounters]") { + if (core::platform::test::runsUnderWine()) + SKIP("wine reports the cycle counters supported but reads them as 0"); auto const source = makeDefaultCpuCounterSource(); auto anySupported = false; for (auto const counter: AllCpuCounters) diff --git a/src/core/platform/FileInfoProvider_test.cpp b/src/core/platform/FileInfoProvider_test.cpp index 9da00e8c..d23fd49f 100644 --- a/src/core/platform/FileInfoProvider_test.cpp +++ b/src/core/platform/FileInfoProvider_test.cpp @@ -2,6 +2,7 @@ #include #include #include +#include #include #include @@ -48,6 +49,9 @@ struct TempDir TEST_CASE("nativeFileInfoProvider is this platform's own provider, and lists a directory", "[platform]") { + if (core::platform::test::runsUnderWine()) + SKIP("under wine the listing throws ERROR_MOD_NOT_FOUND (Module not found) out of the MSVC STL " + "std::filesystem"); // The implementations are private (posix/, windows/); a composition root reaches them only // through the factory. Every POSIX system, and Emscripten, gets the lstat(2) one. auto const provider = nativeFileInfoProvider(); @@ -73,6 +77,9 @@ TEST_CASE("nativeFileInfoProvider is this platform's own provider, and lists a d TEST_CASE("nativeFileInfoProvider lists a directory beyond ASCII by its UTF-8 name", "[platform]") { + if (core::platform::test::runsUnderWine()) + SKIP("under wine the listing throws ERROR_MOD_NOT_FOUND (Module not found) out of the MSVC STL " + "std::filesystem"); // The provider is handed UTF-8 and answers UTF-8. On Windows it read the name it was handed in // the ANSI code page, so it listed a directory that does not exist and answered nothing. TempDir const tmp; diff --git a/src/core/platform/FileSystem_test.cpp b/src/core/platform/FileSystem_test.cpp index e22bcd52..d6d4bbdb 100644 --- a/src/core/platform/FileSystem_test.cpp +++ b/src/core/platform/FileSystem_test.cpp @@ -1,5 +1,6 @@ // SPDX-License-Identifier: Apache-2.0 #include +#include #include #include @@ -649,6 +650,9 @@ TEST_CASE("rename reports why the recase failed, not why the first attempt did", TEST_CASE("rename changes the lettercase of a name, whatever the volume", "[FileSystem]") { + if (core::platform::test::runsUnderWine()) + SKIP("wine lists a case-only rename under the old spelling (foo, not Foo) on its case-folding layer " + "over Linux"); // The case above can only run on a case-sensitive volume: it needs `foo` and `Foo` to be two // entries so the direct rename fails over the destination. That left the two-hop recase with // no case at all on the volumes it was written for -- its whole point is that a case-only diff --git a/src/core/platform/PathUtils_test.cpp b/src/core/platform/PathUtils_test.cpp index 40bae3e4..3553e77b 100644 --- a/src/core/platform/PathUtils_test.cpp +++ b/src/core/platform/PathUtils_test.cpp @@ -1,5 +1,6 @@ // SPDX-License-Identifier: Apache-2.0 #include +#include #include @@ -93,6 +94,8 @@ TEST_CASE("canonicalCasePath.nonexistent_path_falls_back_to_normalize", "[platfo #ifdef _WIN32 TEST_CASE("canonicalCasePath.corrects_case_and_uppercases_drive", "[platform]") { + if (core::platform::test::runsUnderWine()) + SKIP("wine answers a name in the case it was asked for, not the case on disk"); namespace fs = std::filesystem; auto const dirName = std::string("CoreCanonCaseTEST_dir"); auto const dir = fs::temp_directory_path() / dirName; diff --git a/src/core/platform/PlatformTestSupport.hpp b/src/core/platform/PlatformTestSupport.hpp new file mode 100644 index 00000000..c93f1dfd --- /dev/null +++ b/src/core/platform/PlatformTestSupport.hpp @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// The platform questions the platform tests share. Test-only; never part of the module. + +namespace core::platform::test +{ + +/// Whether this process runs under wine rather than on Windows or a POSIX system. Defined per +/// platform (`posix/PlatformTestSupport.cpp`, `windows/PlatformTestSupport.cpp`). A case uses it to +/// skip where wine differs from Windows in a way the case cannot tell from a defect, and says how. +/// A @c bool because the name asks it. +[[nodiscard]] bool runsUnderWine() noexcept; + +} // namespace core::platform::test diff --git a/src/core/platform/posix/PlatformTestSupport.cpp b/src/core/platform/posix/PlatformTestSupport.cpp new file mode 100644 index 00000000..3a8bf342 --- /dev/null +++ b/src/core/platform/posix/PlatformTestSupport.cpp @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The POSIX half of PlatformTestSupport.hpp's platform questions: no POSIX process runs under wine. +#include + +namespace core::platform::test +{ + +bool runsUnderWine() noexcept +{ + return false; +} + +} // namespace core::platform::test diff --git a/src/core/platform/windows/PlatformTestSupport.cpp b/src/core/platform/windows/PlatformTestSupport.cpp new file mode 100644 index 00000000..9539c1c3 --- /dev/null +++ b/src/core/platform/windows/PlatformTestSupport.cpp @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The Windows half of PlatformTestSupport.hpp's platform questions. Wine's ntdll exports +// `wine_get_version`, and no Windows ntdll does: that export is wine's own documented way for a +// program to tell. +#include + +#include + +namespace core::platform::test +{ + +bool runsUnderWine() noexcept +{ + auto* const ntdll = GetModuleHandleW(L"ntdll.dll"); + return ntdll != nullptr && GetProcAddress(ntdll, "wine_get_version") != nullptr; +} + +} // namespace core::platform::test From 207605567b5b2575f7d9ea9cd12642f2e05764e1 Mon Sep 17 00:00:00 2001 From: Christian Parpart Date: Thu, 26 Nov 2026 15:14:56 +0100 Subject: [PATCH 04/19] feat(fs): descriptors resolved beneath their directory on POSIX and Windows, offloaded to an injected executor Descriptor vocabulary, rights, path policy and the in-memory model. core::fs is a new module (DEPS base log async platform, PLATFORMS native, gated by CORE_CPP_WITH_FS, default ON): FsErrorCode with one code per WASI 0.3 filesystem error-code case plus WouldBlock, and the per-OS tables that classify errno, Win32 and NTSTATUS codes; PathPolicy rows for POSIX and Windows names; the IDescriptorFileSystem/IDescriptor/IDirectoryStream interfaces; the rights table and checkOpenRights every implementation enforces; the path planner and symlink splice both resolvers share; and testing::InMemoryDescriptorFileSystem, which resolves and enforces through that same code and suspends through async::offload. The contract suite runs over it; the native descriptors join in the next task. feat(async): async::offload runs a blocking call on an injected executor and resumes on the caller's. The stop token is read once, before the hop; once the work has run, its result is returned. Configure now names the option when an enabled module's directory is missing from a vendored copy, and the vendored smoke carries fs. The layering scan skips test-only *TestSupport.hpp headers, as it skips the tests. Native descriptors on POSIX and Windows, offloaded to an injected executor. makeNativeDescriptorFileSystem(home, blocking, wallClock, random, options) builds the operating system's IDescriptorFileSystem, or answers Invalid for a maxReadChunk of 0. Every system call runs inside async::offload on the blocking executor, and the caller resumes on home. Each offloaded job captures the descriptor's detail::OwnedHandle by shared ownership, so a descriptor dropped under a parked read leaves the read its handle and never lets it reach a file that reused the number (C2). Whoever lets go of a handle last, the close is queued on the blocking executor, never made on the caller's loop. Rights are checked from rightsTable() first, inside the job. A name is one component in this release, and never holds what the kernel splits on (`/`; `\`, `/` and `:` on Windows) whatever PathPolicy an embedder overrides, so the kernel resolves exactly one name beneath a held directory and never follows a final link. POSIX: pread/pwrite; append through pwritev2(RWF_APPEND) on Linux (reopening through /proc/self/fd where the flag is refused), elsewhere through a second O_APPEND handle opened by the same name beneath the held parent, carrying the first's sync flags, and checked by (st_dev, st_ino); posix_fadvise, or F_RDADVISE on Apple; fdatasync/fsync, or F_FULLFSYNC on Apple, with fsync where either fails; ftruncate; futimens with UTIME_NOW; opens with O_NONBLOCK, cleared once open, so a FIFO never stalls the pool. The per-OS calls sit behind posix/PosixSystem.hpp, one CMake-chosen source each (posix/, darwin/, linux/). Windows: NtCreateFile relative to the held directory with FILE_OPEN_REPARSE_POINT and OBJ_DONT_REPARSE; never an overwrite disposition, so a link is classified before anything is truncated, by handle; ReadFile and WriteFile at an OVERLAPPED offset; append through a ReOpenFile(FILE_APPEND_DATA) handle; times, size and deletion through SetFileInformationByHandle, SetToNow read from the injected wall clock on the caller's thread. linkAt, readlinkAt, renameAt, symlinkAt and following a link answer Unsupported here; the directory-containment commit implements them. The module links ntdll there. The metadata hash is HMAC-SHA-256 over (device, file id, size, mtime, ctime), keyed by a 32-byte secret drawn from the injected IRandom at construction, truncated to 128 bits. Tests: every implemented operation parks on the blocking executor and resumes on home; a dropped descriptor's parked read returns its own bytes; the last close is queued on blocking; a name with a kernel separator is Invalid under an overriding policy; maxSymlinkHops ends in Loop; two secrets give two hashes. The contract suite runs the native descriptors beside the in-memory model, with cases for stat, setTimes and SetToNow, advise, a positioned write after an append, the metadata hash, the open dispositions, a final link followed only where asked, and an open of a link that changes neither the link nor its target. Beneath-only resolution on POSIX with openat2 and a component walker. Every *At path of a POSIX native descriptor is now resolved beneath the descriptor, several components deep, and never by the kernel from anywhere else. - detail::walkBeneath is the one walk every resolver runs: `..` never climbs above the root, a final link is followed only where the call or a trailing `/` says so, links are spliced with spliceSymlink and counted against maxSymlinkHops (Loop), and a name holding a kernel separator is Invalid. It moves over an IBeneathCursor, which holds each directory open. - posix/PosixPathWalk: the cursor over directory descriptors, each opened beneath the one before with O_DIRECTORY|O_NOFOLLOW (O_PATH where the system has it). A link met on the way is read with readlinkat; one that became a directory again is looked at again. - linux/Openat2: openat2(RESOLVE_BENEATH|RESOLVE_NO_MAGICLINKS) opens everything before the final name in one call. EXDEV is NotPermitted, EAGAIN is retried 8 times and then that call walks, and a construction-time probe with an invalid descriptor tells EBADF from ENOSYS/EPERM. The system call is a seam (IOpenat2System) a test scripts. - BeneathDefault.cpp, one per build (linux/, posix/, windows/), says what BeneathStrategy::Best is: openat2 on Linux, the walk elsewhere. The opener lives in the file system's context. - The final call always acts without following, in the directory the walk holds: fstatat, utimensat and readlinkat with AT_SYMLINK_NOFOLLOW, openat with O_NOFOLLOW (and O_DIRECTORY for `name/`), linkat with flags 0; a final `.` or `..` acts on the held directory. linkAt and renameAt resolve both sides first. - The in-memory model answers metadataHashAt. Tests: DescriptorEscape_test.cpp's table runs every *At operation x {Follow, NoFollow} x five escape shapes x {in-memory, native Best, native ComponentWalk} against outside decoys; a symlink cycle ends in Loop; a directory raced against an outward link by a swapper thread never yields a descriptor outside. The walker and openat2 are also swapped at a chosen step through hooked seams, and /proc's magic links are refused. Contract cases that need a multi-component path now run natively too (Windows joins with the directory-containment commit). The in-memory model resolves through the shared walk. The in-memory model walked paths with a loop of its own, which carried its own 40-hop limit and its own rule for `..` at the root: two copies of the rules that must not drift from the native descriptors'. It now resolves through detail::walkBeneath over a cursor of inodes, so the hop limit (DefaultMaxSymlinkHops), `..` at the root, the trailing-slash rules and the splice are the walk's alone. A scripted cursor shows the walk enforces the hop limit and `..` at the root without any help from the cursor. Beneath-only resolution on Windows through NtCreateFile. Windows resolves a path one component at a time over held directory handles, as POSIX's walker does: each name is opened with NtCreateFile relative to the handle before it, as the reparse point itself and with OBJ_DONT_REPARSE, so a directory swapped for a link is met as a link. Only a relative symbolic link is followed, its target read with FSCTL_GET_REPARSE_POINT and spliced by the shared walk; a junction, a mount point and every other name surrogate is NotPermitted. A reparse point that names nothing else (a cloud placeholder, a deduplicated file) is opened again by the handle that was checked, through its filter, so its data is the filter's rather than the stub's. linkAt and renameAt name the new entry through NtSetInformationFile with the new directory's handle as RootDirectory (FileRenameInformationEx with POSIX semantics where the file system has it); symlinkAt writes the reparse point itself, as a directory link where the target is a directory; readlinkAt reads it. No call takes a path. The decisions about reparse points are behind an NT seam and tested with scripted answers, and the Windows native descriptors now run the whole contract and escape suites. Streamed directory reads and object identity. readDirectory opens a stream of its own over the directory, which reads it in bounded batches, one offload each, and answers next() from the batch in hand: getdents64 records into a fixed 64 KiB buffer on Linux, fdopendir and readdir elsewhere on POSIX, and GetFileInformationByHandleEx(FileIdBothDirectoryInfo) into a 64 KiB buffer on a handle opened again through openAgain on Windows. "." and ".." are never entries, an entry whose type the system does not report is stat'ed without following, and a name that is not UTF-8 is IllegalByteSequence for that entry alone. The in-memory model streams by key, a batch at a time, through the same shared stream. isSameObject compares (st_dev, st_ino), or the volume serial and the 128-bit file id; a descriptor of another file system is never the same object. Also in this commit: - a path ending in a dot names the directory itself - a malformed name is Invalid on Windows before an operation not implemented there answers Unsupported - an open the parent may not make is NotPermitted before its flags are judged - a reparse point met without following is Loop on Windows - the last owner of a handle closes it inline when its queued close cannot be allocated - Linux appends at the end through its own handle where RWF_APPEND is refused - no open waits on its way in, a leased file is waited for, and macOS's Create on a directory is IsDirectory - Create opens no directory on any POSIX system, and the fs tests read an error only from a failure - the lease retry opens the name the open was made with - directory streams end an empty FAT root, keep a readdir failure, and refuse impossible names - the directory memory test outgrows its budget on every standard library - open directories on FAT, which answers no FileAttributeTagInfo - a NoFollow final link is Loop on FreeBSD too - Windows reads of a directory are IsDirectory, a stopped link is Loop - spell openat2's ABI locally instead of requiring new headers Signed-off-by: Christian Parpart --- .agent/reference/provenance.md | 78 + .agent/rules/testing.md | 6 + .github/workflows/build.yml | 2 +- cmake/CoreCppModules.cmake | 20 + cmake/CoreCppOptions.cmake | 1 + docs/getting-started/options.md | 1 + docs/vendoring.md | 6 +- src/core/async/CMakeLists.txt | 2 + src/core/async/Offload.hpp | 86 ++ src/core/async/Offload_test.cpp | 114 ++ src/core/fs/CMakeLists.txt | 144 ++ src/core/fs/Descriptor.hpp | 396 +++++ src/core/fs/DescriptorContract_test.cpp | 857 +++++++++++ src/core/fs/DescriptorEscape_test.cpp | 367 +++++ src/core/fs/DescriptorTestSupport.hpp | 622 ++++++++ src/core/fs/DirectoryStream_test.cpp | 418 ++++++ src/core/fs/FsError.cpp | 46 + src/core/fs/FsError.hpp | 168 +++ src/core/fs/FsError_test.cpp | 201 +++ src/core/fs/NativeDescriptor_test.cpp | 364 +++++ src/core/fs/NativeFileSystem.hpp | 104 ++ src/core/fs/PathPolicy.cpp | 67 + src/core/fs/PathPolicy.hpp | 67 + src/core/fs/Rights.cpp | 107 ++ src/core/fs/Rights.hpp | 87 ++ src/core/fs/bsd/ErrnoTable.cpp | 39 + src/core/fs/darwin/PosixSystem.cpp | 165 +++ src/core/fs/detail/DirectoryStream.cpp | 40 + src/core/fs/detail/DirectoryStream.hpp | 61 + src/core/fs/detail/NativeSupport.cpp | 161 ++ src/core/fs/detail/NativeSupport.hpp | 191 +++ src/core/fs/detail/OwnedHandle.hpp | 144 ++ src/core/fs/detail/PathWalk.cpp | 378 +++++ src/core/fs/detail/PathWalk.hpp | 194 +++ src/core/fs/detail/PathWalk_test.cpp | 274 ++++ src/core/fs/detail/ResolveBeneath.hpp | 78 + src/core/fs/linux/Append.cpp | 111 ++ src/core/fs/linux/Append.hpp | 31 + src/core/fs/linux/Append_test.cpp | 55 + src/core/fs/linux/BeneathDefault.cpp | 35 + src/core/fs/linux/DescriptorEscape_test.cpp | 63 + src/core/fs/linux/DirectoryRead.cpp | 118 ++ src/core/fs/linux/DirectoryRead.hpp | 28 + src/core/fs/linux/DirectoryRead_test.cpp | 129 ++ src/core/fs/linux/Lease.cpp | 52 + src/core/fs/linux/Lease_test.cpp | 101 ++ src/core/fs/linux/Openat2.cpp | 106 ++ src/core/fs/linux/Openat2.hpp | 74 + src/core/fs/linux/Openat2_test.cpp | 196 +++ src/core/fs/posix/Append.cpp | 76 + src/core/fs/posix/BeneathDefault.cpp | 43 + src/core/fs/posix/DirectoryEntries.cpp | 96 ++ src/core/fs/posix/DirectoryEntries_test.cpp | 79 + src/core/fs/posix/DirectoryRead.cpp | 135 ++ src/core/fs/posix/DirectoryRead.hpp | 54 + .../fs/posix/DirectoryStreamMemory_test.cpp | 102 ++ src/core/fs/posix/ErrnoRows.hpp | 62 + src/core/fs/posix/ErrnoTable.cpp | 37 + src/core/fs/posix/Lease.cpp | 22 + src/core/fs/posix/NativePathPolicy.cpp | 14 + .../fs/posix/OwnedHandleAllocation_test.cpp | 61 + src/core/fs/posix/PosixDescriptor.cpp | 904 ++++++++++++ src/core/fs/posix/PosixDescriptor_test.cpp | 76 + src/core/fs/posix/PosixPathWalk.cpp | 183 +++ src/core/fs/posix/PosixPathWalk.hpp | 71 + src/core/fs/posix/PosixPathWalk_test.cpp | 208 +++ src/core/fs/posix/PosixSystem.cpp | 134 ++ src/core/fs/posix/PosixSystem.hpp | 133 ++ .../testing/InMemoryDescriptorFileSystem.cpp | 1025 +++++++++++++ .../testing/InMemoryDescriptorFileSystem.hpp | 94 ++ .../InMemoryDescriptorFileSystem_test.cpp | 118 ++ src/core/fs/windows/BeneathDefault.cpp | 18 + src/core/fs/windows/DescriptorEscape_test.cpp | 524 +++++++ src/core/fs/windows/DirectoryRecords.cpp | 93 ++ src/core/fs/windows/DirectoryRecords.hpp | 31 + src/core/fs/windows/DirectoryRecords_test.cpp | 289 ++++ src/core/fs/windows/NativePathPolicy.cpp | 14 + src/core/fs/windows/NtFile.hpp | 265 ++++ src/core/fs/windows/NtStatusTable.cpp | 81 + src/core/fs/windows/ReparsePoint.cpp | 228 +++ src/core/fs/windows/ReparsePoint.hpp | 102 ++ src/core/fs/windows/Win32ErrorTable.cpp | 65 + src/core/fs/windows/WindowsDescriptor.cpp | 1312 +++++++++++++++++ src/core/fs/windows/WindowsPathWalk.cpp | 311 ++++ src/core/fs/windows/WindowsPathWalk.hpp | 234 +++ src/core/fs/windows/WindowsPathWalk_test.cpp | 343 +++++ tests/cmake/check-layering.cmake | 30 +- tests/consumer-vendored/CMakeLists.txt | 6 +- 88 files changed, 14815 insertions(+), 13 deletions(-) create mode 100644 src/core/async/Offload.hpp create mode 100644 src/core/async/Offload_test.cpp create mode 100644 src/core/fs/CMakeLists.txt create mode 100644 src/core/fs/Descriptor.hpp create mode 100644 src/core/fs/DescriptorContract_test.cpp create mode 100644 src/core/fs/DescriptorEscape_test.cpp create mode 100644 src/core/fs/DescriptorTestSupport.hpp create mode 100644 src/core/fs/DirectoryStream_test.cpp create mode 100644 src/core/fs/FsError.cpp create mode 100644 src/core/fs/FsError.hpp create mode 100644 src/core/fs/FsError_test.cpp create mode 100644 src/core/fs/NativeDescriptor_test.cpp create mode 100644 src/core/fs/NativeFileSystem.hpp create mode 100644 src/core/fs/PathPolicy.cpp create mode 100644 src/core/fs/PathPolicy.hpp create mode 100644 src/core/fs/Rights.cpp create mode 100644 src/core/fs/Rights.hpp create mode 100644 src/core/fs/bsd/ErrnoTable.cpp create mode 100644 src/core/fs/darwin/PosixSystem.cpp create mode 100644 src/core/fs/detail/DirectoryStream.cpp create mode 100644 src/core/fs/detail/DirectoryStream.hpp create mode 100644 src/core/fs/detail/NativeSupport.cpp create mode 100644 src/core/fs/detail/NativeSupport.hpp create mode 100644 src/core/fs/detail/OwnedHandle.hpp create mode 100644 src/core/fs/detail/PathWalk.cpp create mode 100644 src/core/fs/detail/PathWalk.hpp create mode 100644 src/core/fs/detail/PathWalk_test.cpp create mode 100644 src/core/fs/detail/ResolveBeneath.hpp create mode 100644 src/core/fs/linux/Append.cpp create mode 100644 src/core/fs/linux/Append.hpp create mode 100644 src/core/fs/linux/Append_test.cpp create mode 100644 src/core/fs/linux/BeneathDefault.cpp create mode 100644 src/core/fs/linux/DescriptorEscape_test.cpp create mode 100644 src/core/fs/linux/DirectoryRead.cpp create mode 100644 src/core/fs/linux/DirectoryRead.hpp create mode 100644 src/core/fs/linux/DirectoryRead_test.cpp create mode 100644 src/core/fs/linux/Lease.cpp create mode 100644 src/core/fs/linux/Lease_test.cpp create mode 100644 src/core/fs/linux/Openat2.cpp create mode 100644 src/core/fs/linux/Openat2.hpp create mode 100644 src/core/fs/linux/Openat2_test.cpp create mode 100644 src/core/fs/posix/Append.cpp create mode 100644 src/core/fs/posix/BeneathDefault.cpp create mode 100644 src/core/fs/posix/DirectoryEntries.cpp create mode 100644 src/core/fs/posix/DirectoryEntries_test.cpp create mode 100644 src/core/fs/posix/DirectoryRead.cpp create mode 100644 src/core/fs/posix/DirectoryRead.hpp create mode 100644 src/core/fs/posix/DirectoryStreamMemory_test.cpp create mode 100644 src/core/fs/posix/ErrnoRows.hpp create mode 100644 src/core/fs/posix/ErrnoTable.cpp create mode 100644 src/core/fs/posix/Lease.cpp create mode 100644 src/core/fs/posix/NativePathPolicy.cpp create mode 100644 src/core/fs/posix/OwnedHandleAllocation_test.cpp create mode 100644 src/core/fs/posix/PosixDescriptor.cpp create mode 100644 src/core/fs/posix/PosixDescriptor_test.cpp create mode 100644 src/core/fs/posix/PosixPathWalk.cpp create mode 100644 src/core/fs/posix/PosixPathWalk.hpp create mode 100644 src/core/fs/posix/PosixPathWalk_test.cpp create mode 100644 src/core/fs/posix/PosixSystem.cpp create mode 100644 src/core/fs/posix/PosixSystem.hpp create mode 100644 src/core/fs/testing/InMemoryDescriptorFileSystem.cpp create mode 100644 src/core/fs/testing/InMemoryDescriptorFileSystem.hpp create mode 100644 src/core/fs/testing/InMemoryDescriptorFileSystem_test.cpp create mode 100644 src/core/fs/windows/BeneathDefault.cpp create mode 100644 src/core/fs/windows/DescriptorEscape_test.cpp create mode 100644 src/core/fs/windows/DirectoryRecords.cpp create mode 100644 src/core/fs/windows/DirectoryRecords.hpp create mode 100644 src/core/fs/windows/DirectoryRecords_test.cpp create mode 100644 src/core/fs/windows/NativePathPolicy.cpp create mode 100644 src/core/fs/windows/NtFile.hpp create mode 100644 src/core/fs/windows/NtStatusTable.cpp create mode 100644 src/core/fs/windows/ReparsePoint.cpp create mode 100644 src/core/fs/windows/ReparsePoint.hpp create mode 100644 src/core/fs/windows/Win32ErrorTable.cpp create mode 100644 src/core/fs/windows/WindowsDescriptor.cpp create mode 100644 src/core/fs/windows/WindowsPathWalk.cpp create mode 100644 src/core/fs/windows/WindowsPathWalk.hpp create mode 100644 src/core/fs/windows/WindowsPathWalk_test.cpp diff --git a/.agent/reference/provenance.md b/.agent/reference/provenance.md index 164d819b..bb1969b8 100644 --- a/.agent/reference/provenance.md +++ b/.agent/reference/provenance.md @@ -120,6 +120,8 @@ others in notes. | `src/core/async/Join.hpp` | origin: core-cpp | - | - | the runner, join state and awaiter that `whenAll` and `whenAny` are both written over, collapsed out of contour's two near-identical copies (Task B1). A policy supplies the one step that differs -- what a child finishing does to the shared state -- plus the token each child observes and the parent-cancellation bridge, if any. Public file, `core::async::detail` throughout, like `UniqueCoroHandle.hpp` | | `src/core/async/KeyedStrands.hpp` | origin: core-cpp | - | - | 0.4.0: one strand per key, made lazily and reclaimed when idle, with `runningHere(key)`, `runningAnyHere()` and `waitIdle()`. The requirements are morph's `morph::exec::detail::StrandExecutor` (`include/morph/core/strand.hpp` at `b6377c9508d5e5b80f607dcc6ab55596a9b3e5a5`, PR #806)'s; the design is new -- a key's strand is a coroutine pump over any `IExecutor` rather than a `std::function` queue, and a coroutine that parked while its key went idle comes back to the key through the registry rather than to a stale strand | | `src/core/async/KeyedStrands_test.cpp` | origin: core-cpp | - | - | 0.4.0. Per-key queries, FIFO, idle reclamation, the reclaimed-while-parked return to the key, destruction, and -- where threads exist -- per-key exclusion with cross-key concurrency, a rendezvous only concurrency satisfies, and `waitIdle` over work that submits work | +| `src/core/async/Offload.hpp` | origin: core-cpp | - | - | 0.24.0 (P13). Runs a blocking call on an injected executor and resumes on the caller's; the stop token is read once, before the hop | +| `src/core/async/Offload_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13). Over two `ManualExecutor`s: where the work runs, where the caller resumes, a stop before and during the hop, a throw | | `src/core/async/ParkedWork.hpp` | LASTRADA-Software/fastcached | `src/FastCache/Async/ParkedWork.hpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | camelBack; `Detail::UnownedRootOf` and `ParkedWorkFor` moved here from `Task.hpp` as `unownedRootOf` and `parkedWorkFor`, so the file that defines `ParkedWork::abandon` is the one that decides it, and `ResumeOn` and `AsyncQueue` need no `Task.hpp`; the promise probe is the `CarriesUnownedRoot` concept rather than `std::is_base_of_v`, which is what lets the `whenAll` and `whenAny` runners carry the answer too; `Parked` gains `explicit operator bool` | | `src/core/async/ParkedWork_test.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Async/ParkedWork_test.cpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | only the cases that need no event loop: upstream's reactor-driven teardown properties belong to Task B4. A file-local `QueuedExecutor` stands in for the loop, a frame sentinel counts destructions so no case rests on a sanitizer noticing, and the #1041 compile-time check is here with its negative control -- written over a non-virtual base, because GCC's `-Woverloaded-virtual` refuses the hiding shape on `IExecutor` outright. New: `unownedRoot` reaching a coroutine parked under a `whenAll` and under a `whenAny` runner; also built over the `StopToken` fallback | | `src/core/async/ResumeOn.hpp` | LASTRADA-Software/fastcached | `src/FastCache/Async/ResumeOn.hpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | camelBack; includes `ParkedWork.hpp` rather than `Task.hpp` | @@ -152,6 +154,82 @@ others in notes. | `src/core/codec/Stream.cpp` | contour-terminal/contour | `src/vtbackend/state/StateCodec.cpp` | `3334cdeb80789e8999b8f199501debfc1af657da` | `StateWriter`/`StateReader` without the stream header, as `Writer`/`Reader` | | `src/core/codec/Stream.hpp` | contour-terminal/contour | `src/vtbackend/state/StateCodec.hpp` | `3334cdeb80789e8999b8f199501debfc1af657da` | `StateWriter`/`StateReader` without the stream header, as `Writer`/`Reader` | | `src/core/codec/Stream_test.cpp` | origin: core-cpp | - | - | - | +| `src/core/fs/CMakeLists.txt` | origin: core-cpp | - | - | 0.24.0 (P13): the module, its per-OS error tables and its test binary | +| `src/core/fs/Descriptor.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): `IDescriptorFileSystem`, `IDescriptor`, `IDirectoryStream` and their vocabulary, shaped after WASI 0.3 `wasi:filesystem` | +| `src/core/fs/DescriptorContract_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): what every descriptor owes its caller, per fixture kind | +| `src/core/fs/DescriptorEscape_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): no `*At` operation reaches outside the preopen, under both strategies and kinds; the swap race | +| `src/core/fs/DescriptorTestSupport.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): test-only `DescriptorFixture`, `FixedRandom`, `bytesOf`/`textOf` | +| `src/core/fs/DirectoryStream_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): every entry once, typed, a stream of its own per call holding one batch; `isSameObject`, `metadataHashAt` | +| `src/core/fs/FsError.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/fs/FsError.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): one code per WASI 0.3 `wasi:filesystem` `error-code` case, plus `WouldBlock` | +| `src/core/fs/FsError_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/fs/NativeDescriptor_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): no system call on the caller's executor, a handle that outlives a parked call (C2), the keyed metadata hash | +| `src/core/fs/NativeFileSystem.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): `makeNativeDescriptorFileSystem` and its options | +| `src/core/fs/PathPolicy.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the POSIX and Windows rows | +| `src/core/fs/PathPolicy.hpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/fs/Rights.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the rights table and `checkOpenRights`, after wasmtime's descriptor permissions | +| `src/core/fs/Rights.hpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/fs/bsd/ErrnoTable.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): Apple and the BSDs; `EMLINK` for FreeBSD's `O_NOFOLLOW` | +| `src/core/fs/darwin/PosixSystem.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): Apple: `st_atimespec`, `F_RDADVISE`, `F_FULLFSYNC`, `EACCES` for `O_CREAT` on a directory | +| `src/core/fs/detail/DirectoryStream.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/fs/detail/DirectoryStream.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): the batched directory stream every implementation reads through | +| `src/core/fs/detail/NativeSupport.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/fs/detail/NativeSupport.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): what the native descriptors of every OS share: their context, the keyed metadata hash, the single-component rule | +| `src/core/fs/detail/OwnedHandle.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): the shared native handle of decision C2, closed on the blocking executor | +| `src/core/fs/detail/PathWalk.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/fs/detail/PathWalk.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): the path planner and the walk every resolver shares | +| `src/core/fs/detail/PathWalk_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/fs/detail/ResolveBeneath.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): `resolveBeneath`, `Resolved` and the kernel's beneath step `IBeneathOpener` | +| `src/core/fs/linux/Append.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): `pwritev2(RWF_APPEND)`, and a write at the end `fstat` reports, under the descriptor's lock, where the flag is refused | +| `src/core/fs/linux/Append.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): `appendAtEnd`, the append where `RWF_APPEND` is refused | +| `src/core/fs/linux/Append_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/fs/linux/BeneathDefault.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): `Best` on Linux is `openat2`, probed; the walk opens `O_PATH` | +| `src/core/fs/linux/DirectoryRead.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): a directory stream's `getdents64` records, field by field, in one fixed buffer | +| `src/core/fs/linux/DirectoryRead.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): `parseDirentRecords`, the `getdents64` record seam | +| `src/core/fs/linux/DirectoryRead_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/fs/linux/DescriptorEscape_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): no path goes through a `/proc` magic link | +| `src/core/fs/linux/Lease.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): an open under a lease made again, waiting, through a path handle checked to be a regular file | +| `src/core/fs/linux/Lease_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/fs/linux/Openat2.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): `openat2(RESOLVE_BENEATH | RESOLVE_NO_MAGICLINKS)`, the probe and the bounded `EAGAIN` retry | +| `src/core/fs/linux/Openat2.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): the `openat2` system-call seam | +| `src/core/fs/linux/Openat2_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/fs/posix/Append.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the second, `O_APPEND` handle of every POSIX system but Linux | +| `src/core/fs/posix/BeneathDefault.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): `Best` is the walk on every POSIX system but Linux; `#ifdef O_PATH` inside the data picks the walk's open flags | +| `src/core/fs/posix/DirectoryEntries.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): what a directory entry is: `d_type`, else a stat without following | +| `src/core/fs/posix/DirectoryEntries_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): `DT_UNKNOWN` stat'ed without following; refused names | +| `src/core/fs/posix/DirectoryRead.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): `fdopendir` and `readdir` for every POSIX system but Linux | +| `src/core/fs/posix/DirectoryRead.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): the directory stream's per-OS reader | +| `src/core/fs/posix/DirectoryStreamMemory_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): a large listing read within an allocation budget; replaces the global allocation functions | +| `src/core/fs/posix/ErrnoRows.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): the errno rows `posix/` and `bsd/ErrnoTable.cpp` share | +| `src/core/fs/posix/ErrnoTable.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/fs/posix/Lease.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): no leases off Linux: `WouldBlock` | +| `src/core/fs/posix/NativePathPolicy.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/fs/posix/OwnedHandleAllocation_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the last close when its frame cannot be allocated; replaces the global allocation functions | +| `src/core/fs/posix/PosixDescriptor.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the POSIX native descriptors | +| `src/core/fs/posix/PosixDescriptor_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): a FIFO opens without waiting; a name that is not UTF-8 is one refused entry | +| `src/core/fs/posix/PosixPathWalk.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the component walker over held directory descriptors | +| `src/core/fs/posix/PosixPathWalk.hpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/fs/posix/PosixPathWalk_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the walker against a swap at a chosen step | +| `src/core/fs/posix/PosixSystem.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): Linux, the BSDs and any POSIX system but Apple's; `#ifdef` inside the data picks `O_DSYNC` and `O_RSYNC` where a system lacks them | +| `src/core/fs/posix/PosixSystem.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): the calls POSIX systems differ in | +| `src/core/fs/testing/InMemoryDescriptorFileSystem.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/fs/testing/InMemoryDescriptorFileSystem.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): the in-memory model, resolving and enforcing through the code the native one uses | +| `src/core/fs/testing/InMemoryDescriptorFileSystem_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/fs/windows/BeneathDefault.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): `Best` is the walk on Windows | +| `src/core/fs/windows/DescriptorEscape_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): junctions, mount points, backslash targets, link flavour, private reparse tags | +| `src/core/fs/windows/DirectoryRecords.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): `FILE_ID_BOTH_DIR_INFO` records, field by field, within their buffer | +| `src/core/fs/windows/DirectoryRecords.hpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/fs/windows/DirectoryRecords_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/fs/windows/NativePathPolicy.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/fs/windows/NtFile.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): `NtCreateFile` relative to a held directory | +| `src/core/fs/windows/NtStatusTable.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/fs/windows/ReparsePoint.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): reparse data, field by field | +| `src/core/fs/windows/ReparsePoint.hpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/fs/windows/Win32ErrorTable.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/fs/windows/WindowsDescriptor.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the Windows native descriptors | +| `src/core/fs/windows/WindowsPathWalk.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the Windows component walker and the NT seam | +| `src/core/fs/windows/WindowsPathWalk.hpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/fs/windows/WindowsPathWalk_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | | `src/core/SystemRandomSource.hpp` | origin: core-cpp | - | - | the platform half of `Random.hpp`: one `fillFromSystemRandom()` per platform | | `src/core/log/Assert.hpp` | contour-terminal/contour | `src/crispy/Assert.hpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | `fatal()`/`SoftRequire()` moved here from crispy's `Assert.hpp` to close a base→log layering cycle; `Require`/`Guarantee`/`todo`/`unreachable`/`setFailHandler` stay in `src/core/Assert.hpp` | | `src/core/log/CMakeLists.txt` | origin: core-cpp | - | - | - | diff --git a/.agent/rules/testing.md b/.agent/rules/testing.md index 1a9c839a..8d6e0949 100644 --- a/.agent/rules/testing.md +++ b/.agent/rules/testing.md @@ -54,6 +54,12 @@ Most of these rules were paid for in fastcached; the full measurements are in everywhere and run by nothing, and an absent check looks exactly like a passing one. `core-cpp.tree-level-coverage` refuses that in both directions, but know the rule as well as the gate: a gate tells you that you broke it, the rule tells you what it is. +- **Test support that needs Catch2, `SKIP` or another module is a test-only `*TestSupport.hpp`** + next to the tests (`async/StrandTestSupport.hpp`, `fs/DescriptorTestSupport.hpp`), in no + `FILE_SET`, never in `testing/`, which is compiled into the module. Like a `*_test.cpp`, it is + compiled only into a test binary, which may link more than the module's row lists, so + `core-cpp.layering`'s include scan skips it as it skips the tests themselves; its self-check + plants one that reaches a module its row does not. - **Script-driven checks are `cmake -P` scripts under `tests/cmake/`**, registered in `tests/CMakeLists.txt`, each with a self-test that proves every rule it states refuses. diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 664ba2d0..478fef1c 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1322,7 +1322,7 @@ jobs: run: | cmake -DMODE=sync -DREF="$GITHUB_SHA" -DREPO="$GITHUB_WORKSPACE" \ -DDEST="$RUNNER_TEMP/vendor/core-cpp" \ - "-DMODULES=base;log;cli;codec;platform;async;net;testing" \ + "-DMODULES=base;log;cli;codec;platform;async;net;fs;testing" \ -P cmake/CoreCppVendor.cmake sed -n '1,7p' "$RUNNER_TEMP/vendor/core-cpp/MANIFEST" diff --git a/cmake/CoreCppModules.cmake b/cmake/CoreCppModules.cmake index c0beaa6c..bd54653c 100644 --- a/cmake/CoreCppModules.cmake +++ b/cmake/CoreCppModules.cmake @@ -215,6 +215,20 @@ function(core_cpp_add_modules) endif() endforeach() + # A vendored copy may leave a module's directory out (docs/vendoring.md). Without this, the + # add_subdirectory() below fails naming a path, and nothing says which option would have + # switched the module off -- the one thing the consumer has to know. + if(NOT EXISTS "${CORE_CPP_SOURCE_DIR}/src/core/${CORE_CPP_MODULE_${module}_DIR}/CMakeLists.txt") + if(when) + set(remedy "Set ${when}=OFF before adding core-cpp, or copy the module in.") + else() + set(remedy "No option switches it off, so the copy has to carry it.") + endif() + message(FATAL_ERROR + "[core-cpp] module ${module} is enabled but its directory src/core/${CORE_CPP_MODULE_${module}_DIR} " + "is missing from ${CORE_CPP_SOURCE_DIR}. ${remedy}") + endif() + set(CORE_CPP_CURRENT_MODULE "${module}") add_subdirectory("${CORE_CPP_SOURCE_DIR}/src/core/${CORE_CPP_MODULE_${module}_DIR}" "${CORE_CPP_BINARY_DIR}/src/core/${CORE_CPP_MODULE_${module}_DIR}") @@ -261,6 +275,12 @@ core_cpp_module(NAME net KIND STATIC DEPS async platform PLATFORMS wasm-subset) core_cpp_module_target(NAME net_types MODULE net KIND INTERFACE PLATFORMS any) core_cpp_module_target(NAME net_tls MODULE net KIND STATIC DEPS net PLATFORMS native WHEN CORE_CPP_WITH_TLS) +# The descriptor-relative file system: every operation an async::Task, every blocking call offloaded to +# an injected executor (async::offload), and no path resolved outside the directory it is relative to. +# Its own module rather than more of platform, which has no async edge. Native only: Emscripten and +# WASI have no file descriptors to hold. +core_cpp_module(NAME fs KIND STATIC DEPS base log async platform PLATFORMS native WHEN CORE_CPP_WITH_FS) + # endo's terminal UI. Native only: there is no terminal under Emscripten, where CORE_CPP_WITH_TUI is # forced off. core::tui_output is the part that composes and writes bytes, and it has a row of its # own because it links less than the module does: base alone, no libunicode and no coroutines, so a diff --git a/cmake/CoreCppOptions.cmake b/cmake/CoreCppOptions.cmake index 30933d64..6dd4e1f5 100644 --- a/cmake/CoreCppOptions.cmake +++ b/cmake/CoreCppOptions.cmake @@ -36,6 +36,7 @@ option(CORE_CPP_WITH_TUI_CORE "Build core::tui_core, the headless TUI that needs cmake_dependent_option(CORE_CPP_WITH_IMAGES "Decode images in core::tui (stb_image)" ON "CORE_CPP_WITH_TUI" OFF) option(CORE_CPP_WITH_TLS "Build core::net_tls (OpenSSL)" OFF) +option(CORE_CPP_WITH_FS "Build core::fs, the descriptor-relative file system" ON) # Linux only; ignored elsewhere. Needs pkg-config and libsystemd's development files (libsystemd-dev, # systemd-devel). option(CORE_CPP_WITH_SYSTEMD "Notify of system sleep/wake on Linux through logind (libsystemd)" ON) diff --git a/docs/getting-started/options.md b/docs/getting-started/options.md index 386d42a7..2f44f2fe 100644 --- a/docs/getting-started/options.md +++ b/docs/getting-started/options.md @@ -19,6 +19,7 @@ core-cpp never writes to the parent's cache. | `CORE_CPP_WITH_TUI_CORE` | `CORE_CPP_WITH_TUI`, on a first configure | Build `core::tui_core`, the headless TUI (no terminal, no event loop), which needs libunicode. Forced on by `CORE_CPP_WITH_TUI`; forces `CORE_CPP_WITH_TUI_OUTPUT` on | | `CORE_CPP_WITH_IMAGES` | ON, when `CORE_CPP_WITH_TUI` is | Decode images in `core::tui` (stb_image) | | `CORE_CPP_WITH_TLS` | OFF | Build `core::net_tls` (OpenSSL, from the system) | +| `CORE_CPP_WITH_FS` | ON | Build `core::fs`, the descriptor-relative file system. Native only: under Emscripten and WASI the module is skipped | | `CORE_CPP_WITH_SYSTEMD` | ON | Linux only: notify of system sleep/wake through logind (`libsystemd`, found with pkg-config and linked by value). A configure without its development files stops, naming this option; OFF builds without it and `makeNativeSystemPowerMonitor()` reports `NotImplemented` | | `CORE_CPP_WITH_TRACY` | OFF | Instrument core-cpp for the Tracy profiler | | `CORE_CPP_PEDANTIC` | ON when top-level | Compile core-cpp's targets with the pedantic warning set | diff --git a/docs/vendoring.md b/docs/vendoring.md index f7b2d2aa..f3a5d9f1 100644 --- a/docs/vendoring.md +++ b/docs/vendoring.md @@ -28,7 +28,7 @@ cmake -DMODE=sync -DREF= -DDEST= \ # The same, choosing the modules and the repository explicitly. MODULES is a CMake list, so the # shell must not see its semicolons: quote the whole -D argument. cmake -DMODE=sync -DREF= -DDEST= -DREPO= \ - "-DMODULES=base;log;cli;codec;platform;async;net;testing" \ + "-DMODULES=base;log;cli;codec;platform;async;net;fs;testing" \ -P /cmake/CoreCppVendor.cmake # Verify against its MANIFEST. Needs no git, and this one IS the copy's own script. @@ -46,7 +46,9 @@ cmake -DMODE=check -DDEST= -P /cmake/CoreCppVendor.cmake - **`MODULES`** selects which module directories are copied; it defaults to every module the ref has. A module that no option can switch off must be in the list, and `sync` reads the ref's own `cmake/CoreCppModules.cmake` to refuse a list that leaves one out; `CORE_CPP_WITH_TUI=OFF` is - what lets contour leave `tui` out. + what lets contour leave `tui` out, and `CORE_CPP_WITH_FS=OFF` leaves `fs` out. A copy without the + directory of a module whose option is still on stops the configure with a message naming that + option. - **`REF`** is a tag or a full 40-character commit SHA, and `sync` refuses anything else. A branch, `HEAD` or a short SHA names a different tree from one day to the next, and the manifest would then record a ref that cannot restore the copy it describes. diff --git a/src/core/async/CMakeLists.txt b/src/core/async/CMakeLists.txt index edf26a49..e8127d82 100644 --- a/src/core/async/CMakeLists.txt +++ b/src/core/async/CMakeLists.txt @@ -44,6 +44,7 @@ core_cpp_add_module(async KIND STATIC IExecutor.hpp Join.hpp KeyedStrands.hpp + Offload.hpp ParkedWork.hpp ResumeOn.hpp StopToken.hpp @@ -79,6 +80,7 @@ set(_coreCppAsyncStopTokenTests AsyncQueue_test.cpp Awaitable_test.cpp KeyedStrands_test.cpp + Offload_test.cpp ParkedWork_test.cpp StopToken_test.cpp Strand_test.cpp diff --git a/src/core/async/Offload.hpp b/src/core/async/Offload.hpp new file mode 100644 index 00000000..fb9a2b84 --- /dev/null +++ b/src/core/async/Offload.hpp @@ -0,0 +1,86 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// `offload` — run a blocking call on another executor and come back. + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace core::async +{ + +/// Runs @p work on @p blocking and resumes on @p home. +/// +/// The awaiting coroutine hops to @p blocking, calls @p work there, and hops back to @p home before +/// it sees the result, so a caller on a loop never runs the blocking call itself and never resumes +/// on a pool thread. Nothing here owns a thread: both executors are the caller's. +/// +/// **The stop token is read once, before the hop.** A stop already requested throws +/// @c OperationCancelled and @p work never runs. Once @p work has run, its result is returned +/// whatever the token says by then: a write that completed, or a handle that was opened, is never +/// dropped on the floor because a stop arrived while it was in flight. +/// +/// The executors are pointers because a coroutine's parameters are copied into its frame, and a +/// reference parameter would name storage the caller may destroy while this one is suspended. +/// +/// @tparam F A callable taking no arguments; its result must not be a reference. +/// @param home Where the caller resumes. Must outlive the returned task. +/// @param blocking Where @p work runs. Must outlive the returned task. +/// @param work The blocking call, moved into the coroutine frame. +/// @return @p work's result, on @p home. +/// @throws OperationCancelled Where the flow's stop was requested before the hop. What @p work +/// throws is rethrown, on @p home. +template +[[nodiscard]] Task> offload(IExecutor* home, IExecutor* blocking, F work) +{ + using Result = std::invoke_result_t; + static_assert(!std::is_reference_v, "offload: work must return a value, not a reference"); + + auto const token = co_await thisCoroStopToken(); + if (token.stop_requested()) + throw OperationCancelled {}; + + co_await ResumeOn { *blocking }; + auto failure = std::exception_ptr {}; + if constexpr (std::is_void_v) + { + try + { + std::invoke(work); + } + catch (...) + { + failure = std::current_exception(); + } + co_await ResumeOn { *home }; + if (failure) + std::rethrow_exception(failure); + } + else + { + auto result = std::optional {}; + try + { + result.emplace(std::invoke(work)); + } + catch (...) + { + failure = std::current_exception(); + } + co_await ResumeOn { *home }; + if (failure) + std::rethrow_exception(failure); + co_return std::move(*result); + } +} + +} // namespace core::async diff --git a/src/core/async/Offload_test.cpp b/src/core/async/Offload_test.cpp new file mode 100644 index 00000000..e64261b4 --- /dev/null +++ b/src/core/async/Offload_test.cpp @@ -0,0 +1,114 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// async::offload: the work runs on the blocking executor and nowhere else, the caller resumes on the +// home executor and nowhere else, and the flow's stop token is read exactly once, before the hop. +// Two ManualExecutors make each of those an observable step rather than a timing. +#include +#include +#include +#include +#include + +#include + +#include +#include + +using core::async::offload; +using core::async::OperationCancelled; +using core::async::StopSource; +using core::async::testing::ManualExecutor; + +TEST_CASE("offload: the work runs on the blocking executor and the caller resumes on home", + "[async][offload]") +{ + auto home = ManualExecutor {}; + auto blocking = ManualExecutor {}; + auto ran = false; + auto task = offload(&home, &blocking, [&ran] { + ran = true; + return 42; + }); + + task.handle().resume(); + CHECK_FALSE(ran); + CHECK(blocking.pending() == 1); + CHECK(home.pending() == 0); + + CHECK(blocking.drain() == 1); + CHECK(ran); + CHECK_FALSE(task.done()); + CHECK(home.pending() == 1); + + CHECK(home.drain() == 1); + REQUIRE(task.done()); + CHECK(task.result() == 42); +} + +TEST_CASE("offload: void work completes on home", "[async][offload]") +{ + auto home = ManualExecutor {}; + auto blocking = ManualExecutor {}; + auto ran = 0; + auto task = offload(&home, &blocking, [&ran] { ++ran; }); + + task.handle().resume(); + blocking.drain(); + CHECK(ran == 1); + CHECK_FALSE(task.done()); + home.drain(); + REQUIRE(task.done()); + task.result(); +} + +TEST_CASE("offload: a stop requested before the call throws and never runs the work", "[async][offload]") +{ + auto home = ManualExecutor {}; + auto blocking = ManualExecutor {}; + auto source = StopSource {}; + source.request_stop(); + auto ran = false; + auto task = offload(&home, &blocking, [&ran] { + ran = true; + return 1; + }); + task.handle().promise().setStopToken(source.get_token()); + + task.handle().resume(); + REQUIRE(task.done()); + CHECK(blocking.pending() == 0); + CHECK(home.pending() == 0); + CHECK_FALSE(ran); + CHECK_THROWS_AS(task.result(), OperationCancelled); +} + +TEST_CASE("offload: a stop requested while the work is parked still returns its result", "[async][offload]") +{ + auto home = ManualExecutor {}; + auto blocking = ManualExecutor {}; + auto source = StopSource {}; + auto task = offload(&home, &blocking, [] { return std::string { "written" }; }); + task.handle().promise().setStopToken(source.get_token()); + + task.handle().resume(); + REQUIRE(blocking.pending() == 1); + source.request_stop(); + blocking.drain(); + home.drain(); + REQUIRE(task.done()); + CHECK(task.result() == "written"); +} + +TEST_CASE("offload: what the work throws reaches the caller on home", "[async][offload]") +{ + auto home = ManualExecutor {}; + auto blocking = ManualExecutor {}; + auto task = offload(&home, &blocking, []() -> int { throw std::runtime_error { "refused" }; }); + + task.handle().resume(); + CHECK(blocking.drain() == 1); + CHECK_FALSE(task.done()); + CHECK(home.drain() == 1); + REQUIRE(task.done()); + CHECK_THROWS_AS(task.result(), std::runtime_error); +} diff --git a/src/core/fs/CMakeLists.txt b/src/core/fs/CMakeLists.txt new file mode 100644 index 00000000..ff71e4a0 --- /dev/null +++ b/src/core/fs/CMakeLists.txt @@ -0,0 +1,144 @@ +# SPDX-License-Identifier: Apache-2.0 + +# core::fs: the descriptor-relative file system. Every operation is a core::async::Task, every +# blocking call runs on an injected executor through core::async::offload, and a path is resolved +# beneath the descriptor it is relative to, never by the kernel from the root. +# +# What differs per OS is data, or a few calls behind posix/PosixSystem.hpp: the table that classifies +# a system error code, the name rules of the native PathPolicy, how a stat's times are spelled, how +# to advise, sync and append. Each is compiled once, and the platform is asked once, here, as +# src/core/net/CMakeLists.txt does for DefaultBackend.cpp: SOURCES_POSIX and SOURCES_BSD both apply +# on Apple and the BSDs (and SOURCES_LINUX with SOURCES_POSIX on Linux), so two files listed per +# directory would both define the same function. +# - errno table: the BSDs and Apple report a symbolic link refused by O_NOFOLLOW differently +# (FreeBSD answers EMLINK). +# - PosixSystem.cpp: Apple spells the times st_atimespec, advises through F_RDADVISE and syncs +# through F_FULLFSYNC (darwin/); every other POSIX system has st_atim, posix_fadvise and +# fdatasync (posix/). +# - Append.cpp: Linux appends in place with pwritev2(RWF_APPEND); every other POSIX system opens a +# second, O_APPEND handle. +# - BeneathDefault.cpp: what BeneathStrategy::Best stands for. Linux resolves beneath with +# openat2(RESOLVE_BENEATH) where the kernel has it (linux/); every other system walks one +# component at a time (posix/, windows/). +# - windows/: NtCreateFile relative to a held handle opens each component, NtSetInformationFile +# renames and links beneath one, both from ntdll, which the module links PRIVATE on Windows. +# - Lease.cpp: an O_NONBLOCK open of a regular file under a Linux lease answers EWOULDBLOCK, and is +# made again, waiting, through a path handle checked to be a regular file (linux/); no other +# system has leases (posix/). +# - DirectoryRead.cpp: a directory stream reads Linux's getdents64 records into a fixed buffer +# (linux/); every other POSIX system reads through fdopendir and readdir (posix/). +if(WIN32) + set(_coreCppFsPlatform windows/Win32ErrorTable.cpp windows/NtStatusTable.cpp windows/BeneathDefault.cpp) + set(_coreCppFsPrivateLibs ntdll) +elseif(APPLE) + set(_coreCppFsPlatform bsd/ErrnoTable.cpp darwin/PosixSystem.cpp posix/Append.cpp posix/BeneathDefault.cpp posix/DirectoryRead.cpp posix/Lease.cpp) +elseif(CORE_CPP_PLATFORM_BSD) + set(_coreCppFsPlatform bsd/ErrnoTable.cpp posix/PosixSystem.cpp posix/Append.cpp posix/BeneathDefault.cpp posix/DirectoryRead.cpp posix/Lease.cpp) +elseif(LINUX) + set(_coreCppFsPlatform posix/ErrnoTable.cpp posix/PosixSystem.cpp linux/Append.cpp linux/BeneathDefault.cpp linux/DirectoryRead.cpp linux/Lease.cpp) +else() + set(_coreCppFsPlatform posix/ErrnoTable.cpp posix/PosixSystem.cpp posix/Append.cpp posix/BeneathDefault.cpp posix/DirectoryRead.cpp posix/Lease.cpp) +endif() + +# The openat2 path spells the call's ABI itself (linux/Openat2.hpp), so no UAPI 5.6 headers or glibc +# 2.32 are needed to build it; whether the running kernel has the call is probed at run time, per +# file system. Its test checks the spelling against . + +core_cpp_add_module(fs KIND STATIC + HEADERS + Descriptor.hpp + FsError.hpp + NativeFileSystem.hpp + PathPolicy.hpp + Rights.hpp + testing/InMemoryDescriptorFileSystem.hpp + SOURCES + FsError.cpp + PathPolicy.cpp + Rights.cpp + detail/DirectoryStream.cpp + detail/DirectoryStream.hpp + detail/NativeSupport.cpp + detail/NativeSupport.hpp + detail/OwnedHandle.hpp + detail/PathWalk.cpp + detail/PathWalk.hpp + detail/ResolveBeneath.hpp + testing/InMemoryDescriptorFileSystem.cpp + ${_coreCppFsPlatform} + SOURCES_POSIX + posix/DirectoryEntries.cpp + posix/DirectoryRead.hpp + posix/ErrnoRows.hpp + posix/NativePathPolicy.cpp + posix/PosixDescriptor.cpp + posix/PosixPathWalk.cpp + posix/PosixPathWalk.hpp + posix/PosixSystem.hpp + SOURCES_LINUX + linux/Append.hpp + linux/DirectoryRead.hpp + linux/Openat2.cpp + linux/Openat2.hpp + SOURCES_WINDOWS + windows/DirectoryRecords.cpp + windows/DirectoryRecords.hpp + windows/NativePathPolicy.cpp + windows/NtFile.hpp + windows/ReparsePoint.cpp + windows/ReparsePoint.hpp + windows/WindowsDescriptor.cpp + windows/WindowsPathWalk.cpp + windows/WindowsPathWalk.hpp + PUBLIC_LIBS core::base core::async core::platform + PRIVATE_LIBS ${_coreCppFsPrivateLibs}) + +# posix/Append.cpp, posix/BeneathDefault.cpp, posix/DirectoryRead.cpp and posix/Lease.cpp are what Apple and +# the BSDs append, resolve, read directories and open leased files with, +# so a Linux build would never compile them: parse them there too, so a rename or a dropped include +# shows up before a macOS job does. +if(LINUX) + core_cpp_add_unbuilt_source_check(fs-posix + SOURCES posix/Append.cpp posix/BeneathDefault.cpp posix/DirectoryRead.cpp posix/Lease.cpp + PART_OF fs + USAGE core::base core::async core::platform) +endif() + +# One binary: every case links core::fs and nothing the module's row does not list. +# DescriptorTestSupport.hpp is the test-only fixture the descriptor cases share. +core_cpp_add_test(fs + SOURCES + DescriptorContract_test.cpp + DescriptorEscape_test.cpp + DescriptorTestSupport.hpp + DirectoryStream_test.cpp + FsError_test.cpp + NativeDescriptor_test.cpp + detail/PathWalk_test.cpp + testing/InMemoryDescriptorFileSystem_test.cpp + SOURCES_POSIX + posix/DirectoryEntries_test.cpp + posix/PosixDescriptor_test.cpp + posix/PosixPathWalk_test.cpp + SOURCES_LINUX + linux/Append_test.cpp + linux/DescriptorEscape_test.cpp + linux/DirectoryRead_test.cpp + linux/Lease_test.cpp + linux/Openat2_test.cpp + SOURCES_WINDOWS + windows/DescriptorEscape_test.cpp + windows/DirectoryRecords_test.cpp + windows/WindowsPathWalk_test.cpp) + +# What the last owner of a handle does when its queued close cannot be allocated: a binary of its own +# because it replaces the global allocation functions, which would reach every case linked beside +# it. POSIX only, where a closed descriptor is plain to see. Not under a sanitizer, whose runtime +# defines those functions itself (the link refuses a second definition). +if(NOT CORE_CPP_SANITIZERS AND NOT WIN32) + core_cpp_add_test(fs NAME fs-alloc + SOURCES posix/OwnedHandleAllocation_test.cpp ../testing/ReplacedGlobalAllocation.cpp) + # What a directory stream holds while it reads a large directory, counted the same way. + core_cpp_add_test(fs NAME fs-memory + SOURCES posix/DirectoryStreamMemory_test.cpp DescriptorTestSupport.hpp ../testing/ReplacedGlobalAllocation.cpp) +endif() diff --git a/src/core/fs/Descriptor.hpp b/src/core/fs/Descriptor.hpp new file mode 100644 index 00000000..04d4d981 --- /dev/null +++ b/src/core/fs/Descriptor.hpp @@ -0,0 +1,396 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// The descriptor-relative file system: @c IDescriptorFileSystem opens a preopened directory, and +/// every @c IDescriptor operation is an @c async::Task relative to the descriptor it is called on. +/// +/// What every implementation guarantees: +/// - **No path leaves its descriptor.** An absolute path, a `..` above the descriptor, a symbolic +/// link whose target leaves it or is absolute: each is `NotPermitted`. A final symbolic link is +/// followed only where the call says @c SymlinkPolicy::Follow. +/// - **Rights are the descriptor's.** Each operation needs the @c DescriptorFlags its row of +/// @c rightsTable() names, and a child opened by @c IDescriptor::openAt carries no right its parent +/// could not grant (@c checkOpenRights). A refusal is `NotPermitted`, before anything is touched. +/// - **Nothing blocks the caller.** The blocking call runs on the executor the file system was built +/// with (@c async::offload), and the caller resumes on its home executor. +/// - **Paths are UTF-8**, relative, and checked against the file system's @c PathPolicy. + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace core::fs +{ + +/// What a descriptor or a directory entry refers to. +enum class DescriptorType : std::uint8_t +{ + Unknown, ///< Something the file system does not classify. + BlockDevice, ///< A block device. + CharacterDevice, ///< A character device. + Directory, ///< A directory. + Fifo, ///< A named pipe. + SymbolicLink, ///< A symbolic link. + RegularFile, ///< A regular file. + Socket, ///< A socket. +}; + +/// The rights and the write-integrity mode a descriptor carries. A bitmask: combine with `|`, test +/// with @c hasFlag. +enum class DescriptorFlags : std::uint8_t +{ + None = 0, ///< No right. + Read = 0b1, ///< Read a file's bytes or a directory's entries; resolve paths. + Write = 0b10, ///< Write a file's bytes. A directory never carries it. + FileIntegritySync = 0b100, ///< Writes complete with file integrity (`O_SYNC`). Not a right. + DataIntegritySync = 0b1000, ///< Writes complete with data integrity (`O_DSYNC`). Not a right. + RequestedWriteSync = 0b1'0000, ///< Reads wait for pending writes (`O_RSYNC`). Not a right. + MutateDirectory = 0b10'0000, ///< Create, remove, rename and link entries in a directory. +}; + +/// @param a The first mask. +/// @param b The second mask. +/// @return Both masks' flags. +[[nodiscard]] constexpr DescriptorFlags operator|(DescriptorFlags a, DescriptorFlags b) noexcept +{ + return static_cast(static_cast(a) | static_cast(b)); +} + +/// @param set The mask to test. +/// @param flag The flag to look for; @c DescriptorFlags::None is never present. +/// @return Whether @p set carries @p flag. +[[nodiscard]] constexpr bool hasFlag(DescriptorFlags set, DescriptorFlags flag) noexcept +{ + return (static_cast(set) & static_cast(flag)) != 0; +} + +/// How an @c IDescriptor::openAt treats what it opens. A bitmask: combine with `|`, test with +/// @c hasFlag. +enum class OpenFlags : std::uint8_t +{ + None = 0, ///< Open what exists. + Create = 0b1, ///< Create a regular file where nothing exists. + Directory = 0b10, ///< Fail unless the object is a directory. + Exclusive = 0b100, ///< With @c Create: fail where something exists. + Truncate = 0b1000, ///< Truncate a regular file to zero bytes. +}; + +/// @param a The first mask. +/// @param b The second mask. +/// @return Both masks' flags. +[[nodiscard]] constexpr OpenFlags operator|(OpenFlags a, OpenFlags b) noexcept +{ + return static_cast(static_cast(a) | static_cast(b)); +} + +/// @param set The mask to test. +/// @param flag The flag to look for; @c OpenFlags::None is never present. +/// @return Whether @p set carries @p flag. +[[nodiscard]] constexpr bool hasFlag(OpenFlags set, OpenFlags flag) noexcept +{ + return (static_cast(set) & static_cast(flag)) != 0; +} + +/// Whether a path's final component is followed when it is a symbolic link. Links before it are +/// always followed, beneath the descriptor. +enum class SymlinkPolicy : std::uint8_t +{ + NoFollow, ///< Operate on the link itself; an open of one is `Loop`. + Follow, ///< Operate on what it names. +}; + +/// How the caller intends to access a range of a file (`posix_fadvise`). Advisory only. +enum class Advice : std::uint8_t +{ + Normal, ///< No particular pattern. + Sequential, ///< In order, from low offsets to high. + Random, ///< In no particular order. + WillNeed, ///< Soon. + DontNeed, ///< Not soon. + NoReuse, ///< Once. +}; + +/// Whether a read reached the end of what it reads. +enum class StreamEnd : std::uint8_t +{ + More, ///< There may be more after the bytes returned. + Reached, ///< The bytes returned end at the end of the file. +}; + +/// A point in time, as seconds and nanoseconds since the Unix epoch. +struct FileTime +{ + std::int64_t seconds = 0; ///< Whole seconds since 1970-01-01T00:00:00Z. + std::uint32_t nanoseconds = 0; ///< Below a second, `[0, 1e9)`. + + /// Ordered by instant. + auto operator<=>(FileTime const&) const = default; +}; + +/// A @c NewTimestamp that leaves the time as it is. +struct NoChange +{ +}; + +/// A @c NewTimestamp that sets the time to the file system's clock. +struct SetToNow +{ +}; + +/// What @c IDescriptor::setTimes does with one of the times. +using NewTimestamp = std::variant; + +/// What a descriptor refers to, and its size and times. +struct DescriptorStat +{ + DescriptorType type = DescriptorType::Unknown; ///< What it is. + std::uint64_t linkCount = 0; ///< How many hard links name it. + std::uint64_t size = 0; ///< Its size in bytes. + std::optional accessed; ///< Last access, where the system keeps it. + std::optional modified; ///< Last modification of its data. + std::optional statusChanged; ///< Last change of its metadata. +}; + +/// One entry of a directory. +struct DirectoryEntry +{ + DescriptorType type = DescriptorType::Unknown; ///< What it is. + std::string name; ///< Its name, in UTF-8. +}; + +/// A 128-bit hash of an object's metadata: equal for two descriptors of one unchanged object, +/// different once it changes. +struct MetadataHash +{ + std::uint64_t lower = 0; ///< The low 64 bits. + std::uint64_t upper = 0; ///< The high 64 bits. + + /// Compared as a pair. + auto operator<=>(MetadataHash const&) const = default; +}; + +/// What a read returns. +struct ReadChunk +{ + std::vector bytes; ///< The bytes read; fewer than asked for near the end. + StreamEnd end = StreamEnd::More; ///< Whether they end at the end of the file. +}; + +/// The entries of a directory, read in batches. +/// +/// Each @c IDescriptor::readDirectory opens a stream of its own, positioned at the directory's +/// start, and the stream holds one batch of entries at a time, never the whole listing. A stream +/// outlives the descriptor it came from. An entry neither added nor removed while the directory is +/// read comes exactly once; one added or removed meanwhile may come or not, as the system has it. One +/// call at a time: @c next is called again once the call before it has completed, and the stream +/// outlives every call to it that is still pending. +class IDirectoryStream +{ + public: + IDirectoryStream() = default; + IDirectoryStream(IDirectoryStream const&) = delete; + IDirectoryStream(IDirectoryStream&&) = delete; + IDirectoryStream& operator=(IDirectoryStream const&) = delete; + IDirectoryStream& operator=(IDirectoryStream&&) = delete; + virtual ~IDirectoryStream() = default; + + /// @return The next entry, nullopt at the end; never "." or "..". An unrepresentable name is + /// IllegalByteSequence for that entry, and the following call continues after it. + [[nodiscard]] virtual async::Task>> next() = 0; +}; + +/// An open file or directory, and every operation relative to it. +/// +/// A descriptor passed as `newDirectory` or `other` is borrowed for the call; it must be one of the +/// same file system instance, or the answer is `CrossDevice` (`false` for @c isSameObject). +class IDescriptor +{ + public: + IDescriptor() = default; + IDescriptor(IDescriptor const&) = delete; + IDescriptor(IDescriptor&&) = delete; + IDescriptor& operator=(IDescriptor const&) = delete; + IDescriptor& operator=(IDescriptor&&) = delete; + virtual ~IDescriptor() = default; + + /// Reads up to @p maxBytes from @p offset. Needs `Read`. + /// @param maxBytes How many bytes at most; clamped to the file system's `maxReadChunk`. + /// @param offset Where to start. + /// @return The bytes, and whether they reach the end of the file. + [[nodiscard]] virtual async::Task> read(std::size_t maxBytes, + std::uint64_t offset) = 0; + + /// Writes @p bytes at @p offset, extending the file as needed. Needs `Write`. + /// @param bytes What to write. + /// @param offset Where. + /// @return How many bytes were written. + [[nodiscard]] virtual async::Task> write(std::vector bytes, + std::uint64_t offset) = 0; + + /// Writes @p bytes at the end of the file. Needs `Write`. + /// @param bytes What to write. + /// @return How many bytes were written. + [[nodiscard]] virtual async::Task> append(std::vector bytes) = 0; + + /// Tells the system how a range will be accessed. + /// @param offset Where the range starts. + /// @param length How long it is; 0 to the end. + /// @param advice How. + /// @return Nothing, or why the advice was refused. + [[nodiscard]] virtual async::Task> advise(std::uint64_t offset, + std::uint64_t length, + Advice advice) = 0; + + /// @return Nothing once the file's data is on stable storage (`fdatasync`). + [[nodiscard]] virtual async::Task> syncData() = 0; + + /// @return Nothing once the file's data and metadata are on stable storage (`fsync`). + [[nodiscard]] virtual async::Task> sync() = 0; + + /// @return The flags the descriptor was opened with. + [[nodiscard]] virtual DescriptorFlags flags() const noexcept = 0; + + /// @return What the descriptor refers to. + [[nodiscard]] virtual async::Task> type() = 0; + + /// Truncates or extends the file to @p size bytes. Needs `Write`. + /// @param size The new size. + /// @return Nothing, or why not. + [[nodiscard]] virtual async::Task> setSize(std::uint64_t size) = 0; + + /// Sets the access and modification times. Needs `Write`, or `MutateDirectory` on a directory. + /// @param accessed The new access time. + /// @param modified The new modification time. + /// @return Nothing, or why not. + [[nodiscard]] virtual async::Task> setTimes(NewTimestamp accessed, + NewTimestamp modified) = 0; + + /// @return What the descriptor refers to, its size and its times. + [[nodiscard]] virtual async::Task> stat() = 0; + + /// @return The hash of the object's metadata. + [[nodiscard]] virtual async::Task> metadataHash() = 0; + + /// Opens a stream over the directory's entries. Needs `Read`. + /// @return The stream. + [[nodiscard]] virtual async::Task>> readDirectory() = 0; + + /// Opens @p path beneath this directory. Needs `Read`; the child's flags are held to + /// @c checkOpenRights. + /// @param policy Whether a final symbolic link is followed. + /// @param path The relative path. + /// @param open How to open it. + /// @param flags The rights and mode the new descriptor carries. + /// @return The new descriptor. + [[nodiscard]] virtual async::Task>> openAt( + SymlinkPolicy policy, std::string path, OpenFlags open, DescriptorFlags flags) = 0; + + /// Creates the directory @p path. Needs `MutateDirectory`. + /// @param path The relative path. + /// @return Nothing, or why not. + [[nodiscard]] virtual async::Task> createDirectoryAt(std::string path) = 0; + + /// Reads what @p path refers to without opening it. Needs `Read`. + /// @param policy Whether a final symbolic link is followed. + /// @param path The relative path. + /// @return What @p path refers to, its size and its times. + [[nodiscard]] virtual async::Task> statAt(SymlinkPolicy policy, + std::string path) = 0; + + /// Sets the times of @p path. Needs `MutateDirectory`. + /// @param policy Whether a final symbolic link is followed. + /// @param path The relative path. + /// @param accessed The new access time. + /// @param modified The new modification time. + /// @return Nothing, or why not. + [[nodiscard]] virtual async::Task> setTimesAt(SymlinkPolicy policy, + std::string path, + NewTimestamp accessed, + NewTimestamp modified) = 0; + + /// Creates the hard link @p newPath beneath @p newDirectory to @p oldPath beneath this one. Needs + /// `MutateDirectory` on both. + /// @param policy @c SymlinkPolicy::Follow is `Invalid`. + /// @param oldPath The existing object. + /// @param newDirectory From the same file system, or the answer is CrossDevice (D11). + /// @param newPath The new name. + /// @return Nothing, or why not. + [[nodiscard]] virtual async::Task> linkAt(SymlinkPolicy policy, + std::string oldPath, + IDescriptor* newDirectory, + std::string newPath) = 0; + + /// Reads a symbolic link's target. Needs `Read`. + /// @param path The relative path of the link. + /// @return Its target, as stored. + [[nodiscard]] virtual async::Task> readlinkAt(std::string path) = 0; + + /// Removes the empty directory @p path. Needs `MutateDirectory`. + /// @param path The relative path. + /// @return Nothing, or why not. + [[nodiscard]] virtual async::Task> removeDirectoryAt(std::string path) = 0; + + /// Renames @p oldPath beneath this directory to @p newPath beneath @p newDirectory. Needs + /// `MutateDirectory` on both. + /// @param oldPath The existing object. + /// @param newDirectory From the same file system, or the answer is CrossDevice (D11). + /// @param newPath The new name. + /// @return Nothing, or why not. + [[nodiscard]] virtual async::Task> renameAt(std::string oldPath, + IDescriptor* newDirectory, + std::string newPath) = 0; + + /// Creates the symbolic link @p newPath holding @p target. Needs `MutateDirectory`. + /// @param target What the link names; an absolute one is `NotPermitted`. + /// @param newPath The relative path of the link. + /// @return Nothing, or why not. + [[nodiscard]] virtual async::Task> symlinkAt(std::string target, std::string newPath) = 0; + + /// Removes the non-directory @p path. Needs `MutateDirectory`. + /// @param path The relative path. + /// @return Nothing, or why not. + [[nodiscard]] virtual async::Task> unlinkFileAt(std::string path) = 0; + + /// Hashes the metadata of @p path without opening it. Needs `Read`. + /// @param policy Whether a final symbolic link is followed. + /// @param path The relative path. + /// @return The hash of its metadata. + [[nodiscard]] virtual async::Task> metadataHashAt(SymlinkPolicy policy, + std::string path) = 0; + + /// A bool because the name asks the question; a foreign descriptor is never the same object. + /// @param other The descriptor to compare with. + /// @return Whether both refer to one object. + [[nodiscard]] virtual async::Task> isSameObject(IDescriptor* other) = 0; +}; + +/// Opens preopened directories, the roots every other descriptor descends from. +class IDescriptorFileSystem +{ + public: + IDescriptorFileSystem() = default; + IDescriptorFileSystem(IDescriptorFileSystem const&) = delete; + IDescriptorFileSystem(IDescriptorFileSystem&&) = delete; + IDescriptorFileSystem& operator=(IDescriptorFileSystem const&) = delete; + IDescriptorFileSystem& operator=(IDescriptorFileSystem&&) = delete; + virtual ~IDescriptorFileSystem() = default; + + /// Opens @p hostDirectory as a root. The host chose it, so it is not held to a @c PathPolicy. + /// @param hostDirectory The directory, in the host's own terms. + /// @param flags The rights the root carries; `Write` is `IsDirectory`, as on any directory. + /// @return The root descriptor. + [[nodiscard]] virtual async::Task>> openPreopen( + std::filesystem::path hostDirectory, DescriptorFlags flags) = 0; +}; + +} // namespace core::fs diff --git a/src/core/fs/DescriptorContract_test.cpp b/src/core/fs/DescriptorContract_test.cpp new file mode 100644 index 00000000..2637e870 --- /dev/null +++ b/src/core/fs/DescriptorContract_test.cpp @@ -0,0 +1,857 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// What every IDescriptor owes its caller, whichever file system is under it. Each case GENERATEs +// the fixture kinds it holds for: the in-memory model and the native descriptors. +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using core::fs::Advice; +using core::fs::DescriptorFlags; +using core::fs::DescriptorStat; +using core::fs::DescriptorType; +using core::fs::FileTime; +using core::fs::FsErrorCode; +using core::fs::FsResult; +using core::fs::IDescriptor; +using core::fs::MetadataHash; +using core::fs::NoChange; +using core::fs::OpenFlags; +using core::fs::Operation; +using core::fs::SetToNow; +using core::fs::StreamEnd; +using core::fs::SymlinkPolicy; +using core::fs::test::bytesOf; +using core::fs::test::DescriptorFixture; +using core::fs::test::FixtureKind; +using core::fs::test::NowSource; +using core::fs::test::Outcome; +using core::fs::test::outcomeOf; +using core::fs::test::SymlinkSupport; +using core::fs::test::textOf; + +TEST_CASE("contract: written bytes read back with an end marker", "[fs][contract]") +{ + auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); + using enum core::fs::OpenFlags; + auto file = fixture.run( + fixture.root().openAt(core::fs::SymlinkPolicy::NoFollow, + "f.txt", + Create | Exclusive, + core::fs::DescriptorFlags::Read | core::fs::DescriptorFlags::Write)); + REQUIRE(file.has_value()); + CHECK(fixture.run((*file)->write(bytesOf("hello"), 0)).value() == 5); + CHECK(textOf(fixture.run((*file)->read(64, 0)).value().bytes) == "hello"); + CHECK(fixture.run((*file)->read(64, 5)).value().end == core::fs::StreamEnd::Reached); + CHECK(outcomeOf(fixture.run(fixture.root().openAt(core::fs::SymlinkPolicy::NoFollow, + "f.txt", + Create | Exclusive, + core::fs::DescriptorFlags::Write))) + == core::fs::FsErrorCode::Exist); +} + +TEST_CASE("contract: a path that climbs above its descriptor is NotPermitted", "[fs][contract]") +{ + auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); + REQUIRE(fixture.run(fixture.root().createDirectoryAt("a")).has_value()); + fixture.createFile("x", "inside"); + + auto const escaped = fixture.run( + fixture.root().openAt(SymlinkPolicy::NoFollow, "a/../../x", OpenFlags::None, DescriptorFlags::Read)); + REQUIRE_FALSE(escaped.has_value()); + CHECK(escaped.error().code == FsErrorCode::NotPermitted); + CHECK(outcomeOf(fixture.run(fixture.root().statAt(SymlinkPolicy::NoFollow, ".."))) + == FsErrorCode::NotPermitted); + CHECK(fixture + .run(fixture.root().openAt( + SymlinkPolicy::NoFollow, "a/../x", OpenFlags::None, DescriptorFlags::Read)) + .has_value()); +} + +TEST_CASE("contract: a read-only preopen refuses every mutation and changes nothing", "[fs][contract]") +{ + auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); + fixture.createFile("f", "content"); + REQUIRE(fixture.run(fixture.root().createDirectoryAt("d")).has_value()); + auto readOnly = fixture.openRoot(DescriptorFlags::Read); + REQUIRE(readOnly.has_value()); + auto& dir = **readOnly; + auto const before = fixture.run(dir.statAt(SymlinkPolicy::NoFollow, "f")); + REQUIRE(before.has_value()); + fixture.clock().advance(std::chrono::hours { 1 }); + + auto const refusal = [&fixture](auto task) { + auto const result = fixture.run(std::move(task)); + REQUIRE_FALSE(result.has_value()); + return result.error().code; + }; + CHECK(refusal(dir.openAt(SymlinkPolicy::NoFollow, "f", OpenFlags::None, DescriptorFlags::Write)) + == FsErrorCode::NotPermitted); + CHECK(refusal(dir.openAt(SymlinkPolicy::NoFollow, "g", OpenFlags::Create, DescriptorFlags::Read)) + == FsErrorCode::NotPermitted); + CHECK(refusal(dir.openAt(SymlinkPolicy::NoFollow, "f", OpenFlags::Truncate, DescriptorFlags::Read)) + == FsErrorCode::NotPermitted); + CHECK(refusal(dir.createDirectoryAt("e")) == FsErrorCode::NotPermitted); + CHECK(refusal(dir.unlinkFileAt("f")) == FsErrorCode::NotPermitted); + CHECK(refusal(dir.removeDirectoryAt("d")) == FsErrorCode::NotPermitted); + CHECK(refusal(dir.renameAt("f", &dir, "g")) == FsErrorCode::NotPermitted); + CHECK(refusal(dir.symlinkAt("f", "l")) == FsErrorCode::NotPermitted); + CHECK(refusal(dir.linkAt(SymlinkPolicy::NoFollow, "f", &dir, "h")) == FsErrorCode::NotPermitted); + CHECK(refusal(dir.setTimesAt(SymlinkPolicy::NoFollow, "f", SetToNow {}, SetToNow {})) + == FsErrorCode::NotPermitted); + + for (auto const* name: { "e", "g", "h", "l" }) + { + CAPTURE(name); + CHECK(outcomeOf(fixture.run(fixture.root().statAt(SymlinkPolicy::NoFollow, name))) + == FsErrorCode::NoEntry); + } + auto const after = fixture.run(fixture.root().statAt(SymlinkPolicy::NoFollow, "f")); + REQUIRE(after.has_value()); + CHECK(after->modified == before->modified); + CHECK(after->accessed == before->accessed); + CHECK(after->size == 7); + CHECK(fixture.run(fixture.root().statAt(SymlinkPolicy::NoFollow, "d"))->type + == DescriptorType::Directory); +} + +TEST_CASE("contract: a child opened with more flags than its parent is NotPermitted", "[fs][contract]") +{ + auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); + REQUIRE(fixture.run(fixture.root().createDirectoryAt("d")).has_value()); + auto readOnly = fixture.openRoot(DescriptorFlags::Read); + REQUIRE(readOnly.has_value()); + + auto const wider = + fixture.run((*readOnly)->openAt(SymlinkPolicy::NoFollow, + "d", + OpenFlags::Directory, + DescriptorFlags::Read | DescriptorFlags::MutateDirectory)); + REQUIRE_FALSE(wider.has_value()); + CHECK(wider.error().code == FsErrorCode::NotPermitted); + + auto const narrower = fixture.run( + (*readOnly)->openAt(SymlinkPolicy::NoFollow, "d", OpenFlags::Directory, DescriptorFlags::Read)); + REQUIRE(narrower.has_value()); + CHECK((*narrower)->flags() == DescriptorFlags::Read); +} + +TEST_CASE("contract: an open the parent may not make is NotPermitted before its flags are judged", + "[fs][contract][rights]") +{ + // wasmtime's order: the parent's rights first, then Directory with Create is Invalid. + auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); + REQUIRE(fixture.run(fixture.root().createDirectoryAt("d")).has_value()); + auto readOnly = fixture.openRoot(DescriptorFlags::Read); + REQUIRE(readOnly.has_value()); + + CHECK(outcomeOf(fixture.run((*readOnly)->openAt( + SymlinkPolicy::NoFollow, "d", OpenFlags::Directory | OpenFlags::Create, DescriptorFlags::Read))) + == FsErrorCode::NotPermitted); + CHECK(outcomeOf(fixture.run((*readOnly)->openAt(SymlinkPolicy::NoFollow, + "d", + OpenFlags::Directory, + DescriptorFlags::Read | DescriptorFlags::Write))) + == FsErrorCode::NotPermitted); + CHECK(outcomeOf(fixture.run(fixture.root().openAt( + SymlinkPolicy::NoFollow, "d", OpenFlags::Directory | OpenFlags::Create, DescriptorFlags::Read))) + == FsErrorCode::Invalid); +} + +TEST_CASE("contract: a read returns at most maxReadChunk bytes", "[fs][contract]") +{ + auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); + fixture.createFile("big", std::string(DescriptorFixture::MaxReadChunk * 3, 'x')); + auto file = fixture.run( + fixture.root().openAt(SymlinkPolicy::NoFollow, "big", OpenFlags::None, DescriptorFlags::Read)); + REQUIRE(file.has_value()); + + auto const chunk = fixture.run((*file)->read(std::size_t { 1 } << 30U, 0)); + REQUIRE(chunk.has_value()); + CHECK(chunk->bytes.size() == DescriptorFixture::MaxReadChunk); + CHECK(chunk->end == StreamEnd::More); +} + +TEST_CASE("contract: a foreign descriptor passed to renameAt is CrossDevice", "[fs][contract]") +{ + auto const kind = GENERATE(FixtureKind::InMemory, FixtureKind::Native); + auto fixture = DescriptorFixture::create(kind); + auto other = DescriptorFixture::create(kind); + fixture.createFile("f", "content"); + + auto const moved = fixture.run(fixture.root().renameAt("f", &other.root(), "g")); + REQUIRE_FALSE(moved.has_value()); + CHECK(moved.error().code == FsErrorCode::CrossDevice); + CHECK(fixture.run(fixture.root().statAt(SymlinkPolicy::NoFollow, "f")).has_value()); + CHECK(outcomeOf(other.run(other.root().statAt(SymlinkPolicy::NoFollow, "g"))) == FsErrorCode::NoEntry); +} + +TEST_CASE("contract: names compare under the policy's case rule", "[fs][contract]") +{ + // In-memory only, for good: the native case rule is the volume's, not the policy's. + SECTION("posix: names differing in case are two names") + { + auto fixture = DescriptorFixture::create(FixtureKind::InMemory, core::fs::posixPathPolicy()); + fixture.createFile("Name.txt", "upper"); + CHECK(fixture + .run(fixture.root().openAt(SymlinkPolicy::NoFollow, + "name.txt", + OpenFlags::Create | OpenFlags::Exclusive, + DescriptorFlags::Write)) + .has_value()); + } + SECTION("windows: names differing in case are one name") + { + auto fixture = DescriptorFixture::create(FixtureKind::InMemory, core::fs::windowsPathPolicy()); + fixture.createFile("Name.txt", "upper"); + CHECK(outcomeOf(fixture.run(fixture.root().openAt(SymlinkPolicy::NoFollow, + "name.txt", + OpenFlags::Create | OpenFlags::Exclusive, + DescriptorFlags::Write))) + == FsErrorCode::Exist); + auto file = fixture.run(fixture.root().openAt( + SymlinkPolicy::NoFollow, "NAME.TXT", OpenFlags::None, DescriptorFlags::Read)); + REQUIRE(file.has_value()); + CHECK(textOf(fixture.run((*file)->read(64, 0)).value().bytes) == "upper"); + } +} + +TEST_CASE("contract: a symbolic link is followed only beneath its descriptor", "[fs][contract]") +{ + auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); + if (fixture.requireSymlinks() == SymlinkSupport::Unavailable) + SKIP("this file system cannot create symbolic links"); + REQUIRE(fixture.run(fixture.root().createDirectoryAt("a")).has_value()); + fixture.createFile("target", "through the link"); + + CHECK(outcomeOf(fixture.run(fixture.root().symlinkAt("/etc/passwd", "absolute"))) + == FsErrorCode::NotPermitted); + REQUIRE(fixture.run(fixture.root().symlinkAt("../target", "a/inside")).has_value()); + REQUIRE(fixture.run(fixture.root().symlinkAt("../../outside", "a/escape")).has_value()); + REQUIRE(fixture.run(fixture.root().symlinkAt("loop", "loop")).has_value()); + + auto inside = fixture.run( + fixture.root().openAt(SymlinkPolicy::Follow, "a/inside", OpenFlags::None, DescriptorFlags::Read)); + REQUIRE(inside.has_value()); + CHECK(textOf(fixture.run((*inside)->read(64, 0)).value().bytes) == "through the link"); + CHECK(fixture.run(fixture.root().readlinkAt("a/inside")).value() == "../target"); + CHECK(fixture.run(fixture.root().statAt(SymlinkPolicy::NoFollow, "a/inside"))->type + == DescriptorType::SymbolicLink); + CHECK(outcomeOf(fixture.run(fixture.root().openAt( + SymlinkPolicy::NoFollow, "a/inside", OpenFlags::None, DescriptorFlags::Read))) + == FsErrorCode::Loop); + + CHECK(outcomeOf(fixture.run(fixture.root().openAt( + SymlinkPolicy::Follow, "a/escape", OpenFlags::None, DescriptorFlags::Read))) + == FsErrorCode::NotPermitted); + CHECK(outcomeOf(fixture.run(fixture.root().statAt(SymlinkPolicy::Follow, "loop"))) == FsErrorCode::Loop); + CHECK(outcomeOf( + fixture.run(fixture.root().linkAt(SymlinkPolicy::Follow, "target", &fixture.root(), "hard"))) + == FsErrorCode::Invalid); +} + +TEST_CASE("contract: a directory descriptor never carries Write", "[fs][contract]") +{ + auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); + REQUIRE(fixture.run(fixture.root().createDirectoryAt("d")).has_value()); + CHECK(outcomeOf(fixture.run(fixture.root().openAt( + SymlinkPolicy::NoFollow, "d", OpenFlags::None, DescriptorFlags::Read | DescriptorFlags::Write))) + == FsErrorCode::IsDirectory); + CHECK(outcomeOf(fixture.run(fixture.root().openAt( + SymlinkPolicy::NoFollow, "d", OpenFlags::Directory | OpenFlags::Create, DescriptorFlags::Read))) + == FsErrorCode::Invalid); +} + +namespace +{ + +/// What a rights case calls its operation on. +enum class Holder : std::uint8_t +{ + File, ///< `f`, a regular file; it can carry Read and Write. + Directory, ///< The root; it can carry Read and MutateDirectory. +}; + +/// One operation of the rights table, and how to call it on a holder in a fixture that holds `f` +/// (a file with content), `sub` (an empty directory) and, where the file system has them, `link` (a +/// symbolic link to `f`). +struct RightsCase +{ + Operation operation; + DescriptorFlags required; ///< What its row must say, pinned here rather than read from the table. + Holder holder; + std::function call; +}; + +std::vector rightsCases() +{ + using enum Operation; + using enum Holder; + auto const nf = SymlinkPolicy::NoFollow; + return { + { Read, + DescriptorFlags::Read, + File, + [](auto& fx, auto& d) { return outcomeOf(fx.run(d.read(1, 0))); } }, + { Write, + DescriptorFlags::Write, + File, + [](auto& fx, auto& d) { return outcomeOf(fx.run(d.write(bytesOf("x"), 0))); } }, + { Append, + DescriptorFlags::Write, + File, + [](auto& fx, auto& d) { return outcomeOf(fx.run(d.append(bytesOf("x")))); } }, + { Advise, + DescriptorFlags::None, + File, + [](auto& fx, auto& d) { return outcomeOf(fx.run(d.advise(0, 0, Advice::Normal))); } }, + { Sync, DescriptorFlags::None, File, [](auto& fx, auto& d) { return outcomeOf(fx.run(d.sync())); } }, + { SetSize, + DescriptorFlags::Write, + File, + [](auto& fx, auto& d) { return outcomeOf(fx.run(d.setSize(1))); } }, + { SetTimes, + DescriptorFlags::Write | DescriptorFlags::MutateDirectory, + File, + [](auto& fx, auto& d) { return outcomeOf(fx.run(d.setTimes(SetToNow {}, SetToNow {}))); } }, + { Stat, DescriptorFlags::None, File, [](auto& fx, auto& d) { return outcomeOf(fx.run(d.stat())); } }, + { MetadataHash, + DescriptorFlags::None, + File, + [](auto& fx, auto& d) { return outcomeOf(fx.run(d.metadataHash())); } }, + { ReadDirectory, + DescriptorFlags::Read, + Directory, + [](auto& fx, auto& d) { return outcomeOf(fx.run(d.readDirectory())); } }, + { OpenAt, + DescriptorFlags::Read, + Directory, + [nf](auto& fx, auto& d) { + return outcomeOf(fx.run(d.openAt(nf, "f", OpenFlags::None, DescriptorFlags::None))); + } }, + { CreateDirectoryAt, + DescriptorFlags::MutateDirectory, + Directory, + [](auto& fx, auto& d) { return outcomeOf(fx.run(d.createDirectoryAt("new"))); } }, + { StatAt, + DescriptorFlags::Read, + Directory, + [nf](auto& fx, auto& d) { return outcomeOf(fx.run(d.statAt(nf, "f"))); } }, + { SetTimesAt, + DescriptorFlags::MutateDirectory, + Directory, + [nf](auto& fx, auto& d) { + return outcomeOf(fx.run(d.setTimesAt(nf, "f", SetToNow {}, SetToNow {}))); + } }, + { LinkAt, + DescriptorFlags::MutateDirectory, + Directory, + [nf](auto& fx, auto& d) { return outcomeOf(fx.run(d.linkAt(nf, "f", &d, "hard"))); } }, + { ReadlinkAt, + DescriptorFlags::Read, + Directory, + [](auto& fx, auto& d) { return outcomeOf(fx.run(d.readlinkAt("link"))); } }, + { RemoveDirectoryAt, + DescriptorFlags::MutateDirectory, + Directory, + [](auto& fx, auto& d) { return outcomeOf(fx.run(d.removeDirectoryAt("sub"))); } }, + { RenameAt, + DescriptorFlags::MutateDirectory, + Directory, + [](auto& fx, auto& d) { return outcomeOf(fx.run(d.renameAt("f", &d, "renamed"))); } }, + { SymlinkAt, + DescriptorFlags::MutateDirectory, + Directory, + [](auto& fx, auto& d) { return outcomeOf(fx.run(d.symlinkAt("f", "newlink"))); } }, + { UnlinkFileAt, + DescriptorFlags::MutateDirectory, + Directory, + [](auto& fx, auto& d) { return outcomeOf(fx.run(d.unlinkFileAt("f"))); } }, + { MetadataHashAt, + DescriptorFlags::Read, + Directory, + [nf](auto& fx, auto& d) { return outcomeOf(fx.run(d.metadataHashAt(nf, "f"))); } }, + }; +} + +/// Calls @p rightsCase on a holder carrying @p flags, in a fixture of its own. +Outcome callWith(FixtureKind kind, RightsCase const& rightsCase, DescriptorFlags flags) +{ + auto fixture = DescriptorFixture::create(kind); + fixture.createFile("f", "content"); + REQUIRE(fixture.run(fixture.root().createDirectoryAt("sub")).has_value()); + if (fixture.requireSymlinks() == SymlinkSupport::Available) + REQUIRE(fixture.run(fixture.root().symlinkAt("f", "link")).has_value()); + auto holder = + rightsCase.holder == Holder::File + ? fixture.run(fixture.root().openAt(SymlinkPolicy::NoFollow, "f", OpenFlags::None, flags)) + : fixture.openRoot(flags); + REQUIRE(holder.has_value()); + return rightsCase.call(fixture, **holder); +} + +DescriptorFlags without(DescriptorFlags set, DescriptorFlags removed) +{ + return static_cast(static_cast(set) & ~static_cast(removed)); +} + +} // namespace + +TEST_CASE("contract: every operation needs the rights its row names", "[fs][contract][rights]") +{ + auto const kind = GENERATE(FixtureKind::InMemory, FixtureKind::Native); + auto const cases = rightsCases(); + REQUIRE(cases.size() == static_cast(Operation::Last)); + for (auto const& row: core::fs::rightsTable()) + { + auto const rightsCase = std::ranges::find(cases, row.operation, &RightsCase::operation); + REQUIRE(rightsCase != cases.end()); + CAPTURE(static_cast(row.operation), static_cast(row.required)); + CHECK(row.required == rightsCase->required); + if (rightsCase->required == DescriptorFlags::None) + { + CHECK(callWith(kind, *rightsCase, DescriptorFlags::None) != FsErrorCode::NotPermitted); + continue; + } + auto const all = rightsCase->holder == Holder::File + ? DescriptorFlags::Read | DescriptorFlags::Write + : DescriptorFlags::Read | DescriptorFlags::MutateDirectory; + CHECK(callWith(kind, *rightsCase, without(all, rightsCase->required)) == FsErrorCode::NotPermitted); + CHECK(callWith(kind, *rightsCase, all) != FsErrorCode::NotPermitted); + } + + // SetTimes's row offers a choice, and the loop above takes the file's side of it (Write); the + // directory's side is MutateDirectory. + auto fixture = DescriptorFixture::create(kind); + auto readOnly = fixture.openRoot(DescriptorFlags::Read); + auto mutating = fixture.openRoot(DescriptorFlags::Read | DescriptorFlags::MutateDirectory); + REQUIRE(readOnly.has_value()); + REQUIRE(mutating.has_value()); + CHECK(outcomeOf(fixture.run((*readOnly)->setTimes(SetToNow {}, SetToNow {}))) + == FsErrorCode::NotPermitted); + CHECK(outcomeOf(fixture.run((*mutating)->setTimes(SetToNow {}, SetToNow {}))) == std::nullopt); +} + +TEST_CASE("contract: a file descriptor resolves no path and carries no MutateDirectory", "[fs][contract]") +{ + auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); + fixture.createFile("f", "content"); + fixture.createFile("g", "other"); + + auto file = fixture.run(fixture.root().openAt(SymlinkPolicy::NoFollow, + "f", + OpenFlags::None, + DescriptorFlags::Read | DescriptorFlags::MutateDirectory)); + REQUIRE(file.has_value()); + CHECK((*file)->flags() == DescriptorFlags::Read); + CHECK(outcomeOf(fixture.run((*file)->statAt(SymlinkPolicy::NoFollow, "x"))) == FsErrorCode::NotDirectory); + CHECK(outcomeOf(fixture.run( + (*file)->openAt(SymlinkPolicy::NoFollow, "x", OpenFlags::None, DescriptorFlags::Read))) + == FsErrorCode::NotDirectory); + CHECK(outcomeOf(fixture.run((*file)->createDirectoryAt("x"))) == FsErrorCode::NotPermitted); + CHECK(outcomeOf(fixture.run(fixture.root().renameAt("g", file->get(), "x"))) + == FsErrorCode::NotPermitted); + CHECK(fixture.run(fixture.root().statAt(SymlinkPolicy::NoFollow, "g")).has_value()); + CHECK(outcomeOf(fixture.run((*file)->setTimes(SetToNow {}, SetToNow {}))) == FsErrorCode::NotPermitted); + + auto writable = + fixture.run(fixture.root().openAt(SymlinkPolicy::NoFollow, + "f", + OpenFlags::None, + DescriptorFlags::Write | DescriptorFlags::MutateDirectory)); + REQUIRE(writable.has_value()); + CHECK((*writable)->flags() == DescriptorFlags::Write); + CHECK(fixture.run((*writable)->setTimes(SetToNow {}, SetToNow {})).has_value()); +} + +TEST_CASE("contract: a trailing slash requires a directory", "[fs][contract]") +{ + auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); + auto& root = fixture.root(); + fixture.createFile("file", "content"); + REQUIRE(fixture.run(root.createDirectoryAt("dir")).has_value()); + auto const nf = SymlinkPolicy::NoFollow; + auto const notDirectory = Outcome { FsErrorCode::NotDirectory }; + + SECTION("a file named with a trailing slash") + { + CHECK(outcomeOf(fixture.run(root.openAt(nf, "file/", OpenFlags::None, DescriptorFlags::Read))) + == notDirectory); + CHECK(outcomeOf(fixture.run(root.statAt(nf, "file/"))) == notDirectory); + CHECK(outcomeOf(fixture.run(root.statAt(nf, "file/."))) == notDirectory); + CHECK(outcomeOf(fixture.run(root.unlinkFileAt("file/"))) == notDirectory); + CHECK(outcomeOf(fixture.run(root.removeDirectoryAt("file/"))) == notDirectory); + CHECK(outcomeOf(fixture.run(root.renameAt("file/", &root, "moved"))) == notDirectory); + CHECK(outcomeOf(fixture.run(root.renameAt("file", &root, "moved/"))) == notDirectory); + CHECK(fixture.run(root.statAt(nf, "file"))->type == DescriptorType::RegularFile); + CHECK(outcomeOf(fixture.run(root.statAt(nf, "moved"))) == FsErrorCode::NoEntry); + } + SECTION("nothing but a directory is created with a trailing slash") + { + auto const created = + outcomeOf(fixture.run(root.openAt(nf, "new.txt/", OpenFlags::Create, DescriptorFlags::Write))); + CHECK((created == notDirectory || created == FsErrorCode::IsDirectory)); + CHECK(outcomeOf(fixture.run(root.symlinkAt("file", "newlink/"))).has_value()); + CHECK(outcomeOf(fixture.run(root.linkAt(nf, "file", &root, "hard/"))).has_value()); + for (auto const* name: { "new.txt", "newlink", "hard" }) + { + CAPTURE(name); + CHECK(outcomeOf(fixture.run(root.statAt(nf, name))) == FsErrorCode::NoEntry); + } + REQUIRE(fixture.run(root.createDirectoryAt("made/")).has_value()); + CHECK(fixture.run(root.statAt(nf, "made"))->type == DescriptorType::Directory); + } + SECTION("a directory named with a trailing slash") + { + CHECK(fixture.run(root.statAt(nf, "dir/"))->type == DescriptorType::Directory); + CHECK(outcomeOf(fixture.run(root.unlinkFileAt("dir/"))) == FsErrorCode::IsDirectory); + REQUIRE(fixture.run(root.renameAt("dir/", &root, "moved/")).has_value()); + REQUIRE(fixture.run(root.removeDirectoryAt("moved/")).has_value()); + CHECK(outcomeOf(fixture.run(root.statAt(nf, "moved"))) == FsErrorCode::NoEntry); + } + SECTION("a trailing slash follows a final symbolic link") + { + if (fixture.requireSymlinks() == SymlinkSupport::Unavailable) + SKIP("this file system cannot create symbolic links"); + REQUIRE(fixture.run(root.symlinkAt("dir", "dirlink")).has_value()); + REQUIRE(fixture.run(root.symlinkAt("file", "filelink")).has_value()); + CHECK(fixture.run(root.statAt(nf, "dirlink"))->type == DescriptorType::SymbolicLink); + CHECK(fixture.run(root.statAt(nf, "dirlink/"))->type == DescriptorType::Directory); + CHECK(fixture.run(root.statAt(nf, "dirlink/."))->type == DescriptorType::Directory); + CHECK(outcomeOf(fixture.run(root.statAt(nf, "filelink/"))) == notDirectory); + + // Removing or moving `dirlink/` acts on the link, which is no directory: Linux answers + // ENOTDIR, and neither the link nor the directory it names may change. + CHECK(outcomeOf(fixture.run(root.removeDirectoryAt("dirlink/"))) == notDirectory); + CHECK(outcomeOf(fixture.run(root.renameAt("dirlink/", &root, "moved"))) == notDirectory); + CHECK(outcomeOf(fixture.run(root.renameAt("dir", &root, "dirlink/"))) == notDirectory); + CHECK(outcomeOf(fixture.run(root.unlinkFileAt("dirlink/"))) == notDirectory); + CHECK(fixture.run(root.statAt(nf, "dirlink"))->type == DescriptorType::SymbolicLink); + CHECK(fixture.run(root.statAt(nf, "dir"))->type == DescriptorType::Directory); + CHECK(outcomeOf(fixture.run(root.statAt(nf, "moved"))) == FsErrorCode::NoEntry); + + // The same on a link to a file: the trailing `/` makes neither the link nor the file the + // object of the call. + CHECK(outcomeOf(fixture.run(root.removeDirectoryAt("filelink/"))) == notDirectory); + CHECK(outcomeOf(fixture.run(root.renameAt("filelink/", &root, "moved"))) == notDirectory); + CHECK(outcomeOf(fixture.run(root.renameAt("file", &root, "filelink/"))) == notDirectory); + CHECK(outcomeOf(fixture.run(root.unlinkFileAt("filelink/"))) == notDirectory); + CHECK(fixture.run(root.statAt(nf, "filelink"))->type == DescriptorType::SymbolicLink); + CHECK(fixture.run(root.statAt(nf, "file"))->type == DescriptorType::RegularFile); + CHECK(outcomeOf(fixture.run(root.statAt(nf, "moved"))) == FsErrorCode::NoEntry); + } +} + +TEST_CASE("contract: a directory named through its own dot is not removed", "[fs][contract]") +{ + // `dir/.` names the directory itself, not an entry of its parent: Linux's rmdir answers EINVAL. + auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); + auto& root = fixture.root(); + REQUIRE(fixture.run(root.createDirectoryAt("dir")).has_value()); + + CHECK(outcomeOf(fixture.run(root.removeDirectoryAt("dir/."))) == FsErrorCode::Invalid); + CHECK(outcomeOf(fixture.run(root.removeDirectoryAt("dir/./"))) == FsErrorCode::Invalid); + CHECK(fixture.run(root.statAt(SymlinkPolicy::NoFollow, "dir"))->type == DescriptorType::Directory); +} + +TEST_CASE("contract: Create opens no directory and creates nothing through a link", "[fs][contract]") +{ + auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); + REQUIRE(fixture.run(fixture.root().createDirectoryAt("dir")).has_value()); + CHECK(outcomeOf(fixture.run(fixture.root().openAt( + SymlinkPolicy::NoFollow, "dir", OpenFlags::Create, DescriptorFlags::Read))) + == FsErrorCode::IsDirectory); + + if (fixture.requireSymlinks() == SymlinkSupport::Unavailable) + SKIP("this file system cannot create symbolic links"); + REQUIRE(fixture.run(fixture.root().symlinkAt("missing", "dangling")).has_value()); + CHECK(outcomeOf(fixture.run(fixture.root().openAt(SymlinkPolicy::Follow, + "dangling", + OpenFlags::Create | OpenFlags::Exclusive, + DescriptorFlags::Write))) + == FsErrorCode::Exist); + CHECK(outcomeOf(fixture.run(fixture.root().statAt(SymlinkPolicy::NoFollow, "missing"))) + == FsErrorCode::NoEntry); +} + +TEST_CASE("contract: a link target is checked when the link is created", "[fs][contract]") +{ + auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); + if (fixture.requireSymlinks() == SymlinkSupport::Unavailable) + SKIP("this file system cannot create symbolic links"); + CHECK(outcomeOf(fixture.run(fixture.root().symlinkAt(std::string { "a\0b", 3 }, "nul"))) + == FsErrorCode::Invalid); + CHECK(outcomeOf(fixture.run(fixture.root().symlinkAt("", "empty"))) == FsErrorCode::NoEntry); + CHECK(outcomeOf(fixture.run(fixture.root().symlinkAt("/abs", "absolute"))) == FsErrorCode::NotPermitted); +} + +TEST_CASE("contract: a Windows drive in a link target is absolute", "[fs][contract]") +{ + // In-memory only, for good: it is the Windows policy's rule, run on every OS. + auto fixture = DescriptorFixture::create(FixtureKind::InMemory, core::fs::windowsPathPolicy()); + for (auto const* target: { "C:\\x", "C:x", "c:/x" }) + { + CAPTURE(target); + CHECK(outcomeOf(fixture.run(fixture.root().symlinkAt(target, "drive"))) == FsErrorCode::NotPermitted); + } +} + +namespace +{ + +/// Opens `name` beneath @p fixture's root, `Read | Write`, creating it. +std::unique_ptr createReadWrite(DescriptorFixture const& fixture, std::string name) +{ + auto file = fixture.run(fixture.root().openAt(SymlinkPolicy::NoFollow, + std::move(name), + OpenFlags::Create | OpenFlags::Exclusive, + DescriptorFlags::Read | DescriptorFlags::Write)); + REQUIRE(file.has_value()); + return std::move(*file); +} + +/// A native time comes from the kernel's clock, which may lag the C++ one by a tick and be stored +/// at a coarser grain: an instant counts as within a window this much wider on each side. +constexpr auto ClockSlack = std::chrono::seconds { 2 }; + +/// @return Whether @p time lies in [@p before, @p after], widened by @c ClockSlack. +bool within(FileTime time, + std::chrono::system_clock::time_point before, + std::chrono::system_clock::time_point after) +{ + return core::fs::test::fileTimeOf(before - ClockSlack) <= time + && time <= core::fs::test::fileTimeOf(after + ClockSlack); +} + +} // namespace + +TEST_CASE("contract: stat reports type, size and a plausible modification time", "[fs][contract]") +{ + auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); + auto const before = std::chrono::system_clock::now(); + fixture.createFile("f", "hello"); + auto const after = std::chrono::system_clock::now(); + + auto file = fixture.run( + fixture.root().openAt(SymlinkPolicy::NoFollow, "f", OpenFlags::None, DescriptorFlags::Read)); + REQUIRE(file.has_value()); + auto const stat = fixture.run((*file)->stat()); + REQUIRE(stat.has_value()); + CHECK(stat->type == DescriptorType::RegularFile); + CHECK(stat->size == 5); + CHECK(stat->linkCount == 1); + REQUIRE(stat->modified.has_value()); + // The model stamps the injected clock; a native file system, the kernel's. + if (fixture.kind() == FixtureKind::InMemory) + CHECK(*stat->modified == core::fs::test::fileTimeOf(fixture.clock().now())); + else + CHECK(within(*stat->modified, before, after)); + CHECK(fixture.run((*file)->type()).value() == DescriptorType::RegularFile); + CHECK(fixture.run(fixture.root().stat())->type == DescriptorType::Directory); + CHECK(fixture.run(fixture.root().statAt(SymlinkPolicy::NoFollow, "f"))->size == 5); +} + +TEST_CASE("contract: setTimes sets an explicit instant, and SetToNow the file system's clock", + "[fs][contract]") +{ + auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); + auto const file = createReadWrite(fixture, "f"); + // A multiple of 100 ns, the grain of a Windows FILETIME. + auto const explicitTime = FileTime { .seconds = 1'600'000'000, .nanoseconds = 123'456'700 }; + + REQUIRE(fixture.run(file->setTimes(explicitTime, explicitTime)).has_value()); + auto const set = fixture.run(file->stat()); + REQUIRE(set.has_value()); + CHECK(set->accessed == explicitTime); + CHECK(set->modified == explicitTime); + + fixture.clock().advance(std::chrono::hours { 24 }); + auto const before = std::chrono::system_clock::now(); + REQUIRE(fixture.run(file->setTimes(NoChange {}, SetToNow {})).has_value()); + auto const after = std::chrono::system_clock::now(); + auto const now = fixture.run(file->stat()); + REQUIRE(now.has_value()); + CHECK(now->accessed == explicitTime); + REQUIRE(now->modified.has_value()); + if (fixture.nowSource() == NowSource::InjectedClock) + CHECK(*now->modified == core::fs::test::fileTimeOf(fixture.clock().now())); + else + CHECK(within(*now->modified, before, after)); + + auto const atTime = FileTime { .seconds = 1'500'000'000, .nanoseconds = 0 }; + REQUIRE(fixture.run(fixture.root().setTimesAt(SymlinkPolicy::NoFollow, "f", atTime, atTime)).has_value()); + CHECK(fixture.run(file->stat())->modified == atTime); +} + +TEST_CASE("contract: advise accepts every Advice", "[fs][contract]") +{ + auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); + fixture.createFile("f", "content"); + auto file = fixture.run( + fixture.root().openAt(SymlinkPolicy::NoFollow, "f", OpenFlags::None, DescriptorFlags::Read)); + REQUIRE(file.has_value()); + using enum Advice; + for (auto const advice: { Normal, Sequential, Random, WillNeed, DontNeed, NoReuse }) + { + CAPTURE(static_cast(advice)); + CHECK(outcomeOf(fixture.run((*file)->advise(0, 0, advice))) == std::nullopt); + CHECK(outcomeOf(fixture.run((*file)->advise(2, 3, advice))) == std::nullopt); + } +} + +TEST_CASE("contract: a write at offset 0 after an append lands at 0", "[fs][contract]") +{ + auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); + auto const file = createReadWrite(fixture, "f"); + REQUIRE(fixture.run(file->write(bytesOf("abcd"), 0)).value() == 4); + REQUIRE(fixture.run(file->append(bytesOf("XY"))).value() == 2); + REQUIRE(fixture.run(file->write(bytesOf("Z"), 0)).value() == 1); + REQUIRE(fixture.run(file->append(bytesOf("!"))).value() == 1); + CHECK(textOf(fixture.run(file->read(64, 0)).value().bytes) == "ZbcdXY!"); +} + +TEST_CASE("contract: a write changes the metadata hash, and nothing else does", "[fs][contract]") +{ + auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); + auto const file = createReadWrite(fixture, "f"); + REQUIRE(fixture.run(file->write(bytesOf("content"), 0)).has_value()); + + auto const first = fixture.run(file->metadataHash()); + REQUIRE(first.has_value()); + CHECK(fixture.run(file->metadataHash()).value() == *first); + std::ignore = fixture.run(file->read(64, 0)); + CHECK(fixture.run(file->metadataHash()).value() == *first); + + // The write grows the file, so its size changes even where the clock's grain hides the time. + REQUIRE(fixture.run(file->write(bytesOf("!"), 7)).has_value()); + auto const second = fixture.run(file->metadataHash()); + REQUIRE(second.has_value()); + CHECK(*second != *first); +} + +TEST_CASE("contract: an open of a link without following changes neither the link nor its target", + "[fs][contract]") +{ + auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); + if (fixture.requireSymlinks() == SymlinkSupport::Unavailable) + SKIP("this file system cannot create symbolic links"); + auto& root = fixture.root(); + fixture.createFile("target", "keep"); + REQUIRE(fixture.run(root.symlinkAt("target", "link")).has_value()); + + for (auto const open: { OpenFlags::Create | OpenFlags::Truncate, OpenFlags::Truncate, OpenFlags::Create }) + { + CAPTURE(static_cast(open)); + CHECK( + outcomeOf(fixture.run(root.openAt(SymlinkPolicy::NoFollow, "link", open, DescriptorFlags::Write))) + == FsErrorCode::Loop); + } + CHECK(fixture.run(root.readlinkAt("link")).value() == "target"); + CHECK(fixture.run(root.statAt(SymlinkPolicy::NoFollow, "link"))->type == DescriptorType::SymbolicLink); + CHECK(fixture.run(root.statAt(SymlinkPolicy::NoFollow, "target"))->size == 4); +} + +TEST_CASE("contract: openAt creates, truncates and requires a directory as it is asked", "[fs][contract]") +{ + auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); + auto& root = fixture.root(); + fixture.createFile("f", "content"); + REQUIRE(fixture.run(root.createDirectoryAt("d")).has_value()); + auto const nf = SymlinkPolicy::NoFollow; + auto const sizeOf = [&](std::string name) { + return fixture.run(root.statAt(nf, std::move(name)))->size; + }; + + SECTION("Create without Exclusive opens what exists and creates what does not") + { + REQUIRE(fixture.run(root.openAt(nf, "f", OpenFlags::Create, DescriptorFlags::Write)).has_value()); + CHECK(sizeOf("f") == 7); + REQUIRE(fixture.run(root.openAt(nf, "g", OpenFlags::Create, DescriptorFlags::Write)).has_value()); + CHECK(fixture.run(root.statAt(nf, "g"))->type == DescriptorType::RegularFile); + CHECK(sizeOf("g") == 0); + } + SECTION("Truncate empties what exists, Create | Truncate too") + { + auto file = fixture.run( + root.openAt(nf, "f", OpenFlags::Truncate, DescriptorFlags::Read | DescriptorFlags::Write)); + REQUIRE(file.has_value()); + CHECK(sizeOf("f") == 0); + CHECK(fixture.run((*file)->read(64, 0)).value().bytes.empty()); + fixture.createFile("h", "more content"); + REQUIRE( + fixture.run(root.openAt(nf, "h", OpenFlags::Create | OpenFlags::Truncate, DescriptorFlags::Write)) + .has_value()); + CHECK(sizeOf("h") == 0); + CHECK(outcomeOf(fixture.run(root.openAt(nf, "missing", OpenFlags::Truncate, DescriptorFlags::Write))) + == FsErrorCode::NoEntry); + } + SECTION("Directory opens a directory and refuses anything else") + { + auto directory = fixture.run(root.openAt(nf, "d", OpenFlags::Directory, DescriptorFlags::Read)); + REQUIRE(directory.has_value()); + CHECK(fixture.run((*directory)->type()).value() == DescriptorType::Directory); + CHECK(outcomeOf(fixture.run(root.openAt(nf, "f", OpenFlags::Directory, DescriptorFlags::Read))) + == FsErrorCode::NotDirectory); + CHECK(sizeOf("f") == 7); + } +} + +TEST_CASE("contract: a final link is followed where the call says so, and no further", "[fs][contract]") +{ + auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); + if (fixture.requireSymlinks() == SymlinkSupport::Unavailable) + SKIP("this file system cannot create symbolic links"); + auto& root = fixture.root(); + fixture.createFile("f", "content"); + REQUIRE(fixture.run(root.symlinkAt("f", "link")).has_value()); + REQUIRE(fixture.run(root.symlinkAt("link", "chain")).has_value()); + REQUIRE(fixture.run(root.symlinkAt("self", "self")).has_value()); + REQUIRE(fixture.run(root.symlinkAt("..", "up")).has_value()); + REQUIRE(fixture.run(root.symlinkAt("absent", "dangling")).has_value()); + auto const follow = SymlinkPolicy::Follow; + + CHECK(fixture.run(root.statAt(follow, "chain"))->type == DescriptorType::RegularFile); + CHECK(fixture.run(root.statAt(follow, "chain"))->size == 7); + CHECK(fixture.run(root.statAt(SymlinkPolicy::NoFollow, "chain"))->type == DescriptorType::SymbolicLink); + auto file = fixture.run(root.openAt(follow, "chain", OpenFlags::None, DescriptorFlags::Read)); + REQUIRE(file.has_value()); + CHECK(textOf(fixture.run((*file)->read(64, 0)).value().bytes) == "content"); + CHECK(outcomeOf(fixture.run(root.statAt(follow, "self"))) == FsErrorCode::Loop); + CHECK(outcomeOf(fixture.run(root.statAt(follow, "up"))) == FsErrorCode::NotPermitted); + CHECK(outcomeOf(fixture.run(root.statAt(follow, "dangling"))) == FsErrorCode::NoEntry); + + // Create through a dangling link creates its target, as POSIX open(O_CREAT) does. + REQUIRE( + fixture.run(root.openAt(follow, "dangling", OpenFlags::Create, DescriptorFlags::Write)).has_value()); + CHECK(fixture.run(root.statAt(SymlinkPolicy::NoFollow, "absent"))->type == DescriptorType::RegularFile); +} + +TEST_CASE("contract: a directory's descriptor reads no bytes", "[fs][contract]") +{ + // POSIX's pread answers EISDIR, Windows' ReadFile ERROR_INVALID_FUNCTION: both are IsDirectory. + auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); + auto& root = fixture.root(); + REQUIRE(fixture.run(root.createDirectoryAt("dir")).has_value()); + auto directory = + fixture.run(root.openAt(SymlinkPolicy::NoFollow, "dir", OpenFlags::Directory, DescriptorFlags::Read)); + REQUIRE(directory.has_value()); + CHECK(outcomeOf(fixture.run((*directory)->read(16, 0))) == FsErrorCode::IsDirectory); +} diff --git a/src/core/fs/DescriptorEscape_test.cpp b/src/core/fs/DescriptorEscape_test.cpp new file mode 100644 index 00000000..1e60299b --- /dev/null +++ b/src/core/fs/DescriptorEscape_test.cpp @@ -0,0 +1,367 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// No path reaches outside the directory it is resolved beneath: every *At operation, with and +// without following, against every way a path can try to leave (a link up, an absolute link, `..` +// past the root, a final link to `..`), under both strategies (openat2 and the component walk on +// Linux) and both kinds. An outside decoy sits where each escape would land, and every row checks +// it was left alone. Then the race: a directory swapped for an outward link while paths through it +// are resolved. +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using core::async::Task; +using core::fs::BeneathStrategy; +using core::fs::DescriptorFlags; +using core::fs::FileTime; +using core::fs::FsErrorCode; +using core::fs::OpenFlags; +using core::fs::SymlinkPolicy; +using core::fs::test::DescriptorFixture; +using core::fs::test::DirectoryLinkNature; +using core::fs::test::FixtureKind; +using core::fs::test::NativeDirectoryLinkNature; +using core::fs::test::Outcome; +using core::fs::test::outcomeOf; +using core::fs::test::SymlinkSupport; + +namespace +{ + +/// A file system to run a case over: a kind, and for a native one the strategy it resolves with. +struct Variant +{ + FixtureKind kind; + BeneathStrategy strategy; +}; + +/// Both kinds, with both strategies for the native one. +std::vector variants() +{ + auto all = std::vector {}; + for (auto const kind: { FixtureKind::InMemory, FixtureKind::Native }) + { + if (kind == FixtureKind::InMemory) + all.push_back({ .kind = kind, .strategy = BeneathStrategy::Best }); + else + for (auto const strategy: { BeneathStrategy::Best, BeneathStrategy::ComponentWalk }) + all.push_back({ .kind = kind, .strategy = strategy }); + } + return all; +} + +std::string_view nameOf(Variant const& variant) +{ + if (variant.kind == FixtureKind::InMemory) + return "in-memory"; + return variant.strategy == BeneathStrategy::Best ? "native, Best" : "native, ComponentWalk"; +} + +/// How a path tries to leave the root. +enum class Shape : std::uint8_t +{ + UpLink, ///< `up/`, where `up` links to `../`. + AbsoluteLink, ///< `abs/`, where `abs` links to the outside directory's absolute path. + TrailingUp, ///< `a/../..`: the parent of the root itself. + ClimbBeyond, ///< `a/../../`. + FinalLinkUp, ///< `uplink`, a link to `..`, as the final component. + FinalLinkOut, ///< `outlink`, a link to the outside file `../decoy`, as the final component. +}; + +constexpr auto Shapes = std::to_array({ Shape::UpLink, + Shape::AbsoluteLink, + Shape::TrailingUp, + Shape::ClimbBeyond, + Shape::FinalLinkUp, + Shape::FinalLinkOut }); + +std::string_view nameOf(Shape shape) +{ + switch (shape) + { + case Shape::UpLink: return "up/"; + case Shape::AbsoluteLink: return "abs/"; + case Shape::TrailingUp: return "a/../.."; + case Shape::ClimbBeyond: return "a/../../"; + case Shape::FinalLinkUp: return "uplink"; + case Shape::FinalLinkOut: return "outlink"; + } + return "?"; +} + +/// @return The path of @p shape aimed at @p name beside the root. +std::string pathOf(Shape shape, std::string_view name) +{ + switch (shape) + { + case Shape::UpLink: return "up/" + std::string { name }; + case Shape::AbsoluteLink: return "abs/" + std::string { name }; + case Shape::TrailingUp: return "a/../.."; + case Shape::ClimbBeyond: return "a/../../" + std::string { name }; + case Shape::FinalLinkUp: return "uplink"; + case Shape::FinalLinkOut: return "outlink"; + } + return {}; +} + +/// What one row starts: the fixture, the policy and the shaped path. +struct Call +{ + DescriptorFixture const* fixture = nullptr; + SymlinkPolicy policy = SymlinkPolicy::NoFollow; + std::string path; +}; + +/// One operation of the table. +struct EscapeOp +{ + std::string_view operation; + std::string_view aimedAt; ///< What beside the root an escape would reach. + Task (*start)(Call); + /// What it answers where the path is `uplink` and the link is not followed (`NoFollow`, or an + /// operation that never follows its final component): it acts on the link, inside the root. + Outcome onFinalLink; +}; + +/// An explicit time no file in a fixture has, so a setTimes that escaped shows in the decoy. +constexpr auto Stamp = FileTime { .seconds = 1'000'000, .nanoseconds = 0 }; + +constexpr auto Ops = std::to_array({ + { .operation = "openAt(Create|Truncate)", + .aimedAt = "decoy", + .start = [](Call c) -> Task { + co_return outcomeOf(co_await c.fixture->root().openAt( + c.policy, c.path, OpenFlags::Create | OpenFlags::Truncate, DescriptorFlags::Write)); + }, + .onFinalLink = FsErrorCode::Loop }, + { .operation = "statAt", + .aimedAt = "decoy", + .start = [](Call c) -> Task { + co_return outcomeOf(co_await c.fixture->root().statAt(c.policy, c.path)); + }, + .onFinalLink = std::nullopt }, + { .operation = "setTimesAt", + .aimedAt = "decoy", + .start = [](Call c) -> Task { + co_return outcomeOf(co_await c.fixture->root().setTimesAt(c.policy, c.path, Stamp, Stamp)); + }, + .onFinalLink = std::nullopt }, + { .operation = "linkAt(from)", + .aimedAt = "decoy", + .start = [](Call c) -> Task { + auto& root = c.fixture->root(); + co_return outcomeOf(co_await root.linkAt(c.policy, c.path, &root, "fresh")); + }, + .onFinalLink = std::nullopt }, + { .operation = "linkAt(to)", + .aimedAt = "fresh", + .start = [](Call c) -> Task { + auto& root = c.fixture->root(); + co_return outcomeOf(co_await root.linkAt(c.policy, "f", &root, c.path)); + }, + .onFinalLink = FsErrorCode::Exist }, + { .operation = "readlinkAt", + .aimedAt = "decoy", + .start = [](Call c) -> Task { + co_return outcomeOf(co_await c.fixture->root().readlinkAt(c.path)); + }, + .onFinalLink = std::nullopt }, + { .operation = "removeDirectoryAt", + .aimedAt = "dir", + .start = [](Call c) -> Task { + co_return outcomeOf(co_await c.fixture->root().removeDirectoryAt(c.path)); + }, + .onFinalLink = FsErrorCode::NotDirectory }, + { .operation = "renameAt(from)", + .aimedAt = "decoy", + .start = [](Call c) -> Task { + auto& root = c.fixture->root(); + co_return outcomeOf(co_await root.renameAt(c.path, &root, "fresh")); + }, + .onFinalLink = std::nullopt }, + { .operation = "renameAt(to)", + .aimedAt = "decoy", + .start = [](Call c) -> Task { + auto& root = c.fixture->root(); + co_return outcomeOf(co_await root.renameAt("f", &root, c.path)); + }, + .onFinalLink = std::nullopt }, + { .operation = "symlinkAt", + .aimedAt = "fresh", + .start = [](Call c) -> Task { + co_return outcomeOf(co_await c.fixture->root().symlinkAt("../", c.path)); + }, + .onFinalLink = FsErrorCode::Exist }, + { .operation = "unlinkFileAt", + .aimedAt = "decoy", + .start = [](Call c) -> Task { + co_return outcomeOf(co_await c.fixture->root().unlinkFileAt(c.path)); + }, + .onFinalLink = std::nullopt }, + { .operation = "metadataHashAt", + .aimedAt = "decoy", + .start = [](Call c) -> Task { + co_return outcomeOf(co_await c.fixture->root().metadataHashAt(c.policy, c.path)); + }, + .onFinalLink = std::nullopt }, + { .operation = "createDirectoryAt", + .aimedAt = "fresh", + .start = [](Call c) -> Task { + co_return outcomeOf(co_await c.fixture->root().createDirectoryAt(c.path)); + }, + .onFinalLink = FsErrorCode::Exist }, +}); + +/// @return Whether @p op takes a @c SymlinkPolicy for its final component. +bool takesPolicy(EscapeOp const& op) +{ + constexpr auto WithPolicy = std::to_array({ "openAt(Create|Truncate)", + "statAt", + "setTimesAt", + "linkAt(from)", + "linkAt(to)", + "metadataHashAt" }); + return std::ranges::find(WithPolicy, op.operation) != WithPolicy.end(); +} + +/// @return Whether @p op is one of the two `linkAt` rows, which refuse `Follow` as `Invalid`. +bool isLinkAt(EscapeOp const& op) +{ + return op.operation.starts_with("linkAt"); +} + +/// What a row must answer (decision D4, ruling R9). +Outcome expectedOf(EscapeOp const& op, Variant const& variant, SymlinkPolicy policy, Shape shape) +{ + if (isLinkAt(op) && policy == SymlinkPolicy::Follow) + return FsErrorCode::Invalid; + if ((shape == Shape::FinalLinkUp || shape == Shape::FinalLinkOut) + && (policy == SymlinkPolicy::NoFollow || !takesPolicy(op))) + { + // `uplink` names a directory, so Windows made it a directory link, which is a directory to + // the file system: no hard link names it, and no file replaces it. + if ((op.operation == "linkAt(from)" || op.operation == "renameAt(to)") && shape == Shape::FinalLinkUp + && variant.kind == FixtureKind::Native + && NativeDirectoryLinkNature == DirectoryLinkNature::Directory) + return FsErrorCode::IsDirectory; + return op.onFinalLink; + } + return FsErrorCode::NotPermitted; +} + +/// A fixture with `a/`, `f`, `up -> ../`, `uplink -> ..`, `outlink -> ../decoy` and `abs -> ` +/// beneath the root, and the decoys `decoy` (a file) and `dir` (a directory) beside it. +DescriptorFixture escapeFixture(Variant const& variant) +{ + auto fixture = DescriptorFixture::create(variant.kind, { .strategy = variant.strategy }); + if (fixture.requireSymlinks() == SymlinkSupport::Unavailable) + return fixture; + REQUIRE(fixture.run(fixture.root().createDirectoryAt("a")).has_value()); + fixture.createFile("f", "inside"); + REQUIRE(fixture.run(fixture.root().symlinkAt("../", "up")).has_value()); + REQUIRE(fixture.run(fixture.root().symlinkAt("..", "uplink")).has_value()); + REQUIRE(fixture.run(fixture.root().symlinkAt("../decoy", "outlink")).has_value()); + fixture.hostSymlink("abs", fixture.outsideAbsoluteTarget()); + fixture.writeOutsideFile("decoy", "outside"); + fixture.createOutsideDirectory("dir"); + return fixture; +} + +} // namespace + +TEST_CASE("no *At operation reaches outside the preopen", "[fs][escape]") +{ + auto const variant = GENERATE(from_range(variants())); + auto const shape = GENERATE(from_range(Shapes)); + auto const policy = GENERATE(SymlinkPolicy::NoFollow, SymlinkPolicy::Follow); + CAPTURE(nameOf(variant), nameOf(shape), policy == SymlinkPolicy::Follow ? "Follow" : "NoFollow"); + + for (auto const& op: Ops) + { + CAPTURE(op.operation); + auto fixture = escapeFixture(variant); + if (fixture.requireSymlinks() == SymlinkSupport::Unavailable) + SKIP("this file system cannot create symbolic links"); + auto const outcome = fixture.run( + op.start(Call { .fixture = &fixture, .policy = policy, .path = pathOf(shape, op.aimedAt) })); + CHECK(outcome == expectedOf(op, variant, policy, shape)); + CHECK(fixture.outsideUnchanged()); + CHECK(outcomeOf(fixture.run(fixture.outside().statAt(SymlinkPolicy::NoFollow, "fresh"))) + == FsErrorCode::NoEntry); + } +} + +TEST_CASE("a symlink cycle ends in Loop, not a hang", "[fs][escape]") +{ + auto const variant = GENERATE(from_range(variants())); + CAPTURE(nameOf(variant)); + auto fixture = DescriptorFixture::create(variant.kind, { .strategy = variant.strategy }); + if (fixture.requireSymlinks() == SymlinkSupport::Unavailable) + SKIP("this file system cannot create symbolic links"); + auto& root = fixture.root(); + REQUIRE(fixture.run(root.symlinkAt("pong", "ping")).has_value()); + REQUIRE(fixture.run(root.symlinkAt("ping/", "pong")).has_value()); + + CHECK(outcomeOf(fixture.run(root.statAt(SymlinkPolicy::Follow, "ping"))) == FsErrorCode::Loop); + CHECK(outcomeOf(fixture.run(root.statAt(SymlinkPolicy::NoFollow, "ping/x"))) == FsErrorCode::Loop); + CHECK(outcomeOf(fixture.run(root.createDirectoryAt("pong/new"))) == FsErrorCode::Loop); + CHECK(outcomeOf(fixture.run( + root.openAt(SymlinkPolicy::NoFollow, "ping/f", OpenFlags::Create, DescriptorFlags::Write))) + == FsErrorCode::Loop); + CHECK(fixture.run(root.statAt(SymlinkPolicy::NoFollow, "ping")).has_value()); +} + +TEST_CASE("a directory swapped for an outward symlink mid-walk never yields a descriptor outside the preopen", + "[fs][escape]") +{ + auto const strategy = GENERATE(BeneathStrategy::Best, BeneathStrategy::ComponentWalk); + CAPTURE(strategy == BeneathStrategy::Best ? "Best" : "ComponentWalk"); + auto fixture = DescriptorFixture::createNative({ .strategy = strategy }); + if (fixture.requireSymlinks() == SymlinkSupport::Unavailable) + SKIP("this file system cannot create symbolic links"); + fixture.writeFile("d/inside.txt", "inside"); + fixture.writeOutsideFile("inside.txt", "outside"); // the decoy at the escape target + auto openedInside = 0; + auto refused = 0; + { + auto const swapper = fixture.startSwapper("d", "../"); + for (auto const round: std::views::iota(0, 2000)) // bounded by count, not by wall time + { + INFO(round); + auto opened = fixture.run(fixture.root().openAt( + SymlinkPolicy::Follow, "d/inside.txt", OpenFlags::None, DescriptorFlags::Read)); + if (opened) + { + REQUIRE(fixture.isInsideRoot(**opened)); + ++openedInside; + } + else + ++refused; + // The decoy holds "outside", one byte more than "inside": a stat that escaped shows it. + if (auto const status = fixture.run(fixture.root().statAt(SymlinkPolicy::Follow, "d/inside.txt"))) + CHECK(status->size == 6); + std::ignore = + fixture.run(fixture.root().setTimesAt(SymlinkPolicy::Follow, "d/inside.txt", Stamp, Stamp)); + } + UNSCOPED_INFO("swaps: " << swapper->swaps()); + CHECK(swapper->swaps() > 100); + } + CHECK(openedInside > 0); + CHECK(refused > 0); + CHECK(fixture.outsideUnchanged()); +} diff --git a/src/core/fs/DescriptorTestSupport.hpp b/src/core/fs/DescriptorTestSupport.hpp new file mode 100644 index 00000000..82c9fd89 --- /dev/null +++ b/src/core/fs/DescriptorTestSupport.hpp @@ -0,0 +1,622 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// What the fs cases share: a fixture that owns a file system of either kind together with the two +/// executors, the wall clock and the random source it runs on, and drives a descriptor operation to +/// its end; its root is a directory beneath an outside one, where escape cases plant decoys, and a +/// swapper thread races a directory against a link for the escape cases. Test-only: in no +/// `FILE_SET`, so never installed. + +#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 core::fs::test +{ + +/// Which implementation of @c IDescriptorFileSystem a fixture builds. +enum class FixtureKind : std::uint8_t +{ + InMemory, ///< @c testing::InMemoryDescriptorFileSystem. + Native, ///< The operating system's, over a temporary directory. +}; + +/// Whether the file system under a fixture can create symbolic links. +enum class SymlinkSupport : std::uint8_t +{ + Unavailable, ///< It cannot; a case that needs one skips. + Available, ///< It can. +}; + +/// What a file system sets a time to for @c SetToNow. +enum class NowSource : std::uint8_t +{ + InjectedClock, ///< The wall clock it was built with (in memory; native on Windows). + SystemClock, ///< The kernel's own clock (`UTIME_NOW`, native on POSIX). +}; + +/// What a symbolic link that names a directory is to the native file system, beside being a link. +enum class DirectoryLinkNature : std::uint8_t +{ + File, ///< A file like any other: hard linked, and replaced by a rename (POSIX). + Directory, ///< A directory: never hard linked, and replaced by no file (Windows). +}; + +/// What a directory link is to the native file system of this system. +#ifdef _WIN32 +inline constexpr auto NativeDirectoryLinkNature = DirectoryLinkNature::Directory; +#else +inline constexpr auto NativeDirectoryLinkNature = DirectoryLinkNature::File; +#endif + +/// What a call came to: nothing where it ran, the code where it was refused. +using Outcome = std::optional; + +/// @param result A call's result. +/// @return Its @c Outcome. +template +[[nodiscard]] Outcome outcomeOf(FsResult const& result) +{ + if (result) + return std::nullopt; + return result.error().code; +} + +/// @param when An instant. +/// @return The same instant as a @c FileTime. +[[nodiscard]] inline FileTime fileTimeOf(std::chrono::system_clock::time_point when) +{ + auto const sinceEpoch = when.time_since_epoch(); + auto const seconds = std::chrono::floor(sinceEpoch); + return FileTime { + .seconds = seconds.count(), + .nanoseconds = static_cast( + std::chrono::duration_cast(sinceEpoch - seconds).count()) + }; +} + +/// @param text Characters. +/// @return The same characters as bytes. +[[nodiscard]] inline std::vector bytesOf(std::string_view text) +{ + auto bytes = std::vector(text.size()); + std::ranges::transform(text, bytes.begin(), [](char c) { return static_cast(c); }); + return bytes; +} + +/// @param bytes Bytes. +/// @return The same bytes as characters. +[[nodiscard]] inline std::string textOf(std::span bytes) +{ + auto text = std::string(bytes.size(), '\0'); + std::ranges::transform(bytes, text.begin(), [](std::byte b) { return static_cast(b); }); + return text; +} + +/// An @c IRandom that fills from a seed, so two instances with one seed agree and two with +/// different seeds do not. +class FixedRandom final: public IRandom +{ + public: + /// @param seed Where the sequence starts. + explicit FixedRandom(std::uint64_t seed) noexcept: _state { seed } {} + + /// Fills @p out from a SplitMix64 sequence. + /// @param out Where the bytes go. + void fill(std::span out) override + { + for (auto& byte: out) + { + _state += 0x9E37'79B9'7F4A'7C15U; + auto mixed = _state; + mixed = (mixed ^ (mixed >> 30U)) * 0xBF58'476D'1CE4'E5B9U; + mixed = (mixed ^ (mixed >> 27U)) * 0x94D0'49BB'1331'11EBU; + byte = static_cast(mixed ^ (mixed >> 31U)); + } + } + + private: + std::uint64_t _state; +}; + +/// A thread that keeps swapping a directory for a symbolic link under one name, through renames in +/// the host's file system, until it is destroyed: what a walk racing an attacker meets. Test-only, +/// so it may own a thread. +class Swapper +{ + public: + /// Starts swapping: @p name alternates between the directory now at @p name and a link to + /// @p target, each parked under a name of its own while the other is in place. + /// @param directory The host directory @p name is in. + /// @param name The directory to swap. + /// @param target The link's target. + Swapper(std::filesystem::path const& directory, std::string const& name, std::string const& target): + _state { std::make_unique() } + { + auto const place = directory / name; + auto const parkedDirectory = directory / (name + ".directory"); + auto const parkedLink = directory / (name + ".link"); + std::filesystem::create_directory_symlink(target, parkedLink); + _thread = std::thread { [state = _state.get(), place, parkedDirectory, parkedLink] { + auto error = std::error_code {}; + while (!state->stop.load()) + { + std::filesystem::rename(place, parkedDirectory, error); + std::filesystem::rename(parkedLink, place, error); + state->swaps.fetch_add(1); + std::filesystem::rename(place, parkedLink, error); + std::filesystem::rename(parkedDirectory, place, error); + state->swaps.fetch_add(1); + } + } }; + } + + Swapper(Swapper const&) = delete; + Swapper(Swapper&&) = delete; + Swapper& operator=(Swapper const&) = delete; + Swapper& operator=(Swapper&&) = delete; + + /// Stops the thread, leaving the directory in place. + ~Swapper() + { + _state->stop.store(true); + _thread.join(); + } + + /// @return How many times the name changed what it names. + [[nodiscard]] std::size_t swaps() const noexcept { return _state->swaps.load(); } + + private: + struct State + { + std::atomic stop { false }; + std::atomic swaps { 0 }; + }; + + std::unique_ptr _state; + std::thread _thread; +}; + +/// A file system of one kind, the executors, the clock and the random source it runs on, and its +/// root descriptor, preopened with `Read | MutateDirectory`. The root is the directory `root` +/// beneath an outside one, which an `outside` descriptor holds, so an escape case can put a decoy +/// where an escape would land and see that it was never touched. +/// +/// Both executors are `ManualExecutor`s: `home` stands for the loop a caller runs on and `blocking` +/// for the pool that takes the blocking calls, so a case sees every hop as a step rather than a +/// timing. The executors are declared first and the descriptors last, so the descriptors are +/// destroyed first and the executors last; a native fixture's temporary directory is removed after +/// its root descriptor is closed. +class DescriptorFixture +{ + public: + /// The `maxReadChunk` the file system is built with: small, so a case can exceed it cheaply. + static constexpr std::size_t MaxReadChunk = 64; + + /// How many rounds of draining @c run makes before it calls a task stuck. + static constexpr std::size_t MaxRounds = 10'000; + + /// The seed of the random source a native file system draws its metadata secret from, unless a + /// case asks for another. + static constexpr std::uint64_t DefaultSecretSeed = 1; + + /// @param kind Which file system to build: in memory under the POSIX rules, or native under the + /// operating system's. + /// @return A fixture with its root descriptor open. + /// @throws std::runtime_error Where the root cannot be opened. + [[nodiscard]] static DescriptorFixture create(FixtureKind kind) + { + if (kind == FixtureKind::Native) + return createNative(); + return create(kind, posixPathPolicy()); + } + + /// @param kind Which file system to build. + /// @param policy The name rules it applies. + /// @return A fixture with its root descriptor open. + /// @throws std::runtime_error Where the root cannot be opened. + [[nodiscard]] static DescriptorFixture create(FixtureKind kind, PathPolicy const& policy) + { + if (kind == FixtureKind::Native) + return createNative({ .policy = &policy }); + auto fixture = DescriptorFixture { FixtureKind::InMemory, DefaultSecretSeed }; + fixture._outsideDirectory = std::filesystem::path { "/" }; + fixture._hostDirectory = std::filesystem::path { "/root" }; + auto fileSystem = std::make_unique( + *fixture._home, *fixture._blocking, *fixture._clock, policy, MaxReadChunk); + fileSystem->addDirectory("root"); + fixture._inMemory = fileSystem.get(); + fixture._fileSystem = std::move(fileSystem); + fixture.openRootDescriptor(); + return fixture; + } + + /// @param kind Which file system to build. + /// @param options What a native one is built with; an in-memory one takes none of them. + /// @return A fixture with its root descriptor open. + /// @throws std::runtime_error Where the root cannot be opened. + [[nodiscard]] static DescriptorFixture create(FixtureKind kind, NativeFileSystemOptions options) + { + if (kind == FixtureKind::Native) + return createNative(options); + return create(kind, posixPathPolicy()); + } + + /// A native file system over a temporary directory of its own. + /// @param options What it is built with; its `maxReadChunk` is always @c MaxReadChunk. + /// @param secretSeed The seed of the random source its metadata secret is drawn from. + /// @return A fixture with its root descriptor open. + /// @throws std::runtime_error Where the root cannot be opened. + [[nodiscard]] static DescriptorFixture createNative(NativeFileSystemOptions options = {}, + std::uint64_t secretSeed = DefaultSecretSeed) + { + auto fixture = DescriptorFixture { FixtureKind::Native, secretSeed }; + fixture._directory = std::make_shared("core-cpp-fs"); + fixture.buildNative(options); + return fixture; + } + + /// A second native file system over this fixture's directory, with executors, a clock and a + /// random source of its own. + /// @param secretSeed The seed its metadata secret is drawn from. + /// @return The fixture; the directory lives as long as the last fixture over it. + /// @throws std::logic_error For an in-memory fixture, whose nodes no second model can see. + [[nodiscard]] DescriptorFixture sibling(std::uint64_t secretSeed) const + { + if (_kind != FixtureKind::Native) + throw std::logic_error { "DescriptorFixture::sibling: only a native fixture has one" }; + auto fixture = DescriptorFixture { FixtureKind::Native, secretSeed }; + fixture._directory = _directory; + fixture.buildNative(_options); + return fixture; + } + + /// @return Which file system this is. + [[nodiscard]] FixtureKind kind() const noexcept { return _kind; } + + /// @return The root descriptor, `Read | MutateDirectory`. + [[nodiscard]] IDescriptor& root() const noexcept { return *_root; } + + /// @return The file system. + [[nodiscard]] IDescriptorFileSystem& fileSystem() const noexcept { return *_fileSystem; } + + /// @return The directory the root is preopened on, in the host's terms. + [[nodiscard]] std::filesystem::path const& hostDirectory() const noexcept { return _hostDirectory; } + + /// @return The directory that holds the root, in the host's terms. + [[nodiscard]] std::filesystem::path const& outsideDirectory() const noexcept { return _outsideDirectory; } + + /// @return A descriptor of the directory that holds the root, `Read | MutateDirectory`. + [[nodiscard]] IDescriptor& outside() const noexcept { return *_outside; } + + /// @return The wall clock the file system reads. + [[nodiscard]] platform::ManualWallClock& clock() const noexcept { return *_clock; } + + /// @return The executor every operation resumes on. + [[nodiscard]] async::testing::ManualExecutor& home() const noexcept { return *_home; } + + /// @return The executor every blocking call runs on. + [[nodiscard]] async::testing::ManualExecutor& blocking() const noexcept { return *_blocking; } + + /// @return What this file system sets a time to for @c SetToNow. + [[nodiscard]] NowSource nowSource() const noexcept + { + if (_kind == FixtureKind::InMemory) + return NowSource::InjectedClock; +#ifdef _WIN32 + return NowSource::InjectedClock; +#else + return NowSource::SystemClock; +#endif + } + + /// Opens the root directory again, with @p flags. + /// @param flags The rights the new descriptor carries. + /// @return The descriptor, or what refused it. + [[nodiscard]] FsResult> openRoot(DescriptorFlags flags) const + { + return run(_fileSystem->openPreopen(_hostDirectory, flags)); + } + + /// @return Whether this file system can create symbolic links: always in memory; natively where + /// a probe link could be created when the fixture was built. + [[nodiscard]] SymlinkSupport requireSymlinks() const noexcept { return _symlinks; } + + /// Creates the file @p path beneath the root holding @p text. + /// @param path Where, relative to the root. + /// @param text What it holds. + /// @throws std::runtime_error Where it could not. + void createFile(std::string path, std::string_view text) const + { + auto file = run(root().openAt(SymlinkPolicy::NoFollow, + std::move(path), + OpenFlags::Create | OpenFlags::Exclusive, + DescriptorFlags::Write)); + if (!file) + throw std::runtime_error { "DescriptorFixture::createFile: " + file.error().toString() }; + auto written = run((*file)->write(bytesOf(text), 0)); + if (!written || *written != text.size()) + throw std::runtime_error { "DescriptorFixture::createFile: the write did not complete" }; + } + + /// Creates the file @p path beneath the root holding @p text, and every directory above it. + /// @param path Where, relative to the root, `/`-separated. + /// @param text What it holds. + /// @throws std::runtime_error Where it could not. + void writeFile(std::string const& path, std::string_view text) const + { + auto names = std::vector {}; + for (auto const piece: path | std::views::split('/')) + names.emplace_back(std::string_view { piece }); + auto parent = std::string {}; + for (auto const& name: names | std::views::take(names.size() - 1)) + { + parent += parent.empty() ? name : "/" + name; + if (auto made = run(root().createDirectoryAt(parent)); + !made && made.error().code != FsErrorCode::Exist) + throw std::runtime_error { "DescriptorFixture::writeFile: " + made.error().toString() }; + } + createFile(path, text); + } + + /// Creates the file @p name beside the root, holding @p text: a decoy an escape would reach. + /// @param name Its name. + /// @param text What it holds. + /// @throws std::runtime_error Where it could not. + void writeOutsideFile(std::string const& name, std::string_view text) + { + auto file = run(outside().openAt( + SymlinkPolicy::NoFollow, name, OpenFlags::Create | OpenFlags::Exclusive, DescriptorFlags::Write)); + if (!file || !run((*file)->write(bytesOf(text), 0))) + throw std::runtime_error { "DescriptorFixture::writeOutsideFile: " + name }; + file->reset(); + _decoys.push_back(name); + recordOutside(); + } + + /// Creates the directory @p name beside the root: a decoy an escape would reach. + /// @param name Its name. + /// @throws std::runtime_error Where it could not. + void createOutsideDirectory(std::string const& name) + { + if (auto made = run(outside().createDirectoryAt(name)); !made) + throw std::runtime_error { "DescriptorFixture::createOutsideDirectory: " + + made.error().toString() }; + _decoys.push_back(name); + recordOutside(); + } + + /// @return Whether everything beside the root is as it was when the last decoy was made: the + /// outside directory's own times and link count, and each decoy's type, size, link + /// count and times. The times of an access are not compared. + [[nodiscard]] bool outsideUnchanged() const { return snapshotOutside() == _outsideSnapshot; } + + /// @return The target an absolute link to the outside directory has, in this file system's + /// terms: what no `symlinkAt` may create and the host can. + [[nodiscard]] std::string outsideAbsoluteTarget() const { return _outsideDirectory.generic_string(); } + + /// Creates a symbolic link beneath the root through the host, with a target no `symlinkAt` + /// would accept (an absolute one). + /// @param path Where, relative to the root. + /// @param target What it points to, verbatim. + void hostSymlink(std::string const& path, std::string const& target) const + { + if (_inMemory != nullptr) + _inMemory->addSymlink("root/" + path, target); + else + std::filesystem::create_directory_symlink(target, _hostDirectory / path); + } + + /// @param descriptor A descriptor opened through this fixture. + /// @return Whether it is open on something other than each decoy beside the root, as their + /// metadata hashes tell. + [[nodiscard]] bool isInsideRoot(IDescriptor& descriptor) const + { + auto const hash = run(descriptor.metadataHash()); + if (!hash) + throw std::runtime_error { "DescriptorFixture::isInsideRoot: " + hash.error().toString() }; + return std::ranges::none_of(_decoys, [&](std::string const& name) { + auto const decoy = run(outside().metadataHashAt(SymlinkPolicy::NoFollow, name)); + return decoy && *decoy == *hash; + }); + } + + /// Starts a thread that swaps the directory @p name beneath the root for a link to @p target, + /// and back, until the returned object is destroyed. + /// @param name The directory, which must exist. + /// @param target The link's target, relative to the root. + /// @return The swapper. + /// @throws std::logic_error For an in-memory fixture, whose nodes no host rename reaches. + [[nodiscard]] std::unique_ptr startSwapper(std::string const& name, + std::string const& target) const + { + if (_kind != FixtureKind::Native) + throw std::logic_error { "DescriptorFixture::startSwapper: only a native fixture has one" }; + return std::make_unique(_hostDirectory, name, target); + } + + /// Drives @p task to its end: resumes it, then drains `home` and `blocking` in turn. + /// @param task A task over this fixture's file system. + /// @return Its result. + /// @throws std::runtime_error Where it is still suspended after @c MaxRounds rounds, or with + /// nothing queued on either executor; its frame is then leaked rather than freed while + /// something may still point into it. + template + [[nodiscard]] T run(async::Task task) const + { + task.handle().resume(); + for ([[maybe_unused]] auto const round: std::views::iota(std::size_t { 0 }, MaxRounds)) + { + if (task.done() || _home->drain() + _blocking->drain() == 0) + break; + } + if (task.done()) + return task.result(); + auto const homePending = _home->pending(); + auto const blockingPending = _blocking->pending(); + std::ignore = task.release(); + throw std::runtime_error { "DescriptorFixture::run: the task is still suspended (home pending " + + std::to_string(homePending) + ", blocking pending " + + std::to_string(blockingPending) + + "): waited for it to complete on the two executors" }; + } + + /// Reads @p stream to its end, each answer as it came: an entry, or why that entry is not one. + /// @param stream A stream over this fixture's file system. + /// @param maxAnswers How many answers the directory can hold at most; one more is a stream that + /// does not end. + /// @return The answers, in order. + /// @throws std::runtime_error Where the stream has not ended after @p maxAnswers answers. + [[nodiscard]] std::vector> readEntries(IDirectoryStream& stream, + std::size_t maxAnswers) const + { + auto answers = std::vector> {}; + while (answers.size() <= maxAnswers) + { + auto next = run(stream.next()); + if (next && !*next) + return answers; + if (next) + answers.emplace_back(std::move(**next)); + else + answers.emplace_back(std::unexpected { std::move(next.error()) }); + } + throw std::runtime_error { "DescriptorFixture::readEntries: the stream had not ended after " + + std::to_string(maxAnswers) + " answers" }; + } + + private: + DescriptorFixture(FixtureKind kind, std::uint64_t secretSeed): + _random { std::make_unique(secretSeed) }, _kind { kind } + { + } + + void buildNative(NativeFileSystemOptions options) + { + options.maxReadChunk = MaxReadChunk; + _options = options; + _outsideDirectory = _directory->path(); + _hostDirectory = _outsideDirectory / "root"; + std::filesystem::create_directories(_hostDirectory); + auto fileSystem = makeNativeDescriptorFileSystem(*_home, *_blocking, *_clock, *_random, options); + if (!fileSystem) + throw std::runtime_error { "DescriptorFixture: no native file system: " + + fileSystem.error().toString() }; + _fileSystem = std::move(*fileSystem); + openRootDescriptor(); + _symlinks = probeSymlinks(); + } + + void openRootDescriptor() + { + auto root = openRoot(DescriptorFlags::Read | DescriptorFlags::MutateDirectory); + if (!root) + throw std::runtime_error { "DescriptorFixture: the root did not open: " + + root.error().toString() }; + _root = std::move(*root); + auto outside = run(_fileSystem->openPreopen( + _outsideDirectory, DescriptorFlags::Read | DescriptorFlags::MutateDirectory)); + if (!outside) + throw std::runtime_error { "DescriptorFixture: the outside directory did not open: " + + outside.error().toString() }; + _outside = std::move(*outside); + recordOutside(); + } + + /// What @c outsideUnchanged compares: a stat without its access time. + struct Seen + { + DescriptorType type = DescriptorType::Unknown; + std::uint64_t linkCount = 0; + std::uint64_t size = 0; + std::optional modified; + std::optional statusChanged; + + bool operator==(Seen const&) const = default; + }; + + [[nodiscard]] static std::optional seenOf(FsResult const& status) + { + if (!status) + return std::nullopt; + return Seen { .type = status->type, + .linkCount = status->linkCount, + .size = status->size, + .modified = status->modified, + .statusChanged = status->statusChanged }; + } + + [[nodiscard]] std::vector> snapshotOutside() const + { + auto seen = std::vector> { seenOf(run(outside().stat())) }; + for (auto const& name: _decoys) + seen.push_back(seenOf(run(outside().statAt(SymlinkPolicy::NoFollow, name)))); + return seen; + } + + void recordOutside() { _outsideSnapshot = snapshotOutside(); } + + /// Creates and removes a link, so a case that needs one skips where the system refuses it (a + /// Windows account without the symbolic-link privilege). + [[nodiscard]] SymlinkSupport probeSymlinks() const + { + constexpr auto ProbeName = std::string_view { ".core-cpp-symlink-probe" }; + if (!run(root().symlinkAt("probe-target", std::string { ProbeName }))) + return SymlinkSupport::Unavailable; + if (auto removed = run(root().unlinkFileAt(std::string { ProbeName })); !removed) + throw std::runtime_error { "DescriptorFixture: the symlink probe was not removed: " + + removed.error().toString() }; + return SymlinkSupport::Available; + } + + std::unique_ptr _home = + std::make_unique(); + std::unique_ptr _blocking = + std::make_unique(); + std::unique_ptr _clock = std::make_unique( + std::chrono::system_clock::time_point { std::chrono::seconds { 1'700'000'000 } }); + std::unique_ptr _random; + std::shared_ptr _directory; + std::filesystem::path _outsideDirectory; + std::filesystem::path _hostDirectory; + NativeFileSystemOptions _options; + std::unique_ptr _fileSystem; + testing::InMemoryDescriptorFileSystem* _inMemory = nullptr; ///< @c _fileSystem, where in memory. + std::unique_ptr _root; + std::unique_ptr _outside; + std::vector _decoys; + std::vector> _outsideSnapshot; + FixtureKind _kind; + SymlinkSupport _symlinks = SymlinkSupport::Available; +}; + +} // namespace core::fs::test diff --git a/src/core/fs/DirectoryStream_test.cpp b/src/core/fs/DirectoryStream_test.cpp new file mode 100644 index 00000000..974cae4d --- /dev/null +++ b/src/core/fs/DirectoryStream_test.cpp @@ -0,0 +1,418 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// What a directory stream and object identity owe their caller, whichever file system is under them: +// every entry once, typed, never "." or ".."; a stream of its own per readDirectory, holding one +// batch rather than the listing; isSameObject by identity; metadataHashAt as metadataHash. Each case +// GENERATEs the fixture kinds it holds for. +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using core::fs::DescriptorFlags; +using core::fs::DescriptorType; +using core::fs::DirectoryEntry; +using core::fs::FsErrorCode; +using core::fs::FsResult; +using core::fs::IDescriptor; +using core::fs::IDirectoryStream; +using core::fs::OpenFlags; +using core::fs::SymlinkPolicy; +using core::fs::test::DescriptorFixture; +using core::fs::test::FixtureKind; +using core::fs::test::outcomeOf; +using core::fs::test::SymlinkSupport; + +namespace +{ + +constexpr auto FileCount = std::size_t { 300 }; + +/// The most answers any case's directory holds, with room to spare: one more is a stream that does +/// not end. +constexpr auto MaxAnswers = std::size_t { 4'000 }; + +/// How many rounds of draining a hand-started call gets before it is called stuck. +constexpr auto MaxRounds = DescriptorFixture::MaxRounds; + +std::string fileName(std::size_t index) +{ + return std::format("file-{:03}", index); +} + +/// How many files the cases that need several batches of every kind make. +constexpr auto LongCount = std::size_t { 1'000 }; + +/// The length of their names: 1000 of them spell more than two 64 KiB batches (Linux's getdents64, +/// Windows' FileIdBothDirectoryInfo) in name bytes alone, and in-memory and readdir batches count 64 +/// entries, so every kind needs at least three batches, and a hop for each. +constexpr auto LongNameLength = std::size_t { 155 }; + +/// @return The @p index-th of @c LongCount names, each @c LongNameLength bytes: long enough for +/// several batches, short enough for any file system and Windows' MAX_PATH. +std::string longName(std::size_t index) +{ + return std::format("{}-{:04}", std::string(LongNameLength - 5, 'n'), index); +} + +/// Fills the root with @c FileCount files and the directory `sub`. +void populate(DescriptorFixture const& fixture) +{ + for (auto const index: std::views::iota(std::size_t { 0 }, FileCount)) + fixture.createFile(fileName(index), "x"); + REQUIRE(fixture.run(fixture.root().createDirectoryAt("sub")).has_value()); +} + +std::unique_ptr openStream(DescriptorFixture const& fixture, IDescriptor& directory) +{ + auto stream = fixture.run(directory.readDirectory()); + REQUIRE(stream.has_value()); + return std::move(*stream); +} + +/// @return The names of @p answers, each with how often it came; fails the case on an answer that +/// is no entry. +std::map countNames(std::vector> const& answers) +{ + auto counts = std::map {}; + for (auto const& answer: answers) + { + REQUIRE(answer.has_value()); + ++counts[answer->name]; + } + return counts; +} + +std::unique_ptr openAt(DescriptorFixture const& fixture, std::string path, DescriptorFlags flags) +{ + auto opened = + fixture.run(fixture.root().openAt(SymlinkPolicy::NoFollow, std::move(path), OpenFlags::None, flags)); + REQUIRE(opened.has_value()); + return std::move(*opened); +} + +} // namespace + +TEST_CASE("directory stream: every entry once, typed, without . and ..", "[fs][contract][directory]") +{ + auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); + populate(fixture); + + auto stream = openStream(fixture, fixture.root()); + auto const answers = fixture.readEntries(*stream, MaxAnswers); + REQUIRE(answers.size() == FileCount + 1); + auto const counts = countNames(answers); + CHECK(counts.size() == FileCount + 1); + CHECK_FALSE(counts.contains(".")); + CHECK_FALSE(counts.contains("..")); + for (auto const& answer: answers) + { + CAPTURE(answer->name); + CHECK(counts.at(answer->name) == 1); + auto const expected = answer->name == "sub" ? DescriptorType::Directory : DescriptorType::RegularFile; + CHECK(answer->type == expected); + } + CHECK(counts.contains(fileName(0))); + CHECK(counts.contains(fileName(FileCount - 1))); + + // The end is the end: asked again, the stream has nothing more. + auto const after = fixture.run(stream->next()); + REQUIRE(after.has_value()); + CHECK(*after == std::nullopt); +} + +TEST_CASE("directory stream: a symbolic link is typed as one, never followed", "[fs][contract][directory]") +{ + auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); + if (fixture.requireSymlinks() == SymlinkSupport::Unavailable) + SKIP("this file system cannot create symbolic links"); + fixture.createFile("f", "x"); + REQUIRE(fixture.run(fixture.root().createDirectoryAt("d")).has_value()); + REQUIRE(fixture.run(fixture.root().symlinkAt("f", "to-file")).has_value()); + REQUIRE(fixture.run(fixture.root().symlinkAt("d", "to-directory")).has_value()); + REQUIRE(fixture.run(fixture.root().symlinkAt("missing", "dangling")).has_value()); + + auto stream = openStream(fixture, fixture.root()); + auto types = std::map {}; + for (auto const& answer: fixture.readEntries(*stream, MaxAnswers)) + { + REQUIRE(answer.has_value()); + types.emplace(answer->name, answer->type); + } + CHECK(types + == std::map { + { "d", DescriptorType::Directory }, + { "dangling", DescriptorType::SymbolicLink }, + { "f", DescriptorType::RegularFile }, + { "to-directory", DescriptorType::SymbolicLink }, + { "to-file", DescriptorType::SymbolicLink }, + }); +} + +TEST_CASE("directory stream: each stream reads the directory from its start", "[fs][contract][directory]") +{ + auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); + populate(fixture); + + SECTION("two consecutive streams each yield every entry") + { + for ([[maybe_unused]] auto const round: { 1, 2 }) + { + auto stream = openStream(fixture, fixture.root()); + auto const answers = fixture.readEntries(*stream, MaxAnswers); + CHECK(answers.size() == FileCount + 1); + CHECK(countNames(answers).size() == FileCount + 1); + } + } + SECTION("two interleaved streams together yield each name exactly twice") + { + auto first = openStream(fixture, fixture.root()); + auto second = openStream(fixture, fixture.root()); + auto counts = std::map {}; + auto ended = std::set {}; + auto answers = std::size_t { 0 }; + while (ended.size() < 2 && answers <= MaxAnswers) + { + for (auto* const stream: { first.get(), second.get() }) + { + if (ended.contains(stream)) + continue; + auto next = fixture.run(stream->next()); + REQUIRE(next.has_value()); + if (!*next) + { + ended.insert(stream); + continue; + } + ++answers; + ++counts[(*next)->name]; + } + } + REQUIRE(ended.size() == 2); + CHECK(answers == 2 * (FileCount + 1)); + CHECK(counts.size() == FileCount + 1); + CHECK(std::ranges::all_of(counts, [](auto const& count) { return count.second == 2; })); + } +} + +TEST_CASE("directory stream: the stream holds a batch, never the whole listing", "[fs][contract][directory]") +{ + auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); + constexpr auto Count = LongCount; + for (auto const index: std::views::iota(std::size_t { 0 }, Count)) + fixture.createFile(longName(index), ""); + + auto stream = openStream(fixture, fixture.root()); + // The setup's own closes are queued on blocking; they are not the stream's. + fixture.blocking().drain(); + fixture.home().drain(); + auto hops = std::size_t { 0 }; + auto entries = std::size_t { 0 }; + while (entries <= Count) + { + // Started by hand rather than through run(), so a call answered from the batch in hand is + // seen to complete without a hop. + auto task = stream->next(); + task.handle().resume(); + fixture.home().drain(); + if (!task.done()) + { + ++hops; + for ([[maybe_unused]] auto const round: std::views::iota(std::size_t { 0 }, MaxRounds)) + if (task.done() || fixture.blocking().drain() + fixture.home().drain() == 0) + break; + } + if (!task.done()) + { + // Leaked rather than freed while an executor may still point into it, as run() does. + std::ignore = task.release(); + FAIL("next() was still suspended after " << MaxRounds << " rounds of draining both executors"); + } + auto const next = task.result(); + REQUIRE(next.has_value()); + if (!*next) + break; + ++entries; + } + CHECK(entries == Count); + static_assert(LongCount * LongNameLength > std::size_t { 2 } * 64 * 1024); + static_assert(LongCount > std::size_t { 2 } * 64); + CHECK(hops >= 3); + CHECK(hops <= Count / 2); +} + +TEST_CASE("directory stream: a directory changed while it is read is read to an end", + "[fs][contract][directory]") +{ + auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); + // Enough for several batches of every kind, so the changes land both in the batch in hand and + // in batches the system has not read yet. + for (auto const index: std::views::iota(std::size_t { 0 }, LongCount)) + fixture.createFile(longName(index), "x"); + REQUIRE(fixture.run(fixture.root().createDirectoryAt("sub")).has_value()); + auto stream = openStream(fixture, fixture.root()); + + // Every tenth file is removed, unless the stream has handed it out already, and as many new ones + // are made, one after each entry read. + auto removed = std::set {}; + for (auto const index: std::views::iota(std::size_t { 0 }, LongCount)) + if (index % 10 == 9) + removed.insert(longName(index)); + auto counts = std::map {}; + auto added = std::size_t { 0 }; + auto answers = std::size_t { 0 }; + while (answers <= MaxAnswers) + { + auto next = fixture.run(stream->next()); + REQUIRE(next.has_value()); + if (!*next) + break; + ++answers; + ++counts[(*next)->name]; + if (added < removed.size()) + { + auto const victim = std::next(removed.begin(), static_cast(added)); + if (!counts.contains(*victim)) + REQUIRE(fixture.run(fixture.root().unlinkFileAt(*victim)).has_value()); + fixture.createFile(std::format("new-{:04}", added), "y"); + ++added; + } + } + REQUIRE(answers <= MaxAnswers); + CHECK(added == removed.size()); + CHECK(std::ranges::all_of(counts, [](auto const& count) { return count.second == 1; })); + // What was there throughout and never removed came exactly once. + CHECK(counts.contains("sub")); + auto missing = std::size_t { 0 }; + for (auto const index: std::views::iota(std::size_t { 0 }, LongCount)) + if (!removed.contains(longName(index)) && !counts.contains(longName(index))) + ++missing; + CHECK(missing == 0); +} + +TEST_CASE("directory stream: a stream outlives the descriptor it was opened from", + "[fs][contract][directory]") +{ + auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); + fixture.writeFile("sub/a", "x"); + fixture.writeFile("sub/b", "x"); + auto sub = openAt(fixture, "sub", DescriptorFlags::Read); + auto stream = openStream(fixture, *sub); + sub.reset(); + auto const counts = countNames(fixture.readEntries(*stream, MaxAnswers)); + CHECK(counts == std::map { { "a", 1 }, { "b", 1 } }); +} + +TEST_CASE("directory stream: a file has no entries to read", "[fs][contract][directory]") +{ + auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); + fixture.createFile("f", "x"); + auto file = openAt(fixture, "f", DescriptorFlags::Read); + CHECK(outcomeOf(fixture.run(file->readDirectory())) == FsErrorCode::NotDirectory); +} + +TEST_CASE("isSameObject: two descriptors of one object are the same object", "[fs][contract][identity]") +{ + auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); + fixture.createFile("f", "x"); + fixture.createFile("g", "x"); + auto const first = openAt(fixture, "f", DescriptorFlags::Read); + auto const second = openAt(fixture, "f", DescriptorFlags::None); + auto const other = openAt(fixture, "g", DescriptorFlags::Read); + + CHECK(fixture.run(first->isSameObject(second.get())) == true); + CHECK(fixture.run(second->isSameObject(first.get())) == true); + CHECK(fixture.run(first->isSameObject(first.get())) == true); + CHECK(fixture.run(first->isSameObject(other.get())) == false); + CHECK(fixture.run(first->isSameObject(&fixture.root())) == false); + + auto root = fixture.openRoot(DescriptorFlags::Read); + REQUIRE(root.has_value()); + CHECK(fixture.run((*root)->isSameObject(&fixture.root())) == true); + CHECK(fixture.run(fixture.root().isSameObject(&fixture.outside())) == false); + + // A hard link names the same object. + REQUIRE(fixture.run(fixture.root().linkAt(SymlinkPolicy::NoFollow, "f", &fixture.root(), "hard")) + .has_value()); + auto const hard = openAt(fixture, "hard", DescriptorFlags::Read); + CHECK(fixture.run(hard->isSameObject(first.get())) == true); + + CHECK(outcomeOf(fixture.run(first->isSameObject(nullptr))) == FsErrorCode::BadDescriptor); +} + +TEST_CASE("isSameObject: a descriptor of another file system is never the same object", + "[fs][contract][identity]") +{ + auto const kind = GENERATE(FixtureKind::InMemory, FixtureKind::Native); + auto fixture = DescriptorFixture::create(kind); + fixture.createFile("f", "x"); + auto const mine = openAt(fixture, "f", DescriptorFlags::Read); + + // Another instance of the same kind, and one of the other kind. + auto same = kind == FixtureKind::Native ? fixture.sibling(DescriptorFixture::DefaultSecretSeed) + : DescriptorFixture::create(FixtureKind::InMemory); + if (kind == FixtureKind::InMemory) + same.createFile("f", "x"); + auto const theirs = openAt(same, "f", DescriptorFlags::Read); + CHECK(fixture.run(mine->isSameObject(theirs.get())) == false); + + auto foreign = + DescriptorFixture::create(kind == FixtureKind::Native ? FixtureKind::InMemory : FixtureKind::Native); + CHECK(fixture.run(mine->isSameObject(&foreign.root())) == false); +} + +TEST_CASE("metadataHashAt: a link is hashed itself, or what it names where followed", + "[fs][contract][identity]") +{ + auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); + if (fixture.requireSymlinks() == SymlinkSupport::Unavailable) + SKIP("this file system cannot create symbolic links"); + fixture.createFile("f", "x"); + REQUIRE(fixture.run(fixture.root().symlinkAt("f", "link")).has_value()); + auto const target = fixture.run(fixture.root().metadataHashAt(SymlinkPolicy::NoFollow, "f")); + auto const followed = fixture.run(fixture.root().metadataHashAt(SymlinkPolicy::Follow, "link")); + auto const itself = fixture.run(fixture.root().metadataHashAt(SymlinkPolicy::NoFollow, "link")); + REQUIRE(target.has_value()); + REQUIRE(followed.has_value()); + REQUIRE(itself.has_value()); + CHECK(*followed == *target); + CHECK(*itself != *target); +} + +TEST_CASE("metadataHashAt: equals the hash of a descriptor of the same object", "[fs][contract][identity]") +{ + auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); + fixture.createFile("f", "x"); + REQUIRE(fixture.run(fixture.root().createDirectoryAt("d")).has_value()); + for (auto const* name: { "f", "d" }) + { + CAPTURE(name); + auto const opened = openAt(fixture, name, DescriptorFlags::Read); + auto const byDescriptor = fixture.run(opened->metadataHash()); + auto const byPath = fixture.run(fixture.root().metadataHashAt(SymlinkPolicy::NoFollow, name)); + REQUIRE(byDescriptor.has_value()); + REQUIRE(byPath.has_value()); + CHECK(*byDescriptor == *byPath); + } + auto const file = fixture.run(fixture.root().metadataHashAt(SymlinkPolicy::NoFollow, "f")); + auto const directory = fixture.run(fixture.root().metadataHashAt(SymlinkPolicy::NoFollow, "d")); + REQUIRE(file.has_value()); + REQUIRE(directory.has_value()); + CHECK(*file != *directory); +} diff --git a/src/core/fs/FsError.cpp b/src/core/fs/FsError.cpp new file mode 100644 index 00000000..c578d903 --- /dev/null +++ b/src/core/fs/FsError.cpp @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: Apache-2.0 +#include + +#include +#include +#include +#include +#include + +namespace core::fs +{ + +namespace +{ + + FsError classify(std::span table, std::int64_t systemCode, std::string context) + { + auto const row = std::ranges::find(table, systemCode, &SystemErrorRow::systemCode); + return FsError { .code = row == table.end() ? FsErrorCode::Io : row->code, + .systemCode = systemCode, + .context = std::move(context) }; + } + +} // namespace + +std::string FsError::toString() const +{ + auto result = std::string { fs::toString(code) }; + if (!context.empty()) + result += " (" + context + ")"; + if (systemCode != 0) + result += " [system code " + std::to_string(systemCode) + "]"; + return result; +} + +FsError fsErrorFromSystemCode(std::int64_t systemCode, std::string context) +{ + return classify(systemErrorTable(), systemCode, std::move(context)); +} + +FsError fsErrorFromNtStatus(std::int64_t status, std::string context) +{ + return classify(ntStatusTable(), status, std::move(context)); +} + +} // namespace core::fs diff --git a/src/core/fs/FsError.hpp b/src/core/fs/FsError.hpp new file mode 100644 index 00000000..afb99039 --- /dev/null +++ b/src/core/fs/FsError.hpp @@ -0,0 +1,168 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// The error vocabulary of the file system: an @c FsErrorCode category, a structured @c FsError that +/// adds the raw system code and a context string, and the per-OS tables that classify a system code. + +#include + +#include +#include +#include +#include +#include + +namespace core::fs +{ + +/// Classifies a file-system failure. +/// +/// One code for each case of the WASI 0.3 `wasi:filesystem` `error-code`, in its order, plus +/// @c WouldBlock, which that interface has no case of its own for. The order is the interface's, +/// so the zero enumerator is @c Access rather than an absent case: an @c FsError always carries a +/// failure, and its member defaults to @c Io. +enum class FsErrorCode : std::uint8_t +{ + Access, ///< Permission denied by the system (`EACCES`). + WouldBlock, ///< The operation would block (`EAGAIN`). + Already, ///< The connection or operation is already in progress (`EALREADY`). + BadDescriptor, ///< The descriptor is closed or not one of this file system's (`EBADF`). + Busy, ///< The resource is in use (`EBUSY`, a sharing violation). + Deadlock, ///< The operation would deadlock (`EDEADLK`). + Quota, ///< A storage quota is exceeded (`EDQUOT`). + Exist, ///< The file exists (`EEXIST`). + FileTooLarge, ///< The file is too large (`EFBIG`). + IllegalByteSequence, ///< A name is not valid UTF-8, or cannot be represented (`EILSEQ`). + InProgress, ///< The operation is in progress (`EINPROGRESS`). + Interrupted, ///< A signal interrupted the call (`EINTR`). + Invalid, ///< An argument is invalid (`EINVAL`), a name included. + Io, ///< An I/O error, and every system code nothing classifies further (`EIO`). + IsDirectory, ///< The object is a directory (`EISDIR`). + Loop, ///< Too many symbolic links, or a link where none may be followed (`ELOOP`). + TooManyLinks, ///< Too many hard links (`EMLINK`). + MessageSize, ///< A message is too large (`EMSGSIZE`). + NameTooLong, ///< A name is too long (`ENAMETOOLONG`). + NoDevice, ///< No such device (`ENODEV`). + NoEntry, ///< No such file or directory (`ENOENT`). + NoLock, ///< No locks are available (`ENOLCK`). + InsufficientMemory, ///< Not enough memory (`ENOMEM`). + InsufficientSpace, ///< No space left on the device (`ENOSPC`). + NotDirectory, ///< A component that must be a directory is not one (`ENOTDIR`). + NotEmpty, ///< The directory is not empty (`ENOTEMPTY`). + NotRecoverable, ///< The state is not recoverable (`ENOTRECOVERABLE`). + Unsupported, ///< The operation is not supported (`ENOTSUP`). + NoTty, ///< Not a terminal (`ENOTTY`). + NoSuchDevice, ///< No such device or address (`ENXIO`). + Overflow, ///< A value does not fit its type (`EOVERFLOW`). + NotPermitted, ///< Refused by policy: a right the descriptor lacks, a path that leaves it, + ///< a reserved name (`EPERM`). + Pipe, ///< The other end of a pipe is gone (`EPIPE`). + ReadOnly, ///< The file system is read-only (`EROFS`). + InvalidSeek, ///< The object cannot seek (`ESPIPE`). + TextFileBusy, ///< The file is an executable in use (`ETXTBSY`). + CrossDevice, ///< The operation crosses file systems, or names a descriptor of another + ///< file system instance (`EXDEV`). + Last, ///< Not a code: the number of codes above it, so a table or a test can walk every one of + ///< them. **A new code goes above it, never below.** +}; + +/// @param code The error code to describe. +/// @return Lower-case words naming @p code, or `"unknown error"` for a value that is not one of the +/// codes (including @c FsErrorCode::Last). The switch has no `default`, so a new code makes +/// every compiler name this function. +[[nodiscard]] constexpr std::string_view toString(FsErrorCode code) noexcept +{ + switch (code) + { + case FsErrorCode::Access: return "access"; + case FsErrorCode::WouldBlock: return "would block"; + case FsErrorCode::Already: return "already"; + case FsErrorCode::BadDescriptor: return "bad descriptor"; + case FsErrorCode::Busy: return "busy"; + case FsErrorCode::Deadlock: return "deadlock"; + case FsErrorCode::Quota: return "quota"; + case FsErrorCode::Exist: return "exist"; + case FsErrorCode::FileTooLarge: return "file too large"; + case FsErrorCode::IllegalByteSequence: return "illegal byte sequence"; + case FsErrorCode::InProgress: return "in progress"; + case FsErrorCode::Interrupted: return "interrupted"; + case FsErrorCode::Invalid: return "invalid"; + case FsErrorCode::Io: return "io"; + case FsErrorCode::IsDirectory: return "is directory"; + case FsErrorCode::Loop: return "loop"; + case FsErrorCode::TooManyLinks: return "too many links"; + case FsErrorCode::MessageSize: return "message size"; + case FsErrorCode::NameTooLong: return "name too long"; + case FsErrorCode::NoDevice: return "no device"; + case FsErrorCode::NoEntry: return "no entry"; + case FsErrorCode::NoLock: return "no lock"; + case FsErrorCode::InsufficientMemory: return "insufficient memory"; + case FsErrorCode::InsufficientSpace: return "insufficient space"; + case FsErrorCode::NotDirectory: return "not directory"; + case FsErrorCode::NotEmpty: return "not empty"; + case FsErrorCode::NotRecoverable: return "not recoverable"; + case FsErrorCode::Unsupported: return "unsupported"; + case FsErrorCode::NoTty: return "no tty"; + case FsErrorCode::NoSuchDevice: return "no such device"; + case FsErrorCode::Overflow: return "overflow"; + case FsErrorCode::NotPermitted: return "not permitted"; + case FsErrorCode::Pipe: return "pipe"; + case FsErrorCode::ReadOnly: return "read only"; + case FsErrorCode::InvalidSeek: return "invalid seek"; + case FsErrorCode::TextFileBusy: return "text file busy"; + case FsErrorCode::CrossDevice: return "cross device"; + case FsErrorCode::Last: break; + } + return "unknown error"; +} + +/// A structured file-system error: a category, the raw system code it was classified from, and an +/// optional context string for diagnostics. +struct FsError +{ + FsErrorCode code = FsErrorCode::Io; ///< The error category. + std::int64_t systemCode = 0; ///< The raw errno, Win32 error or NTSTATUS, or 0 if none. + std::string context; ///< Optional human context (e.g. the failing call). + + /// @return The category in words, then the context and the system code where there are any, + /// for example `no entry (openat) [system code 2]`. + [[nodiscard]] CORE_FS_API std::string toString() const; +}; + +/// The result of a file-system operation. +template +using FsResult = std::expected; + +/// One row of a table that classifies a system code. +struct SystemErrorRow +{ + std::int64_t systemCode; ///< The errno, Win32 error or NTSTATUS. + FsErrorCode code; ///< What it means. +}; + +/// @return This platform's errno table, or its Win32 error table on Windows. +[[nodiscard]] CORE_FS_API std::span systemErrorTable() noexcept; + +/// @return The NTSTATUS table on Windows, which the native API (`NtCreateFile`) answers in; empty +/// elsewhere. +[[nodiscard]] CORE_FS_API std::span ntStatusTable() noexcept; + +/// @return The errno values an `O_NOFOLLOW` open answers when its final component is a symbolic +/// link: `ELOOP`, and `EMLINK` too where FreeBSD answers that; empty on Windows. +[[nodiscard]] CORE_FS_API std::span noFollowSymlinkErrnos() noexcept; + +/// Classifies an errno, or a Win32 error on Windows, through @c systemErrorTable. +/// @param systemCode The raw code, kept in the result. +/// @param context What failed, for diagnostics. +/// @return The error; @c FsErrorCode::Io for a code the table does not hold. +[[nodiscard]] CORE_FS_API FsError fsErrorFromSystemCode(std::int64_t systemCode, std::string context = {}); + +/// Classifies an NTSTATUS through @c ntStatusTable. +/// @param status The raw status, sign-extended from its 32 bits, and kept in the result. +/// @param context What failed, for diagnostics. +/// @return The error; @c FsErrorCode::Io for a status the table does not hold, which off Windows is +/// every status. +[[nodiscard]] CORE_FS_API FsError fsErrorFromNtStatus(std::int64_t status, std::string context = {}); + +} // namespace core::fs diff --git a/src/core/fs/FsError_test.cpp b/src/core/fs/FsError_test.cpp new file mode 100644 index 00000000..53365877 --- /dev/null +++ b/src/core/fs/FsError_test.cpp @@ -0,0 +1,201 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The file-system error vocabulary and the per-OS tables that classify a system code into it. The +// `#ifdef _WIN32` below selects test data, the codes this platform's tables hold; the logic under +// test is the same on every platform. +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 + #include +#endif + +using core::fs::FsError; +using core::fs::FsErrorCode; +using core::fs::fsErrorFromNtStatus; +using core::fs::fsErrorFromSystemCode; +using core::fs::noFollowSymlinkErrnos; +using core::fs::ntStatusTable; +using core::fs::systemErrorTable; + +static_assert(std::is_same_v, std::uint8_t>); +static_assert(FsErrorCode::CrossDevice < FsErrorCode::Last); + +namespace +{ + +constexpr auto CodeCount = static_cast(FsErrorCode::Last); + +} // namespace + +TEST_CASE("FsErrorCode: every code has a name in lower-case words", "[fs][error]") +{ + for (auto const index: std::views::iota(std::uint8_t { 0 }, CodeCount)) + { + auto const name = core::fs::toString(static_cast(index)); + CAPTURE(index, name); + CHECK(name != "unknown error"); + CHECK_FALSE(name.empty()); + CHECK(std::ranges::all_of( + name, [](char c) { return c == ' ' || (std::islower(static_cast(c)) != 0); })); + } + CHECK(core::fs::toString(FsErrorCode::Last) == "unknown error"); +} + +TEST_CASE("FsErrorCode: names are distinct", "[fs][error]") +{ + for (auto const left: std::views::iota(std::uint8_t { 0 }, CodeCount)) + for (auto const right: std::views::iota(static_cast(left + 1), CodeCount)) + CHECK(core::fs::toString(static_cast(left)) + != core::fs::toString(static_cast(right))); +} + +TEST_CASE("FsError: toString names the code, the context and the system code", "[fs][error]") +{ + auto const error = FsError { .code = FsErrorCode::NoEntry, .systemCode = 2, .context = "openat" }; + CHECK(error.toString() == "no entry (openat) [system code 2]"); + CHECK(FsError { .code = FsErrorCode::Exist, .systemCode = 0, .context = {} }.toString() == "exist"); +} + +TEST_CASE("systemErrorTable and ntStatusTable: every row maps below Last", "[fs][error]") +{ + CHECK_FALSE(systemErrorTable().empty()); + for (auto const& row: systemErrorTable()) + { + CAPTURE(row.systemCode); + CHECK(row.code < FsErrorCode::Last); + } + for (auto const& row: ntStatusTable()) + { + CAPTURE(row.systemCode); + CHECK(row.code < FsErrorCode::Last); + } +} + +TEST_CASE("fsErrorFromSystemCode: a missing file is NoEntry and keeps the raw code", "[fs][error]") +{ +#ifdef _WIN32 + auto const notFound = std::int64_t { ERROR_FILE_NOT_FOUND }; +#else + auto const notFound = std::int64_t { ENOENT }; +#endif + auto const error = fsErrorFromSystemCode(notFound, "open"); + CHECK(error.code == FsErrorCode::NoEntry); + CHECK(error.systemCode == notFound); + CHECK(error.context == "open"); +} + +TEST_CASE("fsErrorFromSystemCode: a link a call stopped on is Loop", "[fs][error]") +{ +#ifdef _WIN32 + auto const stopped = std::int64_t { ERROR_STOPPED_ON_SYMLINK }; +#else + auto const stopped = std::int64_t { ELOOP }; +#endif + CHECK(fsErrorFromSystemCode(stopped, "open").code == FsErrorCode::Loop); +} + +TEST_CASE("fsErrorFromSystemCode: an unknown code is Io", "[fs][error]") +{ + auto const error = fsErrorFromSystemCode(987'654'321); + CHECK(error.code == FsErrorCode::Io); + CHECK(error.systemCode == 987'654'321); +} + +TEST_CASE("fsErrorFromNtStatus: STATUS_OBJECT_NAME_NOT_FOUND where the table has it", "[fs][error]") +{ + // STATUS_OBJECT_NAME_NOT_FOUND, as the signed 32-bit NTSTATUS the API returns. + auto const notFound = std::int64_t { static_cast(0xC0000034U) }; + auto const error = fsErrorFromNtStatus(notFound, "NtCreateFile"); + CHECK(error.systemCode == notFound); + CHECK(error.context == "NtCreateFile"); +#ifdef _WIN32 + CHECK(error.code == FsErrorCode::NoEntry); +#else + CHECK(ntStatusTable().empty()); + CHECK(error.code == FsErrorCode::Io); +#endif +} + +TEST_CASE("fsErrorFromNtStatus: a reparse point met without following is Loop", "[fs][error]") +{ + // STATUS_REPARSE_POINT_ENCOUNTERED: OBJ_DONT_REPARSE met the one component an open names, a + // link that was not to be followed. + auto const encountered = std::int64_t { static_cast(0xC000050BU) }; + auto const error = fsErrorFromNtStatus(encountered, "NtCreateFile"); +#ifdef _WIN32 + CHECK(error.code == FsErrorCode::Loop); +#else + CHECK(error.code == FsErrorCode::Io); +#endif +} + +TEST_CASE("noFollowSymlinkErrnos: ELOOP wherever there is an errno", "[fs][error]") +{ +#ifdef _WIN32 + CHECK(noFollowSymlinkErrnos().empty()); +#else + CHECK(std::ranges::find(noFollowSymlinkErrnos(), ELOOP) != noFollowSymlinkErrnos().end()); +#endif +} + +TEST_CASE("systemErrorTable and ntStatusTable: every code the platform can report has a row", "[fs][error]") +{ + auto const covered = [](FsErrorCode code) { + auto const holds = [code](core::fs::SystemErrorRow const& row) { + return row.code == code; + }; + return std::ranges::any_of(systemErrorTable(), holds) || std::ranges::any_of(ntStatusTable(), holds); + }; +#ifdef _WIN32 + // The codes the Win32 and NT calls of the native descriptors can answer; the POSIX-only ones + // (WouldBlock, Deadlock, NoTty, TextFileBusy, ...) have no Windows code to come from. + using enum FsErrorCode; + for (auto const code: { Access, + BadDescriptor, + Busy, + Quota, + Exist, + FileTooLarge, + IllegalByteSequence, + Invalid, + IsDirectory, + Loop, + TooManyLinks, + NameTooLong, + NoEntry, + InsufficientMemory, + InsufficientSpace, + NotDirectory, + NotEmpty, + Unsupported, + NoSuchDevice, + NotPermitted, + Pipe, + ReadOnly, + InvalidSeek, + CrossDevice }) + { + CAPTURE(core::fs::toString(code)); + CHECK(covered(code)); + } +#else + // Every code is some errno's. + for (auto const index: std::views::iota(std::uint8_t { 0 }, CodeCount)) + { + auto const code = static_cast(index); + CAPTURE(core::fs::toString(code)); + CHECK(covered(code)); + } +#endif +} diff --git a/src/core/fs/NativeDescriptor_test.cpp b/src/core/fs/NativeDescriptor_test.cpp new file mode 100644 index 00000000..9a1cce1f --- /dev/null +++ b/src/core/fs/NativeDescriptor_test.cpp @@ -0,0 +1,364 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// What only the native descriptors owe: no system call on the caller's executor, a handle that +// outlives every call still parked on it, and a metadata hash keyed by the file system's secret. +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +using core::fs::Advice; +using core::fs::DescriptorFlags; +using core::fs::FsErrorCode; +using core::fs::IDescriptor; +using core::fs::IDirectoryStream; +using core::fs::MetadataHash; +using core::fs::OpenFlags; +using core::fs::SetToNow; +using core::fs::SymlinkPolicy; +using core::fs::test::bytesOf; +using core::fs::test::DescriptorFixture; +using core::fs::test::Outcome; +using core::fs::test::outcomeOf; +using core::fs::test::SymlinkSupport; +using core::fs::test::textOf; + +namespace +{ + +/// What a parked operation is started on: a fixture holding `f` (a file with content), `sub` (an +/// empty directory) and, where the system has them, `link` (a symbolic link to `f`), with `file` +/// open on `f`, `Read | Write`, and `stream` open on the root, not yet read. +struct ParkContext +{ + DescriptorFixture const* fixture = nullptr; + IDescriptor* root = nullptr; + IDescriptor* file = nullptr; + IDirectoryStream* stream = nullptr; +}; + +/// One operation, started but not driven: the task it returns. +struct ParkRow +{ + std::string_view operation; + core::async::Task (*start)(ParkContext); +}; + +constexpr auto NoFollow = SymlinkPolicy::NoFollow; + +// One row per operation the native descriptors implement, and the stream's next, whose first call +// reads a batch (ruling R6). +constexpr auto ParkRows = std::to_array({ + { "read", + [](ParkContext c) -> core::async::Task { co_return outcomeOf(co_await c.file->read(4, 0)); } }, + { "write", + [](ParkContext c) -> core::async::Task { + co_return outcomeOf(co_await c.file->write(bytesOf("x"), 0)); + } }, + { "append", + [](ParkContext c) -> core::async::Task { + co_return outcomeOf(co_await c.file->append(bytesOf("x"))); + } }, + { "advise", + [](ParkContext c) -> core::async::Task { + co_return outcomeOf(co_await c.file->advise(0, 0, Advice::Sequential)); + } }, + { "syncData", + [](ParkContext c) -> core::async::Task { co_return outcomeOf(co_await c.file->syncData()); } }, + { "sync", + [](ParkContext c) -> core::async::Task { co_return outcomeOf(co_await c.file->sync()); } }, + { "type", + [](ParkContext c) -> core::async::Task { co_return outcomeOf(co_await c.file->type()); } }, + { "setSize", + [](ParkContext c) -> core::async::Task { co_return outcomeOf(co_await c.file->setSize(1)); } }, + { "setTimes", + [](ParkContext c) -> core::async::Task { + co_return outcomeOf(co_await c.file->setTimes(SetToNow {}, SetToNow {})); + } }, + { "stat", + [](ParkContext c) -> core::async::Task { co_return outcomeOf(co_await c.file->stat()); } }, + { "metadataHash", + [](ParkContext c) -> core::async::Task { + co_return outcomeOf(co_await c.file->metadataHash()); + } }, + { "readDirectory", + [](ParkContext c) -> core::async::Task { + co_return outcomeOf(co_await c.root->readDirectory()); + } }, + { "IDirectoryStream::next", + [](ParkContext c) -> core::async::Task { co_return outcomeOf(co_await c.stream->next()); } }, + { "openAt", + [](ParkContext c) -> core::async::Task { + co_return outcomeOf(co_await c.root->openAt(NoFollow, "f", OpenFlags::None, DescriptorFlags::Read)); + } }, + { "createDirectoryAt", + [](ParkContext c) -> core::async::Task { + co_return outcomeOf(co_await c.root->createDirectoryAt("new")); + } }, + { "statAt", + [](ParkContext c) -> core::async::Task { + co_return outcomeOf(co_await c.root->statAt(NoFollow, "f")); + } }, + { "setTimesAt", + [](ParkContext c) -> core::async::Task { + co_return outcomeOf(co_await c.root->setTimesAt(NoFollow, "f", SetToNow {}, SetToNow {})); + } }, + { "linkAt", + [](ParkContext c) -> core::async::Task { + co_return outcomeOf(co_await c.root->linkAt(NoFollow, "f", c.root, "hard")); + } }, + { "readlinkAt", + [](ParkContext c) -> core::async::Task { + co_return outcomeOf(co_await c.root->readlinkAt("link")); + } }, + { "removeDirectoryAt", + [](ParkContext c) -> core::async::Task { + co_return outcomeOf(co_await c.root->removeDirectoryAt("sub")); + } }, + { "renameAt", + [](ParkContext c) -> core::async::Task { + co_return outcomeOf(co_await c.root->renameAt("f", c.root, "renamed")); + } }, + { "symlinkAt", + [](ParkContext c) -> core::async::Task { + co_return outcomeOf(co_await c.root->symlinkAt("f", "newlink")); + } }, + { "unlinkFileAt", + [](ParkContext c) -> core::async::Task { + co_return outcomeOf(co_await c.root->unlinkFileAt("f")); + } }, + { "metadataHashAt", + [](ParkContext c) -> core::async::Task { + co_return outcomeOf(co_await c.root->metadataHashAt(NoFollow, "f")); + } }, + { "isSameObject", + [](ParkContext c) -> core::async::Task { + co_return outcomeOf(co_await c.file->isSameObject(c.root)); + } }, + { "openPreopen", + [](ParkContext c) -> core::async::Task { + co_return outcomeOf(co_await c.fixture->fileSystem().openPreopen(c.fixture->hostDirectory(), + DescriptorFlags::Read)); + } }, +}); + +/// Opens `name` beneath @p fixture's root with @p flags. +std::unique_ptr openExisting(DescriptorFixture const& fixture, + std::string name, + DescriptorFlags flags) +{ + auto file = fixture.run(fixture.root().openAt(NoFollow, std::move(name), OpenFlags::None, flags)); + REQUIRE(file.has_value()); + return std::move(*file); +} + +} // namespace + +TEST_CASE("native: every descriptor operation parks on the blocking executor", "[fs][native]") +{ + for (auto const& row: ParkRows) + { + CAPTURE(row.operation); + auto fixture = DescriptorFixture::createNative(); + fixture.createFile("f", "content"); + REQUIRE(fixture.run(fixture.root().createDirectoryAt("sub")).has_value()); + if (fixture.requireSymlinks() == SymlinkSupport::Available) + REQUIRE(fixture.run(fixture.root().symlinkAt("f", "link")).has_value()); + auto const file = openExisting(fixture, "f", DescriptorFlags::Read | DescriptorFlags::Write); + auto stream = fixture.run(fixture.root().readDirectory()); + REQUIRE(stream.has_value()); + // The setup's own closes are queued on blocking; they are not the row's. + fixture.blocking().drain(); + fixture.home().drain(); + + auto task = row.start(ParkContext { + .fixture = &fixture, .root = &fixture.root(), .file = file.get(), .stream = stream->get() }); + task.handle().resume(); + fixture.home().drain(); + CHECK_FALSE(task.done()); + CHECK(fixture.blocking().pending() == 1); + + fixture.blocking().drain(); + CHECK_FALSE(task.done()); // it resumed on home, not inline on the blocking executor + CHECK(fixture.home().pending() == 1); + + fixture.home().drain(); + REQUIRE(task.done()); + auto const outcome = task.result(); + CHECK(outcome == std::nullopt); + } +} + +TEST_CASE("native: a descriptor dropped under a parked read never reads a reused handle", "[fs][native]") +{ + auto fixture = DescriptorFixture::createNative(); + fixture.createFile("a", "AAAA"); + // A second file system, with executors of its own, so `b` opens while the read is still parked. + auto other = DescriptorFixture::createNative(); + other.createFile("b", "BBBB"); + + auto a = openExisting(fixture, "a", DescriptorFlags::Read); + fixture.blocking().drain(); + fixture.home().drain(); + auto read = a->read(4, 0); + read.handle().resume(); + REQUIRE(fixture.blocking().pending() == 1); + + a.reset(); // the descriptor goes while its read is parked + auto const b = openExisting(other, "b", DescriptorFlags::Read); // takes the lowest free handle + + fixture.blocking().drain(); + fixture.home().drain(); + REQUIRE(read.done()); + auto const result = read.result(); + if (result) + CHECK(textOf(result->bytes) == "AAAA"); + else + CHECK(result.error().code == FsErrorCode::BadDescriptor); + CHECK(textOf(other.run(b->read(4, 0)).value().bytes) == "BBBB"); +} + +TEST_CASE("native: the metadata hash is keyed by the file system's secret", "[fs][native]") +{ + auto fixture = DescriptorFixture::createNative({}, 1); + fixture.createFile("f", "content"); + auto const hashIn = [](DescriptorFixture const& over) -> MetadataHash { + auto const file = openExisting(over, "f", DescriptorFlags::Read); + auto const hash = over.run(file->metadataHash()); + REQUIRE(hash.has_value()); + return *hash; + }; + + auto const first = hashIn(fixture); + CHECK(hashIn(fixture.sibling(1)) == first); + CHECK(hashIn(fixture.sibling(2)) != first); +} + +TEST_CASE("native: the last close of a handle runs on the blocking executor", "[fs][native]") +{ + auto fixture = DescriptorFixture::createNative(); + fixture.createFile("f", "content"); + + SECTION("a descriptor dropped with nothing in flight") + { + auto file = openExisting(fixture, "f", DescriptorFlags::Read); + fixture.blocking().drain(); + fixture.home().drain(); + REQUIRE(fixture.blocking().pending() == 0); + + file.reset(); + CHECK(fixture.home().pending() == 0); + CHECK(fixture.blocking().pending() == 1); // the close, queued rather than made here + fixture.blocking().drain(); + CHECK(fixture.blocking().pending() == 0); + } + SECTION("a descriptor dropped under a parked read") + { + auto file = openExisting(fixture, "f", DescriptorFlags::Read); + fixture.blocking().drain(); + fixture.home().drain(); + { + auto read = file->read(4, 0); + read.handle().resume(); + file.reset(); + REQUIRE(fixture.blocking().pending() == 1); // the read, holding the handle + + fixture.blocking().drain(); + fixture.home().drain(); + REQUIRE(read.done()); + CHECK(textOf(read.result().value().bytes) == "cont"); + CHECK(fixture.blocking().pending() == 0); + } // the read's frame, the handle's last owner, goes here, on the caller's thread + CHECK(fixture.blocking().pending() == 1); // and the close went to blocking + } +} + +namespace +{ + +/// A policy that splits on `|` alone, so `/` and `\` are ordinary characters to it: an override a +/// caller could pass, and which must never let the kernel see more than one component. +constexpr auto BarPolicy = core::fs::PathPolicy { + .separators = "|", + .targetSeparators = "|", + .reservedNames = {}, + .volumeSeparators = "", + .forbiddenCharacters = "", + .encoding = core::fs::PathEncoding::Utf8Bytes, + .caseRule = core::fs::CaseRule::Sensitive, + .trailing = core::fs::TrailingDotsAndSpaces::Allowed, +}; + +} // namespace + +TEST_CASE("native: a name never holds what the kernel splits on, whatever the policy", "[fs][native]") +{ + auto fixture = DescriptorFixture::createNative({ .policy = &BarPolicy }); + REQUIRE(fixture.run(fixture.root().createDirectoryAt("a")).has_value()); + fixture.createFile("f", "content"); + auto const nf = SymlinkPolicy::NoFollow; + + // Each would reach `a/b` beneath the root if the kernel resolved the name. + for (auto const* name: { "a/b", "a/." }) + { + CAPTURE(name); + CHECK(outcomeOf(fixture.run(fixture.root().createDirectoryAt(name))) == FsErrorCode::Invalid); + CHECK(outcomeOf(fixture.run(fixture.root().statAt(nf, name))) == FsErrorCode::Invalid); + CHECK( + outcomeOf(fixture.run(fixture.root().openAt(nf, name, OpenFlags::Create, DescriptorFlags::Write))) + == FsErrorCode::Invalid); + CHECK(outcomeOf(fixture.run(fixture.root().renameAt("f", &fixture.root(), name))) + == FsErrorCode::Invalid); + } + CHECK(outcomeOf(fixture.run(fixture.root().removeDirectoryAt("a/."))) == FsErrorCode::Invalid); + CHECK(fixture.run(fixture.root().statAt(nf, "f")).has_value()); +#ifdef _WIN32 + // Windows splits on `\` too, and `:` names a stream. + for (auto const* name: { "a\\b", "f:stream" }) + { + CAPTURE(name); + CHECK( + outcomeOf(fixture.run(fixture.root().openAt(nf, name, OpenFlags::Create, DescriptorFlags::Write))) + == FsErrorCode::Invalid); + } +#endif +} + +TEST_CASE("native: a chain of links longer than maxSymlinkHops is Loop", "[fs][native]") +{ + auto fixture = DescriptorFixture::createNative({ .maxSymlinkHops = 2 }); + if (fixture.requireSymlinks() == SymlinkSupport::Unavailable) + SKIP("this file system cannot create symbolic links"); + fixture.createFile("f", "content"); + REQUIRE(fixture.run(fixture.root().symlinkAt("f", "one")).has_value()); + REQUIRE(fixture.run(fixture.root().symlinkAt("one", "two")).has_value()); + REQUIRE(fixture.run(fixture.root().symlinkAt("two", "three")).has_value()); + auto const follow = SymlinkPolicy::Follow; + + CHECK(fixture.run(fixture.root().statAt(follow, "two"))->size == 7); + CHECK(outcomeOf(fixture.run(fixture.root().statAt(follow, "three"))) == FsErrorCode::Loop); + CHECK( + outcomeOf(fixture.run(fixture.root().openAt(follow, "three", OpenFlags::None, DescriptorFlags::Read))) + == FsErrorCode::Loop); +} + +TEST_CASE("native: a file system is not built to read nothing", "[fs][native]") +{ + auto home = core::async::testing::ManualExecutor {}; + auto blocking = core::async::testing::ManualExecutor {}; + auto const clock = core::platform::ManualWallClock {}; + auto random = core::fs::test::FixedRandom { 1 }; + auto const made = + core::fs::makeNativeDescriptorFileSystem(home, blocking, clock, random, { .maxReadChunk = 0 }); + REQUIRE_FALSE(made.has_value()); + CHECK(made.error().code == FsErrorCode::Invalid); +} diff --git a/src/core/fs/NativeFileSystem.hpp b/src/core/fs/NativeFileSystem.hpp new file mode 100644 index 00000000..7724dc42 --- /dev/null +++ b/src/core/fs/NativeFileSystem.hpp @@ -0,0 +1,104 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// The operating system's @c IDescriptorFileSystem: descriptors over real files and directories, +/// every system call made on an injected blocking executor. + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace core::fs +{ + +/// How many symbolic links one resolution follows before it answers `Loop`, as Linux's own limit. +inline constexpr std::size_t DefaultMaxSymlinkHops = 40; + +/// How a path is resolved beneath the descriptor it is relative to. +enum class BeneathStrategy : std::uint8_t +{ + Best, ///< What this system does best: `openat2(RESOLVE_BENEATH)` where Linux has it, else + ///< @c ComponentWalk. + ComponentWalk, ///< One component at a time, over held directory handles, on every system. +}; + +/// What a native file system is built with. Fixed at construction. +struct NativeFileSystemOptions +{ + std::size_t maxSymlinkHops = DefaultMaxSymlinkHops; ///< How many links one resolution follows before + ///< it answers `Loop`. Under `Best` on Linux + ///< the kernel counts the links before the + ///< final component against its own 40, so a + ///< lower limit makes `Best` walk instead. + BeneathStrategy strategy = BeneathStrategy::Best; ///< How paths are resolved. + std::size_t maxReadChunk = std::size_t { 1 } << 20U; ///< The most one read returns, whatever a + ///< caller asks for. + PathPolicy const* policy = nullptr; ///< The name rules; null is @c nativePathPolicy(). Must + ///< outlive the file system and its descriptors. +}; + +/// Builds the operating system's file system. +/// +/// Every operation of it and of its descriptors runs its system calls on @p blocking, through +/// @c async::offload, and resumes on @p home. Each such call holds the native handle it uses by +/// shared ownership, so a handle is closed only once its descriptor and every call still running +/// on it are gone: a descriptor dropped while a call is parked never lets that call reach another +/// file that reused the handle's number. The close itself is queued on @p blocking too, wherever +/// the last owner lets go. +/// +/// Teardown: drain or stop @p blocking before @p home is destroyed. A close still queued when +/// @p blocking is destroyed runs there and then. +/// +/// A path of the `*At` operations is resolved beneath the descriptor, never by the kernel from +/// anywhere else: `..` above it, an absolute path or link target and a link that leaves it are +/// `NotPermitted`, whichever @c BeneathStrategy resolves it. The final component is never resolved +/// by the kernel: every final call is made without following, on the directory that holds it. A +/// name holding what the kernel would split on (`/`, and `\` and `:` on Windows) is `Invalid` +/// whatever @c NativeFileSystemOptions::policy allows. +/// +/// On Windows: +/// - A junction, a mount point and every other reparse point that names another object by an +/// absolute path is a link that is never followed (`NotPermitted`); a symbolic link is followed +/// only where its target is relative. `readlinkAt` of such a link is `NotPermitted` too, where +/// POSIX returns an absolute target's text: no host path is handed out. +/// - `symlinkAt` makes a directory link where the target names a directory beneath the descriptor +/// (or ends in a separator, `.` or `..`), so that the system follows it too. It writes the link's +/// reparse point itself, which takes the symbolic-link privilege +/// (`SeCreateSymbolicLinkPrivilege`), and is `NotPermitted` without it. +/// - A directory link is a directory to the system: `linkAt` of one and `renameAt` of a file over +/// one are `IsDirectory`, where POSIX links and replaces it as any file. +/// - `renameAt` of a directory over an existing empty directory is refused by the system, where +/// POSIX replaces it. +/// - A reparse point that names nothing else (a cloud placeholder, a deduplicated file) opens +/// through its filter as the file it is, by the handle that was checked and refusing any reparse +/// the object manager would follow. A filter that serves its point by redirecting the open +/// elsewhere (a container's placeholders) is therefore refused (`NotPermitted`): safety first. +/// Before Windows 10 1803, which cannot refuse that reparse, such a point does not open at all. +/// - Every open identifies the process to a server it reaches (a named pipe, a share) at most at +/// identification level, so no server can impersonate it. +/// +/// @param home Where every operation resumes. Must outlive the file system and its descriptors. +/// @param blocking Where every system call runs. Must outlive them too. +/// @param wallClock What `SetToNow` reads where the system takes an explicit time (Windows). Must +/// outlive them too. +/// @param random Keys metadata hashes with a secret drawn once, here, so a hash reveals none of +/// the file identity, size or times it is computed from. +/// @param options What the file system is built with. +/// @return The file system; `Invalid` for a `maxReadChunk` of 0. +[[nodiscard]] CORE_FS_API FsResult> makeNativeDescriptorFileSystem( + async::IExecutor& home, + async::IExecutor& blocking, + platform::IWallClock const& wallClock, + IRandom& random, + NativeFileSystemOptions options = {}); + +} // namespace core::fs diff --git a/src/core/fs/PathPolicy.cpp b/src/core/fs/PathPolicy.cpp new file mode 100644 index 00000000..30a49ba6 --- /dev/null +++ b/src/core/fs/PathPolicy.cpp @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: Apache-2.0 +#include + +#include +#include + +namespace core::fs +{ + +namespace +{ + + using namespace std::string_view_literals; + + // A name's stem (what precedes its first dot, trailing spaces dropped) that Windows opens as a + // device wherever it appears. The superscript digits are U+00B9, U+00B2 and U+00B3, which + // Windows reads as COM1-3 and LPT1-3. + constexpr auto WindowsReservedNames = std::to_array({ + "CON", "PRN", "AUX", "NUL", "COM0", "COM1", "COM2", + "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", + "LPT0", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", + "LPT7", "LPT8", "LPT9", "COM\xc2\xb9", "COM\xc2\xb2", "COM\xc2\xb3", "LPT\xc2\xb9", + "LPT\xc2\xb2", "LPT\xc2\xb3", "CONIN$", "CONOUT$", + }); + + // The characters Win32 refuses in a name: the control characters 1-31 and <>:"|?*. The separators + // are not here; they separate. + constexpr auto WindowsForbiddenCharacters = + "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f" + "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f" + "<>:\"|?*"sv; + + constexpr auto PosixPolicy = PathPolicy { + .separators = "/", + .targetSeparators = "/", + .reservedNames = {}, + .volumeSeparators = {}, + .forbiddenCharacters = {}, + .encoding = PathEncoding::Utf8Bytes, + .caseRule = CaseRule::Sensitive, + .trailing = TrailingDotsAndSpaces::Allowed, + }; + + constexpr auto WindowsPolicy = PathPolicy { + .separators = "/\\", + .targetSeparators = "/\\", + .reservedNames = WindowsReservedNames, + .volumeSeparators = ":", + .forbiddenCharacters = WindowsForbiddenCharacters, + .encoding = PathEncoding::Utf16, + .caseRule = CaseRule::Insensitive, + .trailing = TrailingDotsAndSpaces::Refused, + }; + +} // namespace + +PathPolicy const& posixPathPolicy() noexcept +{ + return PosixPolicy; +} + +PathPolicy const& windowsPathPolicy() noexcept +{ + return WindowsPolicy; +} + +} // namespace core::fs diff --git a/src/core/fs/PathPolicy.hpp b/src/core/fs/PathPolicy.hpp new file mode 100644 index 00000000..e5c6cca0 --- /dev/null +++ b/src/core/fs/PathPolicy.hpp @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// The name rules a file system applies to a relative path: one `constexpr` row per operating +/// system, so the walker reads data rather than asking which platform it runs on. + +#include + +#include +#include +#include + +namespace core::fs +{ + +/// How a name reaches the operating system. +enum class PathEncoding : std::uint8_t +{ + Utf8Bytes, ///< As the UTF-8 bytes it is spelled in (POSIX). + Utf16, ///< Converted to UTF-16 (Windows). +}; + +/// Whether two names that differ only in case name one object. +enum class CaseRule : std::uint8_t +{ + Sensitive, ///< They name two (POSIX). + Insensitive, ///< They name one (Windows; ASCII letters are folded). +}; + +/// Whether a name may end in a dot or a space, which Windows strips from a name it opens, so that +/// `x.` and `x` would name one file. +enum class TrailingDotsAndSpaces : std::uint8_t +{ + Allowed, ///< An ordinary character at the end, too (POSIX). + Refused, ///< `Invalid` (Windows). +}; + +/// The name rules of one file system. +struct PathPolicy +{ + std::string_view separators; ///< What separates components of a path argument. + std::string_view targetSeparators; ///< What separates components of a symbolic link's target. + std::span reservedNames; ///< Device names refused as a name's stem, in any case. + std::string_view volumeSeparators; ///< What marks a symbolic link's target as naming a + ///< volume (`C:`), and so absolute, in its first + ///< component. + std::string_view forbiddenCharacters; ///< Characters a name may not hold, NUL aside, which + ///< no policy allows. + PathEncoding encoding; ///< How a name reaches the system. + CaseRule caseRule; ///< Whether case distinguishes names. + TrailingDotsAndSpaces trailing; ///< Whether a name may end in `.` or a space. +}; + +/// @return The POSIX rules: `/` separates, every other byte but NUL is a name's, names are case +/// sensitive. +[[nodiscard]] CORE_FS_API PathPolicy const& posixPathPolicy() noexcept; + +/// @return The Windows rules: `/` and `\` separate; `<>:"|?*` and the control characters are +/// forbidden; `CON PRN AUX NUL COM0-9 LPT0-9 COM¹²³ LPT¹²³ CONIN$ CONOUT$` are reserved as a +/// name's stem; a trailing dot or space is refused; names are case insensitive. +[[nodiscard]] CORE_FS_API PathPolicy const& windowsPathPolicy() noexcept; + +/// @return The rules of the operating system this was built for, chosen by the build. +[[nodiscard]] CORE_FS_API PathPolicy const& nativePathPolicy() noexcept; + +} // namespace core::fs diff --git a/src/core/fs/Rights.cpp b/src/core/fs/Rights.cpp new file mode 100644 index 00000000..2369063e --- /dev/null +++ b/src/core/fs/Rights.cpp @@ -0,0 +1,107 @@ +// SPDX-License-Identifier: Apache-2.0 +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace core::fs +{ + +namespace +{ + + using enum DescriptorFlags; + + // Read and resolve need Read; change an entry, MutateDirectory; change a file's bytes, Write. + // SetTimes is the one row with a choice: a file's times need Write, a directory's MutateDirectory. + // A directory never carries Write and a file never MutateDirectory (grantedFlags), so each kind + // meets the row only with its own flag. + constexpr auto RightsRows = std::to_array({ + { .operation = Operation::Read, .required = Read }, + { .operation = Operation::Write, .required = Write }, + { .operation = Operation::Append, .required = Write }, + { .operation = Operation::Advise, .required = None }, + { .operation = Operation::Sync, .required = None }, + { .operation = Operation::SetSize, .required = Write }, + { .operation = Operation::SetTimes, .required = Write | MutateDirectory }, + { .operation = Operation::Stat, .required = None }, + { .operation = Operation::MetadataHash, .required = None }, + { .operation = Operation::ReadDirectory, .required = Read }, + { .operation = Operation::OpenAt, .required = Read }, + { .operation = Operation::CreateDirectoryAt, .required = MutateDirectory }, + { .operation = Operation::StatAt, .required = Read }, + { .operation = Operation::SetTimesAt, .required = MutateDirectory }, + { .operation = Operation::LinkAt, .required = MutateDirectory }, + { .operation = Operation::ReadlinkAt, .required = Read }, + { .operation = Operation::RemoveDirectoryAt, .required = MutateDirectory }, + { .operation = Operation::RenameAt, .required = MutateDirectory }, + { .operation = Operation::SymlinkAt, .required = MutateDirectory }, + { .operation = Operation::UnlinkFileAt, .required = MutateDirectory }, + { .operation = Operation::MetadataHashAt, .required = Read }, + }); + static_assert(RightsRows.size() == static_cast(Operation::Last)); + + constexpr bool rowsFollowTheEnumeration() noexcept + { + return std::ranges::all_of( + std::views::iota(std::size_t { 0 }, RightsRows.size()), [](std::size_t index) { + return static_cast(RightsRows.at(index).operation) == index; + }); + } + static_assert(rowsFollowTheEnumeration(), "RightsRows must hold one row per Operation, in its order"); + + std::unexpected refuse(FsErrorCode code) noexcept + { + return std::unexpected { FsError { .code = code, .systemCode = 0, .context = {} } }; + } + +} // namespace + +std::span rightsTable() noexcept +{ + return RightsRows; +} + +FsResult checkRights(DescriptorFlags held, Operation operation) noexcept +{ + auto const row = std::ranges::find(RightsRows, operation, &RightsRow::operation); + if (row != RightsRows.end() && (row->required == None || hasFlag(held, row->required))) + return {}; + return refuse(FsErrorCode::NotPermitted); +} + +FsResult checkOpenRights(DescriptorFlags parent, OpenFlags open, DescriptorFlags child) noexcept +{ + // wasmtime's order: what the parent may not grant is NotPermitted before the flags themselves + // are judged. + auto const changesEntries = hasFlag(open, OpenFlags::Create) || hasFlag(open, OpenFlags::Truncate) + || hasFlag(open, OpenFlags::Exclusive); + if (hasFlag(child, Read) && !hasFlag(parent, Read)) + return refuse(FsErrorCode::NotPermitted); + auto const needsMutate = hasFlag(child, Write) || hasFlag(child, MutateDirectory) || changesEntries; + if (needsMutate && !hasFlag(parent, MutateDirectory)) + return refuse(FsErrorCode::NotPermitted); + if (hasFlag(open, OpenFlags::Directory) && changesEntries) + return refuse(FsErrorCode::Invalid); + if (hasFlag(open, OpenFlags::Directory) && hasFlag(child, Write)) + return refuse(FsErrorCode::IsDirectory); + return {}; +} + +DescriptorFlags grantedFlags(DescriptorType type, DescriptorFlags requested) noexcept +{ + if (type == DescriptorType::Directory) + return requested; + return static_cast(static_cast(requested) + & ~static_cast(MutateDirectory)); +} + +} // namespace core::fs diff --git a/src/core/fs/Rights.hpp b/src/core/fs/Rights.hpp new file mode 100644 index 00000000..da3303f1 --- /dev/null +++ b/src/core/fs/Rights.hpp @@ -0,0 +1,87 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// Which rights each descriptor operation needs, as one table every implementation enforces, and the +/// rule for the rights a child opened by `openAt` may carry. + +#include +#include +#include + +#include +#include + +namespace core::fs +{ + +/// An @c IDescriptor operation, as @c rightsTable names it. +enum class Operation : std::uint8_t +{ + Read, ///< @c IDescriptor::read. + Write, ///< @c IDescriptor::write. + Append, ///< @c IDescriptor::append. + Advise, ///< @c IDescriptor::advise. + Sync, ///< @c IDescriptor::sync and @c IDescriptor::syncData. + SetSize, ///< @c IDescriptor::setSize. + SetTimes, ///< @c IDescriptor::setTimes. + Stat, ///< @c IDescriptor::stat and @c IDescriptor::type. + MetadataHash, ///< @c IDescriptor::metadataHash. + ReadDirectory, ///< @c IDescriptor::readDirectory. + OpenAt, ///< @c IDescriptor::openAt, before @c checkOpenRights. + CreateDirectoryAt, ///< @c IDescriptor::createDirectoryAt. + StatAt, ///< @c IDescriptor::statAt. + SetTimesAt, ///< @c IDescriptor::setTimesAt. + LinkAt, ///< @c IDescriptor::linkAt, on both directories. + ReadlinkAt, ///< @c IDescriptor::readlinkAt. + RemoveDirectoryAt, ///< @c IDescriptor::removeDirectoryAt. + RenameAt, ///< @c IDescriptor::renameAt, on both directories. + SymlinkAt, ///< @c IDescriptor::symlinkAt. + UnlinkFileAt, ///< @c IDescriptor::unlinkFileAt. + MetadataHashAt, ///< @c IDescriptor::metadataHashAt. + Last, ///< Not an operation: the number of them, so a test can walk the table. +}; + +/// One row of @c rightsTable. +struct RightsRow +{ + Operation operation; ///< The operation. + DescriptorFlags required; ///< The descriptor must carry one of these; `None` needs nothing. +}; + +/// @return One row per @c Operation, in its order: what the descriptor it is called on must carry. +[[nodiscard]] CORE_FS_API std::span rightsTable() noexcept; + +/// Checks @p held against @p operation's row of @c rightsTable. +/// @param held The flags of the descriptor the operation is called on. +/// @param operation The operation. +/// @return Nothing, or `NotPermitted`. +[[nodiscard]] CORE_FS_API FsResult checkRights(DescriptorFlags held, Operation operation) noexcept; + +/// Checks what a child opened by @c IDescriptor::openAt may carry, against its parent directory: +/// - `Read` needs the parent's `Read`; +/// - `Write` or `MutateDirectory`, and `Create`, `Truncate` or `Exclusive`, need the parent's +/// `MutateDirectory`; +/// - the three sync flags are a mode, not a right, and need nothing; +/// - then, as wasmtime checks them only once the rights hold: `Directory` with `Create`, +/// `Truncate` or `Exclusive` is `Invalid`, and a directory never carries `Write` (`IsDirectory`). +/// @param parent The flags of the directory @c openAt is called on. +/// @param open How the child is opened. +/// @param child The flags the child asks for. +/// @return Nothing, or `NotPermitted`, `IsDirectory` or `Invalid`. +[[nodiscard]] CORE_FS_API FsResult checkOpenRights(DescriptorFlags parent, + OpenFlags open, + DescriptorFlags child) noexcept; + +/// The flags a descriptor opened with @p requested carries once its object is known: only a +/// directory carries `MutateDirectory`, so a file asked for it gets the rest, as in wasmtime. +/// Together with @c checkOpenRights' rule that a directory never carries `Write`, this is what lets +/// @c Operation::SetTimes need "one of `Write` and `MutateDirectory`": a file has only the first to +/// offer, a directory only the second. +/// @param type What the new descriptor refers to. +/// @param requested The flags `openAt` was asked for, already held to @c checkOpenRights. +/// @return The flags it carries. +[[nodiscard]] CORE_FS_API DescriptorFlags grantedFlags(DescriptorType type, + DescriptorFlags requested) noexcept; + +} // namespace core::fs diff --git a/src/core/fs/bsd/ErrnoTable.cpp b/src/core/fs/bsd/ErrnoTable.cpp new file mode 100644 index 00000000..49f1ae20 --- /dev/null +++ b/src/core/fs/bsd/ErrnoTable.cpp @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The errno tables of Apple and the BSDs. +#include +#include + +#include +#include +#include + +namespace core::fs +{ + +namespace +{ + + // FreeBSD answers an O_NOFOLLOW open of a symbolic link with EMLINK, where POSIX says ELOOP and + // macOS and the other BSDs answer that. EMLINK cannot come from an open otherwise, so the row costs + // the systems that never send it nothing. + constexpr auto NoFollowSymlinkErrnos = std::to_array({ ELOOP, EMLINK }); + +} // namespace + +std::span systemErrorTable() noexcept +{ + return detail::ErrnoRows; +} + +std::span ntStatusTable() noexcept +{ + return {}; +} + +std::span noFollowSymlinkErrnos() noexcept +{ + return NoFollowSymlinkErrnos; +} + +} // namespace core::fs diff --git a/src/core/fs/darwin/PosixSystem.cpp b/src/core/fs/darwin/PosixSystem.cpp new file mode 100644 index 00000000..3a4623df --- /dev/null +++ b/src/core/fs/darwin/PosixSystem.cpp @@ -0,0 +1,165 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The descriptor calls of Apple's systems: the `st_atimespec` family of times; `F_RDADVISE` for +// read-ahead, the one advice macOS can act on (it has no `posix_fadvise`); and `F_FULLFSYNC`, without +// which macOS's `fsync` leaves the data in the drive's cache. macOS has no `O_RSYNC`. +#include + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace core::fs::detail +{ + +namespace +{ + + FileTime fileTimeOf(struct ::timespec const& time) noexcept + { + return FileTime { .seconds = time.tv_sec, .nanoseconds = static_cast(time.tv_nsec) }; + } + + /// What an @c Advice becomes here. + enum class AdviceAction : std::uint8_t + { + Ignore, ///< Nothing to tell the system; the advice succeeds. + ReadAhead, ///< `F_RDADVISE` over the range. + }; + + struct AdviceRow + { + Advice advice; + AdviceAction action; + }; + + constexpr auto AdviceRows = std::to_array({ + { .advice = Advice::Normal, .action = AdviceAction::Ignore }, + { .advice = Advice::Sequential, .action = AdviceAction::Ignore }, + { .advice = Advice::Random, .action = AdviceAction::Ignore }, + { .advice = Advice::WillNeed, .action = AdviceAction::ReadAhead }, + { .advice = Advice::DontNeed, .action = AdviceAction::Ignore }, + { .advice = Advice::NoReuse, .action = AdviceAction::Ignore }, + }); + + struct SyncFlagRow + { + DescriptorFlags flag; + int openFlag; ///< 0 where this system has no such mode. + }; + + constexpr auto SyncFlagRows = std::to_array({ + { .flag = DescriptorFlags::FileIntegritySync, .openFlag = O_SYNC }, + { .flag = DescriptorFlags::DataIntegritySync, .openFlag = O_DSYNC }, + { .flag = DescriptorFlags::RequestedWriteSync, .openFlag = 0 }, + }); + + FsResult readAhead(int handle, std::uint64_t offset, std::uint64_t length) + { + if (length == 0) + { + struct ::stat status {}; + if (::fstat(handle, &status) != 0) + return errnoError("fstat"); + auto const size = static_cast(status.st_size); + length = offset < size ? size - offset : 0; + } + auto advisory = + ::radvisory { .ra_offset = static_cast(offset), + .ra_count = static_cast(std::min(length, INT_MAX)) }; + if (advisory.ra_count == 0) + return {}; + if (::fcntl(handle, F_RDADVISE, &advisory) == -1) + return errnoError("fcntl(F_RDADVISE)"); + return {}; + } + + /// `F_FULLFSYNC`, or `fsync` where it fails, as SQLite and libuv do: network and FUSE file + /// systems answer ENOTSUP, ENOTTY or EINVAL for it, and `fsync` is the best they offer. + FsResult fullSync(int handle) + { + if (::fcntl(handle, F_FULLFSYNC) != -1) + return {}; + if (retryOnInterrupt([handle] { return ::fsync(handle); }) != 0) + return errnoError("fsync"); + return {}; + } + +} // namespace + +StatTimes timesOf(struct ::stat const& status) noexcept +{ + return StatTimes { .accessed = fileTimeOf(status.st_atimespec), + .modified = fileTimeOf(status.st_mtimespec), + .statusChanged = fileTimeOf(status.st_ctimespec) }; +} + +FsResult adviseRange(int handle, std::uint64_t offset, std::uint64_t length, Advice advice) +{ + constexpr auto OffsetMax = static_cast(std::numeric_limits::max()); + if (offset > OffsetMax || length > OffsetMax) + return refuse(FsErrorCode::Invalid); + auto const row = std::ranges::find(AdviceRows, advice, &AdviceRow::advice); + if (row == AdviceRows.end()) + return refuse(FsErrorCode::Invalid); + switch (row->action) + { + case AdviceAction::Ignore: return {}; + case AdviceAction::ReadAhead: return readAhead(handle, offset, length); + } + return refuse(FsErrorCode::Invalid); +} + +FsResult syncData(int handle) +{ + return fullSync(handle); +} + +FsResult syncAll(int handle) +{ + return fullSync(handle); +} + +FsResult syncOpenFlags(DescriptorFlags flags) +{ + auto openFlags = 0; + for (auto const& row: SyncFlagRows) + { + if (!hasFlag(flags, row.flag)) + continue; + if (row.openFlag == 0) + return refuse(FsErrorCode::Unsupported); + openFlags |= row.openFlag; + } + return openFlags; +} + +FsError openFailure(int directory, std::string const& name, int flags, int error) +{ + // macOS refuses O_CREAT on an existing directory with EACCES (EPERM on some file systems), + // where Linux answers EISDIR: the name, unfollowed, tells which it was. + struct ::stat status {}; + if ((error == EACCES || error == EPERM) && (flags & O_CREAT) != 0 + && ::fstatat(directory, name.c_str(), &status, AT_SYMLINK_NOFOLLOW) == 0 && S_ISDIR(status.st_mode)) + return FsError { .code = FsErrorCode::IsDirectory, .systemCode = error, .context = "openat" }; + if ((flags & O_NOFOLLOW) != 0 + && std::ranges::find(noFollowSymlinkErrnos(), error) != noFollowSymlinkErrnos().end()) + return FsError { .code = FsErrorCode::Loop, .systemCode = error, .context = "openat" }; + return fsErrorFromSystemCode(error, "openat"); +} + +} // namespace core::fs::detail diff --git a/src/core/fs/detail/DirectoryStream.cpp b/src/core/fs/detail/DirectoryStream.cpp new file mode 100644 index 00000000..dd463e09 --- /dev/null +++ b/src/core/fs/detail/DirectoryStream.cpp @@ -0,0 +1,40 @@ +// SPDX-License-Identifier: Apache-2.0 +#include + +#include +#include +#include + +#include +#include +#include + +namespace core::fs::detail +{ + +async::Task>> BatchedDirectoryStream::next() +{ + // A batch may hold no entry and still not end the directory (one that read only `.` and `..`). + while (_position == _entries.size()) + { + if (_end == StreamEnd::Reached) + co_return std::optional {}; + auto batch = co_await fetch(); + _entries.clear(); + _position = 0; + if (!batch) + { + _end = StreamEnd::Reached; + co_return std::unexpected { std::move(batch.error()) }; + } + _entries = std::move(batch->entries); + _end = batch->end; + } + auto entry = std::move(_entries[_position]); + ++_position; + if (!entry) + co_return std::unexpected { std::move(entry.error()) }; + co_return std::optional { std::move(*entry) }; +} + +} // namespace core::fs::detail diff --git a/src/core/fs/detail/DirectoryStream.hpp b/src/core/fs/detail/DirectoryStream.hpp new file mode 100644 index 00000000..7b856622 --- /dev/null +++ b/src/core/fs/detail/DirectoryStream.hpp @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// What every directory stream shares: it reads the directory in batches of bounded size, one hop +/// to the blocking executor per batch, and hands the entries out one call at a time, so it never +/// holds more of a directory than one batch, however large the directory is. Private to the fs +/// module. + +#include +#include +#include + +#include +#include +#include + +namespace core::fs::detail +{ + +/// The most entries one batch of a stream that counts entries (`readdir`, in memory) reads. One +/// that reads records reads what @c DirectoryBufferBytes holds instead. +inline constexpr std::size_t DirectoryBatchEntries = 64; + +/// The buffer a stream that reads records (Linux's `getdents64`, Windows' +/// `FileIdBothDirectoryInfo`) holds and reads each batch into. +inline constexpr std::size_t DirectoryBufferBytes = std::size_t { 64 } * 1024; + +/// What one batch read of a directory came to. +struct DirectoryBatch +{ + /// The entries read, in order, each an entry or why it cannot be one (a name that is not UTF-8). + /// Never `.` or `..`. + std::vector> entries; + /// @c StreamEnd::Reached where the directory has nothing after them. + StreamEnd end = StreamEnd::More; +}; + +/// A directory stream that reads through @c fetch, a batch at a time, and answers @c next from the +/// batch in hand without a hop until it is spent. One call at a time: a call is made once the one +/// before it has completed. A pending @c next resumes into the stream, which must outlive it. +class BatchedDirectoryStream: public IDirectoryStream +{ + public: + /// @return The next entry; nullopt once the directory has ended, and from then on. A batch that + /// failed is answered with its error once, and ends the stream. + [[nodiscard]] async::Task>> next() final; + + protected: + /// Reads the next batch, on the blocking executor. Called only once the batch before it is + /// spent, and never again after one that ended the directory or failed. + /// @return The batch; why the directory could not be read. + [[nodiscard]] virtual async::Task> fetch() = 0; + + private: + std::vector> _entries; ///< The batch in hand. + std::size_t _position = 0; ///< The next of @c _entries to hand out. + StreamEnd _end = StreamEnd::More; ///< Whether a batch ended the directory. +}; + +} // namespace core::fs::detail diff --git a/src/core/fs/detail/NativeSupport.cpp b/src/core/fs/detail/NativeSupport.cpp new file mode 100644 index 00000000..c6ef27c0 --- /dev/null +++ b/src/core/fs/detail/NativeSupport.cpp @@ -0,0 +1,161 @@ +// SPDX-License-Identifier: Apache-2.0 +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace core::fs::detail +{ + +namespace +{ + + /// Eight 64-bit words: device, the two halves of the file id, size, and two times of two words. + constexpr std::size_t MessageSize = 8 * sizeof(std::uint64_t); + + /// The bytes @c hashMetadata hashes: every field, little-endian, in declaration order. + class MessageWriter + { + public: + void put(std::uint64_t value) noexcept + { + for (auto const shift: std::views::iota(0U, 8U)) + _bytes.at(_size++) = static_cast((value >> (shift * 8U)) & 0xFFU); + } + + void put(FileTime time) noexcept + { + put(static_cast(time.seconds)); + put(std::uint64_t { time.nanoseconds }); + } + + [[nodiscard]] std::span bytes() const noexcept { return { _bytes.data(), _size }; } + + private: + std::array _bytes {}; + std::size_t _size = 0; + }; + + std::uint64_t littleEndianAt(Sha256::Digest const& digest, std::size_t offset) noexcept + { + auto value = std::uint64_t { 0 }; + for (auto const index: std::views::iota(std::size_t { 0 }, std::size_t { 8 })) + value |= std::to_integer(digest.at(offset + index)) << (index * 8U); + return value; + } + +} // namespace + +std::unexpected refuse(FsErrorCode code) +{ + return std::unexpected { FsError { .code = code, .systemCode = 0, .context = {} } }; +} + +FsResult checkOptions(NativeFileSystemOptions const& options) +{ + if (options.maxReadChunk == 0) + return std::unexpected { FsError { + .code = FsErrorCode::Invalid, .systemCode = 0, .context = "maxReadChunk must be above 0" } }; + return {}; +} + +NativeContext::NativeContext(async::IExecutor& homeExecutor, + async::IExecutor& blockingExecutor, + platform::IWallClock const& clock, + IRandom& random, + NativeFileSystemOptions fileSystemOptions, + std::string_view separators, + INtFiles const* files): + home { &homeExecutor }, + blocking { &blockingExecutor }, + wallClock { &clock }, + policy { fileSystemOptions.policy != nullptr ? fileSystemOptions.policy : &nativePathPolicy() }, + kernelSeparators { separators }, + options { fileSystemOptions }, + // The kernel counts the links before the final name against its own 40: a lower limit is kept + // only by the walk. + beneathOpener { fileSystemOptions.strategy == BeneathStrategy::Best + && fileSystemOptions.maxSymlinkHops >= DefaultMaxSymlinkHops + ? makeBestBeneathOpener() + : nullptr }, + ntFiles { files } +{ + random.fill(secret); +} + +MetadataHash hashMetadata(MetadataSecret const& secret, MetadataFields const& fields) noexcept +{ + auto message = MessageWriter {}; + message.put(fields.device); + message.put(fields.fileIdLow); + message.put(fields.fileIdHigh); + message.put(fields.size); + message.put(fields.modified); + message.put(fields.statusChanged); + auto const digest = hmacSha256(secret, message.bytes()); + return MetadataHash { .lower = littleEndianAt(digest, 0), .upper = littleEndianAt(digest, 8) }; +} + +FileTime fileTimeOf(std::chrono::system_clock::time_point when) noexcept +{ + auto const sinceEpoch = when.time_since_epoch(); + auto const seconds = std::chrono::floor(sinceEpoch); + return FileTime { + .seconds = seconds.count(), + .nanoseconds = static_cast( + std::chrono::duration_cast(sinceEpoch - seconds).count()) + }; +} + +FsResult requireDirectory(DescriptorType type) +{ + if (type != DescriptorType::Directory) + return refuse(FsErrorCode::NotDirectory); + return {}; +} + +FsResult NativeDescriptorBase::sameSystemTarget(IDescriptor* other) const +{ + if (other == nullptr) + return refuse(FsErrorCode::BadDescriptor); + auto const* mine = dynamic_cast(other); + if (mine == nullptr || mine->_context != _context) + return refuse(FsErrorCode::CrossDevice); + return Target { .handle = mine->_handle, .flags = mine->_flags, .type = mine->_type }; +} + +FsResult> NativeDescriptorBase::sameObjectCandidate( + IDescriptor* other) const +{ + auto target = sameSystemTarget(other); + if (target) + return std::optional { std::move(*target) }; + if (target.error().code == FsErrorCode::CrossDevice) + return std::optional {}; + return std::unexpected { std::move(target.error()) }; +} + +WalkRules walkRulesOf(NativeContext const& context, + SymlinkPolicy finalPolicy, + TrailingSlashOnLink onLink) noexcept +{ + return WalkRules { .policy = context.policy, + .finalPolicy = finalPolicy, + .onLink = onLink, + .maxSymlinkHops = context.options.maxSymlinkHops, + .kernelSeparators = context.kernelSeparators }; +} + +} // namespace core::fs::detail diff --git a/src/core/fs/detail/NativeSupport.hpp b/src/core/fs/detail/NativeSupport.hpp new file mode 100644 index 00000000..53af6848 --- /dev/null +++ b/src/core/fs/detail/NativeSupport.hpp @@ -0,0 +1,191 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// What the native descriptors of every operating system share: the configuration a file system +/// fixes at construction, the descriptor base that offloads and recognises its siblings, the keyed +/// metadata hash, and the walk's rules. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace core::fs::detail +{ + +class INtFiles; // windows/WindowsPathWalk.hpp + +/// @param code What refused. +/// @return The refusal, with no system code. +[[nodiscard]] std::unexpected refuse(FsErrorCode code); + +/// Checks what a native file system is built with. +/// @param options The options. +/// @return Nothing, or `Invalid` for a `maxReadChunk` of 0, which would make every read return +/// nothing and claim more is to come. +[[nodiscard]] FsResult checkOptions(NativeFileSystemOptions const& options); + +/// The key of a file system's metadata hashes. +using MetadataSecret = std::array; + +/// What one native file system and all of its descriptors share, fixed at construction. +struct NativeContext +{ + async::IExecutor* home = nullptr; ///< Where every operation resumes. + async::IExecutor* blocking = nullptr; ///< Where every system call runs. + platform::IWallClock const* wallClock = nullptr; ///< What `SetToNow` reads where it is explicit. + PathPolicy const* policy = nullptr; ///< The name rules, never null. + /// What the kernel itself would split a name on (`/`; `\`, `/` and `:` on Windows): refused in + /// a name whatever @c policy allows, so an overriding policy can never hand the kernel more + /// than one component to resolve. + std::string_view kernelSeparators; + NativeFileSystemOptions options; ///< What the file system was built with. + MetadataSecret secret {}; ///< The key of its metadata hashes. + /// The kernel's beneath step @c NativeFileSystemOptions::strategy chose, probed once, here; + /// null where every path is walked one component at a time, which is also the case under + /// `Best` with a `maxSymlinkHops` below @c DefaultMaxSymlinkHops, a limit only the walk keeps. + std::shared_ptr beneathOpener; + /// The NT calls a Windows file system opens, inspects and identifies through: the system's, or a + /// test's scripted ones. Null on every other system. + INtFiles const* ntFiles = nullptr; + + /// @param homeExecutor Where every operation resumes. + /// @param blockingExecutor Where every system call runs. + /// @param clock What `SetToNow` reads. + /// @param random Where the secret is drawn from, once, here. + /// @param fileSystemOptions What the file system is built with; a null policy is the native one. + /// @param separators What this kernel splits a name on. + /// @param files The NT calls on Windows; null elsewhere. Must outlive the file system. + /// The strategy's opener is made here: under `Best`, from @c makeBestBeneathOpener. + NativeContext(async::IExecutor& homeExecutor, + async::IExecutor& blockingExecutor, + platform::IWallClock const& clock, + IRandom& random, + NativeFileSystemOptions fileSystemOptions, + std::string_view separators, + INtFiles const* files); +}; + +/// How a native file system and its descriptors share their @c NativeContext. +using SharedContext = std::shared_ptr; + +/// What a metadata hash is computed over: the object's identity, size and the times its data and +/// its metadata last changed. +struct MetadataFields +{ + std::uint64_t device = 0; ///< The device or volume. + std::uint64_t fileIdLow = 0; ///< The file id on it, low 64 bits. + std::uint64_t fileIdHigh = 0; ///< The file id, high 64 bits (Windows' 128-bit ids). + std::uint64_t size = 0; ///< The size in bytes. + FileTime modified; ///< The last change of its data. + FileTime statusChanged; ///< The last change of its metadata. +}; + +/// HMAC-SHA-256 of @p fields, keyed by @p secret, truncated to 128 bits: it changes when any field +/// does and reveals none of them to whoever does not hold the secret. +/// @param secret The file system's key. +/// @param fields What is hashed. +/// @return The hash. +[[nodiscard]] MetadataHash hashMetadata(MetadataSecret const& secret, MetadataFields const& fields) noexcept; + +/// @param when An instant of the wall clock. +/// @return It as seconds and nanoseconds since the Unix epoch. +[[nodiscard]] FileTime fileTimeOf(std::chrono::system_clock::time_point when) noexcept; + +/// @param type What a descriptor refers to. +/// @return Nothing for a directory; `NotDirectory` otherwise, since a file descriptor resolves no +/// path. +[[nodiscard]] FsResult requireDirectory(DescriptorType type); + +/// @param context A file system's context. +/// @param finalPolicy Whether a final link is followed. +/// @param onLink What a trailing `/` does to a final link under `NoFollow`. +/// @return The walk's rules under @p context's policy, hop limit and kernel separators. +[[nodiscard]] WalkRules walkRulesOf(NativeContext const& context, + SymlinkPolicy finalPolicy, + TrailingSlashOnLink onLink) noexcept; + +/// What the native descriptors of every OS share: the file system's context, the handle, the +/// flags and the type, the offload every operation goes through, and the recognition of a +/// descriptor of the same file system passed as `newDirectory`. +class NativeDescriptorBase: public IDescriptor +{ + public: + /// @return The flags the descriptor carries. + [[nodiscard]] DescriptorFlags flags() const noexcept final { return _flags; } + + protected: + /// @param context The file system's. + /// @param handle The descriptor's handle. + /// @param flags What it carries. + /// @param type What it refers to. + NativeDescriptorBase(SharedContext context, + SharedHandle handle, + DescriptorFlags flags, + DescriptorType type): + _context { std::move(context) }, _handle { std::move(handle) }, _flags { flags }, _type { type } + { + } + + /// A directory passed as `newDirectory`: its handle, rights and type, read on the caller's + /// thread while the caller still holds it. + struct Target + { + SharedHandle handle; ///< Its handle, shared with the job. + DescriptorFlags flags = DescriptorFlags::None; ///< Its rights. + DescriptorType type = DescriptorType::Unknown; ///< What it is. + }; + + /// Runs @p work on the blocking executor and resumes on home. @p work captures by value + /// everything it uses, the handle included, and never the descriptor. + template + [[nodiscard]] auto submit(F work) const + { + return async::offload(_context->home, _context->blocking, std::move(work)); + } + + /// @return @p other's handle, rights and type; `CrossDevice` unless it is a descriptor of this + /// very file system, `BadDescriptor` for none at all. + [[nodiscard]] FsResult sameSystemTarget(IDescriptor* other) const; + + /// @return @p other's handle, rights and type, for @c isSameObject; nullopt where it is a + /// descriptor of another file system, which is never the same object (D11); + /// `BadDescriptor` for none at all. + [[nodiscard]] FsResult> sameObjectCandidate(IDescriptor* other) const; + + /// @return The file system's context. + [[nodiscard]] SharedContext const& context() const noexcept { return _context; } + + /// @return The descriptor's handle. + [[nodiscard]] SharedHandle const& handle() const noexcept { return _handle; } + + /// @return What the descriptor refers to. + [[nodiscard]] DescriptorType objectType() const noexcept { return _type; } + + private: + SharedContext _context; + SharedHandle _handle; + DescriptorFlags _flags; + DescriptorType _type; +}; + +} // namespace core::fs::detail diff --git a/src/core/fs/detail/OwnedHandle.hpp b/src/core/fs/detail/OwnedHandle.hpp new file mode 100644 index 00000000..65b34f4c --- /dev/null +++ b/src/core/fs/detail/OwnedHandle.hpp @@ -0,0 +1,144 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// The native handles of the fs module: one a job holds alone, and one a descriptor shares with +/// every job in flight on it (decision C2), whose last owner hands the close to the blocking +/// executor so `close` never runs on the caller's loop. + +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace core::fs::detail +{ + +/// Closes @p handle: `close` on POSIX, `CloseHandle` on Windows. Defined by the platform's +/// descriptor source. +/// @param handle An open handle, closed exactly once. +CORE_FS_API void closeNativeHandle(platform::NativeHandle handle) noexcept; + +/// An open native handle with one owner, closed where it is destroyed: a handle a job opens and +/// closes on the blocking executor, or one on its way to becoming an @c OwnedHandle. +class UniqueHandle +{ + public: + /// @param handle An open handle; this object closes it. + explicit UniqueHandle(platform::NativeHandle handle) noexcept: _handle { handle } {} + + UniqueHandle(UniqueHandle const&) = delete; + UniqueHandle& operator=(UniqueHandle const&) = delete; + + UniqueHandle(UniqueHandle&& other) noexcept: + _handle { std::exchange(other._handle, platform::InvalidHandle) } + { + } + + UniqueHandle& operator=(UniqueHandle&& other) noexcept + { + if (this != &other) + { + reset(); + _handle = std::exchange(other._handle, platform::InvalidHandle); + } + return *this; + } + + ~UniqueHandle() { reset(); } + + /// Closes the handle now, if it is still open. + void reset() noexcept + { + if (_handle != platform::InvalidHandle) + closeNativeHandle(std::exchange(_handle, platform::InvalidHandle)); + } + + /// @return The handle, borrowed for as long as this object holds it. + [[nodiscard]] platform::NativeHandle get() const noexcept { return _handle; } + + /// Gives the handle up without closing it, to an owner that closes it otherwise (`fdopendir`). + /// @return The handle, now the caller's to close. + [[nodiscard]] platform::NativeHandle release() noexcept + { + return std::exchange(_handle, platform::InvalidHandle); + } + + private: + platform::NativeHandle _handle; +}; + +/// Closes @p handle on @p closer. Should the executor free this frame without running it (an +/// executor destroyed with work queued), the handle closes there and then, rather than leaking. +/// @param closer Where the close runs. +/// @param handle The handle to close. +inline async::DetachedTask closeOn(async::IExecutor* closer, UniqueHandle handle) +{ + co_await async::ResumeOn { *closer }; + handle.reset(); +} + +/// The handle a descriptor and every job it offloads share. +/// +/// A descriptor holds it through a @c SharedHandle, and every job captures a copy of that pointer +/// by value, so the handle stays open until the last of them is gone: a descriptor dropped while a +/// read is parked leaves the read its handle, and no other open can reuse the number until the read +/// has run. Whoever lets go last, on whatever thread, the close itself runs on the blocking +/// executor: `close` on a network file system can wait as long as a read. +class OwnedHandle +{ + public: + /// @param handle The open handle. + /// @param closer Where it is closed; the blocking executor. Must outlive this object, or be + /// destroyed with the close still queued, which then closes inline. + OwnedHandle(UniqueHandle handle, async::IExecutor& closer) noexcept: + _handle { std::move(handle) }, _closer { &closer } + { + } + + OwnedHandle(OwnedHandle const&) = delete; + OwnedHandle(OwnedHandle&&) = delete; + OwnedHandle& operator=(OwnedHandle const&) = delete; + OwnedHandle& operator=(OwnedHandle&&) = delete; + + /// Queues the close on the closer; where the frame that would run it cannot be allocated, the + /// handle closes here instead, since a destructor may not throw. + ~OwnedHandle() + { + try + { + closeOn(_closer, std::move(_handle)); + } + catch (std::bad_alloc const&) + { + // The handle was moved into the call's argument, which closed it as the call unwound; + // this closes it should it still be here. + _handle.reset(); + } + } + + /// @return The handle, borrowed for as long as this object lives. + [[nodiscard]] platform::NativeHandle get() const noexcept { return _handle.get(); } + + private: + UniqueHandle _handle; + async::IExecutor* _closer; +}; + +/// How a descriptor and its jobs share an @c OwnedHandle. +using SharedHandle = std::shared_ptr; + +/// @param handle An open handle. +/// @param closer Where its last owner's close runs: the blocking executor. +/// @return It, shared. +[[nodiscard]] inline SharedHandle shareHandle(UniqueHandle handle, async::IExecutor& closer) +{ + return std::make_shared(std::move(handle), closer); +} + +} // namespace core::fs::detail diff --git a/src/core/fs/detail/PathWalk.cpp b/src/core/fs/detail/PathWalk.cpp new file mode 100644 index 00000000..c6d23e7b --- /dev/null +++ b/src/core/fs/detail/PathWalk.cpp @@ -0,0 +1,378 @@ +// SPDX-License-Identifier: Apache-2.0 +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace core::fs::detail +{ + +namespace +{ + + std::unexpected refuse(FsErrorCode code) + { + return std::unexpected { FsError { .code = code, .systemCode = 0, .context = {} } }; + } + + /// The length of the well-formed UTF-8 sequence that starts @p text, or 0 where none does + /// (Unicode 15, table 3-7: no overlong form, no surrogate, nothing past U+10FFFF). + std::size_t sequenceLength(std::string_view text) noexcept + { + struct Lead + { + std::uint8_t first; ///< The lowest lead byte of the row. + std::uint8_t last; ///< The highest. + std::uint8_t secondMin; ///< The range the second byte must be in. + std::uint8_t secondMax; + std::uint8_t length; ///< Bytes in the sequence. + }; + static constexpr auto Leads = std::to_array({ + { .first = 0x00, .last = 0x7F, .secondMin = 0x00, .secondMax = 0x00, .length = 1 }, + { .first = 0xC2, .last = 0xDF, .secondMin = 0x80, .secondMax = 0xBF, .length = 2 }, + { .first = 0xE0, .last = 0xE0, .secondMin = 0xA0, .secondMax = 0xBF, .length = 3 }, + { .first = 0xE1, .last = 0xEC, .secondMin = 0x80, .secondMax = 0xBF, .length = 3 }, + { .first = 0xED, .last = 0xED, .secondMin = 0x80, .secondMax = 0x9F, .length = 3 }, + { .first = 0xEE, .last = 0xEF, .secondMin = 0x80, .secondMax = 0xBF, .length = 3 }, + { .first = 0xF0, .last = 0xF0, .secondMin = 0x90, .secondMax = 0xBF, .length = 4 }, + { .first = 0xF1, .last = 0xF3, .secondMin = 0x80, .secondMax = 0xBF, .length = 4 }, + { .first = 0xF4, .last = 0xF4, .secondMin = 0x80, .secondMax = 0x8F, .length = 4 }, + }); + auto const byteAt = [text](std::size_t index) { + return static_cast(text[index]); + }; + auto const lead = std::ranges::find_if( + Leads, [first = byteAt(0)](Lead const& row) { return row.first <= first && first <= row.last; }); + if (lead == Leads.end() || text.size() < lead->length) + return 0; + if (lead->length == 1) + return 1; + if (byteAt(1) < lead->secondMin || byteAt(1) > lead->secondMax) + return 0; + auto const rest = text.substr(2, lead->length - 2); + auto const continuation = [](char c) { + return (static_cast(c) & 0xC0U) == 0x80U; + }; + return std::ranges::all_of(rest, continuation) ? lead->length : 0; + } + + /// NUL is refused under every policy, and a name crosses the API as UTF-8. + FsResult checkText(std::string_view text) + { + if (text.contains('\0')) + return refuse(FsErrorCode::Invalid); + if (!isUtf8(text)) + return refuse(FsErrorCode::IllegalByteSequence); + return {}; + } + + std::vector splitOn(std::string_view text, std::string_view separators) + { + auto pieces = std::vector {}; + while (!text.empty()) + { + auto const end = text.find_first_of(separators); + auto const piece = text.substr(0, end); + if (!piece.empty()) + pieces.push_back(piece); + text.remove_prefix(end == std::string_view::npos ? text.size() : end + 1); + } + return pieces; + } + + bool equalsIgnoringAsciiCase(std::string_view a, std::string_view b) noexcept + { + auto const fold = [](char c) { + return c >= 'a' && c <= 'z' ? static_cast(c - 'a' + 'A') : c; + }; + return std::ranges::equal(a, b, {}, fold, fold); + } + + /// The part of @p name Windows compares against its device names: up to the first dot, trailing + /// spaces dropped, so `nul.txt` and `NUL ` are both the device. + std::string_view stemOf(std::string_view name) noexcept + { + auto stem = name.substr(0, name.find('.')); + while (stem.ends_with(' ')) + stem.remove_suffix(1); + return stem; + } + + FsResult checkComponent(std::string_view name, PathPolicy const& policy) + { + if (name == "." || name == "..") + return {}; + if (name.find_first_of(policy.forbiddenCharacters) != std::string_view::npos) + return refuse(FsErrorCode::Invalid); + if (policy.trailing == TrailingDotsAndSpaces::Refused && (name.ends_with('.') || name.ends_with(' '))) + return refuse(FsErrorCode::Invalid); + auto const stem = stemOf(name); + if (std::ranges::any_of(policy.reservedNames, [stem](std::string_view reserved) { + return equalsIgnoringAsciiCase(stem, reserved); + })) + return refuse(FsErrorCode::NotPermitted); + return {}; + } + + /// Which kind of text @c componentsOf splits. + enum class TextKind : std::uint8_t + { + Path, ///< A path argument, split on the policy's separators. + SymlinkTarget, ///< A link's target, split on its target separators; a volume is absolute. + }; + + /// The components of a path or a target, and whether its last one must be a directory. + struct Components + { + std::vector names; + FinalComponent finalComponent = FinalComponent::Any; + }; + + /// The components of @p text, with `.` dropped and every other one checked. A trailing separator + /// or a trailing `.` makes the last component one that must be a directory, as POSIX resolves + /// `name/` and `name/.`. A path argument keeps a trailing `.` as its last component: `name/.` + /// names the directory itself, not an entry of its parent, so an operation on that entry (rmdir, + /// mkdir) answers for the directory, as Linux does. A link's target drops it, since an operation + /// that follows a final link never acts on the entry. + FsResult componentsOf(std::string_view text, TextKind kind, PathPolicy const& policy) + { + auto const separators = kind == TextKind::Path ? policy.separators : policy.targetSeparators; + if (text.empty()) + return refuse(FsErrorCode::NoEntry); + if (auto checked = checkText(text); !checked) + return std::unexpected { std::move(checked.error()) }; + if (separators.contains(text.front())) + return refuse(FsErrorCode::NotPermitted); + auto const pieces = splitOn(text, separators); + if (kind == TextKind::SymlinkTarget && !pieces.empty() + && pieces.front().find_first_of(policy.volumeSeparators) != std::string_view::npos) + return refuse(FsErrorCode::NotPermitted); + auto components = Components {}; + if (separators.contains(text.back()) || (!pieces.empty() && pieces.back() == ".")) + components.finalComponent = FinalComponent::Directory; + for (auto const piece: pieces) + { + if (piece == ".") + continue; + if (auto checked = checkComponent(piece, policy); !checked) + return std::unexpected { std::move(checked.error()) }; + components.names.emplace_back(piece); + } + if (kind == TextKind::Path && !pieces.empty() && pieces.back() == ".") + components.names.emplace_back("."); + return components; + } + +} // namespace + +bool isUtf8(std::string_view text) noexcept +{ + while (!text.empty()) + { + auto const length = sequenceLength(text); + if (length == 0) + return false; + text.remove_prefix(length); + } + return true; +} + +FsResult planRelativePath(std::string_view path, PathPolicy const& policy) +{ + return componentsOf(path, TextKind::Path, policy).transform([](Components components) { + if (components.names.empty()) + components.names.emplace_back("."); + return PathPlan { .components = std::move(components.names), + .finalComponent = components.finalComponent }; + }); +} + +FsResult checkSymlinkTarget(std::string_view target, PathPolicy const& policy) +{ + return componentsOf(target, TextKind::SymlinkTarget, policy).transform([](Components const&) {}); +} + +FsResult spliceSymlink(PathPlan& plan, + std::size_t at, + std::string_view target, + PathPolicy const& policy) +{ + if (at >= plan.components.size()) + return refuse(FsErrorCode::Invalid); + return componentsOf(target, TextKind::SymlinkTarget, policy) + .transform([&plan, at](Components components) { + auto const isFinal = at + 1 == plan.components.size(); + auto const link = plan.components.begin() + static_cast(at); + auto const next = plan.components.erase(link); + plan.components.insert(next, + std::make_move_iterator(components.names.begin()), + std::make_move_iterator(components.names.end())); + if (isFinal && components.finalComponent == FinalComponent::Directory) + plan.finalComponent = FinalComponent::Directory; + }); +} + +namespace +{ + + /// @return Whether @p component would reach the kernel as more than one name. + FsResult checkKernelName(std::string_view component, WalkRules const& rules) + { + if (!rules.kernelSeparators.empty() + && component.find_first_of(rules.kernelSeparators) != std::string_view::npos) + return refuse(FsErrorCode::Invalid); + return {}; + } + + /// One walk: the plan as it is spliced, where it has got to, and how many links it followed. + class Walk + { + public: + Walk(IBeneathCursor& cursor, PathPlan plan, WalkRules const& rules): + _cursor { &cursor }, _plan { std::move(plan) }, _rules { rules } + { + } + + FsResult run() + { + while (_index < _plan.components.size()) + { + if (_index == 0 && _cursor->atRoot()) + if (auto taken = offerShortcut(); !taken) + return std::unexpected { std::move(taken.error()) }; + if (_index >= _plan.components.size()) + break; + auto name = _plan.components[_index]; + auto const isFinal = _index + 1 == _plan.components.size(); + if (name == ".") + { + ++_index; + continue; + } + if (name == "..") + { + if (_cursor->atRoot()) + return refuse(FsErrorCode::NotPermitted); + _cursor->leave(); + ++_index; + continue; + } + if (auto checked = checkKernelName(name, _rules); !checked) + return std::unexpected { std::move(checked.error()) }; + if (!isFinal) + { + auto const kind = _cursor->enter(name); + if (!kind) + return std::unexpected { kind.error() }; + if (*kind == EntryKind::SymbolicLink) + { + if (auto followed = follow(name); !followed) + return std::unexpected { std::move(followed.error()) }; + continue; + } + ++_index; + continue; + } + auto const kind = _cursor->inspect(name); + if (!kind) + return std::unexpected { kind.error() }; + auto const asksForDirectory = _plan.finalComponent == FinalComponent::Directory; + if (*kind == EntryKind::SymbolicLink) + { + if (asksForDirectory && _rules.finalPolicy == SymlinkPolicy::NoFollow + && _rules.onLink == TrailingSlashOnLink::Refuse) + return refuse(FsErrorCode::NotDirectory); + if (_rules.finalPolicy == SymlinkPolicy::Follow || asksForDirectory) + { + if (auto followed = follow(name); !followed) + return std::unexpected { std::move(followed.error()) }; + continue; + } + } + if (asksForDirectory && *kind != EntryKind::Missing && *kind != EntryKind::Directory) + return refuse(FsErrorCode::NotDirectory); + return WalkEnd { .name = std::move(name), + .kind = *kind, + .finalComponent = _plan.finalComponent }; + } + return WalkEnd { .name = {}, + .kind = EntryKind::Directory, + .finalComponent = FinalComponent::Directory }; + } + + private: + /// Lets the cursor resolve everything before the final name at once, or the whole path where + /// it ends in `.` or `..`. + FsResult offerShortcut() + { + auto const& components = _plan.components; + auto const last = components.back(); + auto const length = last == "." || last == ".." ? components.size() : components.size() - 1; + if (length == 0) + return {}; + auto const prefix = std::span { components.data(), length }; + for (auto const& component: prefix) + if (auto checked = checkKernelName(component, _rules); !checked) + return checked; + return _cursor->shortcut(prefix).transform([this, length](Shortcut taken) { + if (taken == Shortcut::Taken) + { + _index = length; + _shortcut = Shortcut::Taken; + } + }); + } + + /// Replaces the link at the current component with its target. A walk that stands where a + /// shortcut put it starts again from the root, since it holds no directory to climb back to. + FsResult follow(std::string const& name) + { + if (++_hops > _rules.maxSymlinkHops) + return refuse(FsErrorCode::Loop); + auto target = _cursor->readLink(name); + if (!target) + { + // No longer a link: it changed under the walk, which looks at it again. + if (target.error().code == FsErrorCode::Invalid) + return {}; + return std::unexpected { std::move(target.error()) }; + } + if (auto spliced = spliceSymlink(_plan, _index, *target, *_rules.policy); !spliced) + return spliced; + if (_shortcut == Shortcut::Taken) + { + _cursor->restart(); + _index = 0; + _shortcut = Shortcut::Declined; + } + return {}; + } + + IBeneathCursor* _cursor; + PathPlan _plan; + WalkRules _rules; + std::size_t _index = 0; + std::size_t _hops = 0; + Shortcut _shortcut = Shortcut::Declined; + }; + +} // namespace + +FsResult walkBeneath(IBeneathCursor& cursor, PathPlan plan, WalkRules const& rules) +{ + return Walk { cursor, std::move(plan), rules }.run(); +} + +} // namespace core::fs::detail diff --git a/src/core/fs/detail/PathWalk.hpp b/src/core/fs/detail/PathWalk.hpp new file mode 100644 index 00000000..3fe56917 --- /dev/null +++ b/src/core/fs/detail/PathWalk.hpp @@ -0,0 +1,194 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// What a relative path becomes before any directory is touched: its components, checked against a +/// @c PathPolicy, and the splice that replaces a symbolic link's component with its target; and the +/// one walk every resolver runs over them, one component at a time over held directories, so the +/// kernel never resolves more than one name. The walk owns the rules a resolver must not get +/// wrong on its own: `..` never climbs above the root, a final link is followed only where the call +/// or a trailing `/` says so, and a resolution follows at most @c WalkRules::maxSymlinkHops links. + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace core::fs::detail +{ + +/// What a path's last component must be. +enum class FinalComponent : std::uint8_t +{ + Any, ///< Whatever it names. + Directory, ///< A directory, followed through a symbolic link: the path ends in `/` or `/.`. +}; + +/// A relative path split into the components a walker resolves in order. +struct PathPlan +{ + /// The components: never empty, and never `.` but as the last one, where the path ends in `.` + /// (`.`, `a/.`): that names the directory itself rather than an entry of the one above it, so + /// removing it is `Invalid` and creating it `Exist`. `..` is kept, for the walker to resolve + /// against the directories it holds. + std::vector components; + /// What the last component must be. A walker follows a final symbolic link where it says + /// `Directory`, whatever the call's @c SymlinkPolicy, and answers `NotDirectory` for anything + /// else there; an operation that would create a non-directory there answers `NotDirectory`. + FinalComponent finalComponent = FinalComponent::Any; +}; + +/// @param text Bytes that should spell UTF-8. +/// @return Whether they do: no overlong form, no surrogate, nothing above U+10FFFF. +[[nodiscard]] bool isUtf8(std::string_view text) noexcept; + +/// Splits @p path into components under @p policy's rules. +/// @param path A relative path in UTF-8. +/// @param policy The name rules. +/// @return The plan; `NoEntry` for an empty path, `Invalid` for a NUL, a forbidden character or a +/// refused trailing dot or space, `IllegalByteSequence` where @p path is not UTF-8, and +/// `NotPermitted` for an absolute path or a reserved name. +[[nodiscard]] CORE_FS_API FsResult planRelativePath(std::string_view path, + PathPolicy const& policy); + +/// Checks a symbolic link's target before the link is created, as @c spliceSymlink would on +/// following it. +/// @param target The target, split on @p policy's target separators. +/// @param policy The name rules. +/// @return Nothing, or `NoEntry` for an empty target, `NotPermitted` for an absolute one (a leading +/// separator, or a first component naming a volume), and what @c planRelativePath answers for +/// a bad component. +[[nodiscard]] CORE_FS_API FsResult checkSymlinkTarget(std::string_view target, + PathPolicy const& policy); + +/// Replaces component @p at of @p plan, a symbolic link, with the components of its @p target, so +/// the walk goes on from the directory holding the link. A target ending in `/` or `/.` that +/// replaces the last component makes the plan's @c PathPlan::finalComponent `Directory`. +/// @param plan The plan being walked; left as it was where this fails. +/// @param at The index of the link's component. +/// @param target The link's target, split on @p policy's target separators. +/// @param policy The name rules. +/// @return Nothing, or why the target cannot be followed: `NoEntry` for an empty one, `NotPermitted` +/// for an absolute one, and what @c planRelativePath answers for a bad component; `Invalid` +/// where @p at is not a component of @p plan. +[[nodiscard]] CORE_FS_API FsResult spliceSymlink(PathPlan& plan, + std::size_t at, + std::string_view target, + PathPolicy const& policy); + +/// What a name in a directory is, as a walk sees it without following it. +enum class EntryKind : std::uint8_t +{ + Missing, ///< Nothing has the name. + Directory, ///< A directory. + SymbolicLink, ///< A symbolic link. + Other, ///< A regular file, a device, a FIFO or a socket. +}; + +/// What a trailing `/` does to a final symbolic link under `NoFollow`. A lookup follows it, as +/// POSIX resolves `dirlink/` to the directory; an operation that removes or moves the final entry +/// acts on the link itself, so Linux refuses `rmdir`, `rename` and `unlink` of `dirlink/` with +/// `ENOTDIR` rather than reaching through to the directory. +enum class TrailingSlashOnLink : std::uint8_t +{ + Follow, ///< Follow it (stat, open, set times, hash, and every call that creates an entry). + Refuse, ///< `NotDirectory` (remove, rename, unlink). +}; + +/// How one resolution treats what it meets. +struct WalkRules +{ + PathPolicy const* policy = nullptr; ///< How a link's target is split; never null. + SymlinkPolicy finalPolicy = SymlinkPolicy::NoFollow; ///< Whether a final link is followed. + TrailingSlashOnLink onLink = TrailingSlashOnLink::Follow; ///< A trailing `/` on a final link. + std::size_t maxSymlinkHops = DefaultMaxSymlinkHops; ///< Links followed before `Loop`. + /// What the kernel under the cursor would split a name on: a component holding one is + /// `Invalid`, so no policy can hand the kernel two names as one. Empty where nothing splits. + std::string_view kernelSeparators; +}; + +/// Whether a cursor took a shortcut it was offered. +enum class Shortcut : std::uint8_t +{ + Declined, ///< It did not; the walk goes on one component at a time. + Taken, ///< It stands on the directory the components name. +}; + +/// The directories a walk moves through, each held open (a handle, an inode), never named again by +/// a path, with one exception: a @c shortcut names the components before the final one as a path, +/// relative to the root, to a kernel that resolves it beneath the root itself and refuses whatever +/// would leave it (`openat2(RESOLVE_BENEATH)`). It starts on the root and keeps a stack of what it +/// entered. +class IBeneathCursor +{ + public: + IBeneathCursor() = default; + IBeneathCursor(IBeneathCursor const&) = delete; + IBeneathCursor(IBeneathCursor&&) = delete; + IBeneathCursor& operator=(IBeneathCursor const&) = delete; + IBeneathCursor& operator=(IBeneathCursor&&) = delete; + virtual ~IBeneathCursor() = default; + + /// @return Whether the cursor stands on the root, where `..` is refused. + [[nodiscard]] virtual bool atRoot() const noexcept = 0; + + /// Enters @p name of the current directory without following it. + /// @param name One component, neither `.` nor `..`. + /// @return `Directory` where it entered it, `SymbolicLink` where @p name is a link (not + /// entered); `NoEntry`, `NotDirectory` or what else refused it otherwise. + [[nodiscard]] virtual FsResult enter(std::string const& name) = 0; + + /// Goes back to the directory the current one was entered from. Not called on the root. + virtual void leave() = 0; + + /// @param name One component of the current directory, neither `.` nor `..`. + /// @return What it is, unfollowed; `Missing` where nothing has the name. + [[nodiscard]] virtual FsResult inspect(std::string const& name) = 0; + + /// @param name A symbolic link of the current directory. + /// @return Its target; `Invalid` where @p name is no longer a link, which the walk takes as a + /// change under it and looks again. + [[nodiscard]] virtual FsResult readLink(std::string const& name) = 0; + + /// Offers to move from the root to the directory @p components name in one step, as the kernel + /// can where it resolves beneath a directory itself (`openat2(RESOLVE_BENEATH)`). Only offered + /// on the root. + /// @param components Names and `..`, none holding a kernel separator. + /// @return Whether it took it; what refused the path otherwise (`NotPermitted` for one that + /// leaves the root). + [[nodiscard]] virtual FsResult shortcut(std::span components) = 0; + + /// Goes back to the root, dropping every directory entered. + virtual void restart() = 0; +}; + +/// Where a walk ended: the cursor stands on the directory that holds @c name. +struct WalkEnd +{ + std::string name; ///< The final name; empty where the path names that directory. + EntryKind kind = EntryKind::Missing; ///< What the name is, unfollowed. + FinalComponent finalComponent = FinalComponent::Any; ///< What the path asked it to be. +}; + +/// Walks @p plan beneath the cursor's root, following every link before the final component and +/// the final one where @p rules say so, splicing each with @c spliceSymlink. +/// @param cursor Where the walk moves; left on the directory holding the final name. +/// @param plan The planned path. +/// @param rules How links, `..` and the kernel's separators are treated. +/// @return Where it ended; `NotPermitted` where `..` would climb above the root or a link leaves +/// it, `Loop` past @c WalkRules::maxSymlinkHops, `NotDirectory` where the path ends in `/` +/// on something else (or on a link @c TrailingSlashOnLink::Refuse keeps), `Invalid` for a +/// name holding a kernel separator, and what the cursor answers. +[[nodiscard]] CORE_FS_API FsResult walkBeneath(IBeneathCursor& cursor, + PathPlan plan, + WalkRules const& rules); + +} // namespace core::fs::detail diff --git a/src/core/fs/detail/PathWalk_test.cpp b/src/core/fs/detail/PathWalk_test.cpp new file mode 100644 index 00000000..77bdd35c --- /dev/null +++ b/src/core/fs/detail/PathWalk_test.cpp @@ -0,0 +1,274 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The path planner both resolvers share: what a relative path becomes before any directory is +// touched, under each PathPolicy row. One table, run over both policies on every OS, because the +// in-memory model runs either and the native default is only one of them. +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +using core::fs::FsErrorCode; +using core::fs::PathPolicy; +using core::fs::posixPathPolicy; +using core::fs::windowsPathPolicy; +using core::fs::detail::checkSymlinkTarget; +using core::fs::detail::EntryKind; +using core::fs::detail::FinalComponent; +using core::fs::detail::planRelativePath; +using core::fs::detail::spliceSymlink; +using core::fs::detail::walkBeneath; +using core::fs::test::outcomeOf; + +namespace +{ + +/// What a path plans to: components, or the code it is refused with. +struct Expected +{ + std::vector components; + std::optional error; +}; + +Expected accepts(std::vector components) +{ + return Expected { .components = std::move(components), .error = std::nullopt }; +} + +Expected refuses(FsErrorCode code) +{ + return Expected { .components = {}, .error = code }; +} + +struct Row +{ + std::string_view path; + Expected posix; + Expected windows; +}; + +void checkPlan(std::string_view path, PathPolicy const& policy, Expected const& expected) +{ + CAPTURE(path); + auto const plan = planRelativePath(path, policy); + if (expected.error) + { + REQUIRE_FALSE(plan.has_value()); + CHECK(plan.error().code == *expected.error); + } + else + { + REQUIRE(plan.has_value()); + CHECK(plan->components == expected.components); + } +} + +} // namespace + +TEST_CASE("planRelativePath: each path under each policy", "[fs][pathwalk]") +{ + using enum FsErrorCode; + auto const row = GENERATE(Row { "/etc", refuses(NotPermitted), refuses(NotPermitted) }, + Row { "C:x", accepts({ "C:x" }), refuses(Invalid) }, + Row { "\\\\srv\\x", accepts({ "\\\\srv\\x" }), refuses(NotPermitted) }, + Row { "a:b", accepts({ "a:b" }), refuses(Invalid) }, + Row { "a\\b", accepts({ "a\\b" }), accepts({ "a", "b" }) }, + Row { std::string_view { "a\0b", 3 }, refuses(Invalid), refuses(Invalid) }, + Row { "a\xff", refuses(IllegalByteSequence), refuses(IllegalByteSequence) }, + Row { "\xc0\xaf", refuses(IllegalByteSequence), refuses(IllegalByteSequence) }, + Row { "a/./b//c", accepts({ "a", "b", "c" }), accepts({ "a", "b", "c" }) }, + Row { "a/../b", accepts({ "a", "..", "b" }), accepts({ "a", "..", "b" }) }, + Row { "", refuses(NoEntry), refuses(NoEntry) }, + Row { ".", accepts({ "." }), accepts({ "." }) }, + Row { "./.", accepts({ "." }), accepts({ "." }) }, + Row { "nul.txt", accepts({ "nul.txt" }), refuses(NotPermitted) }, + Row { "dir/CON", accepts({ "dir", "CON" }), refuses(NotPermitted) }, + Row { "COM\xc2\xb9", accepts({ "COM\xc2\xb9" }), refuses(NotPermitted) }, + Row { "CONIN$", accepts({ "CONIN$" }), refuses(NotPermitted) }, + Row { "console", accepts({ "console" }), accepts({ "console" }) }, + Row { "x.", accepts({ "x." }), refuses(Invalid) }, + Row { "x ", accepts({ "x " }), refuses(Invalid) }, + Row { "a|b", accepts({ "a|b" }), refuses(Invalid) }, + Row { "caf\xc3\xa9", accepts({ "caf\xc3\xa9" }), accepts({ "caf\xc3\xa9" }) }); + + SECTION("posix") + { + checkPlan(row.path, posixPathPolicy(), row.posix); + } + SECTION("windows") + { + checkPlan(row.path, windowsPathPolicy(), row.windows); + } +} + +TEST_CASE("spliceSymlink: a target replaces the link's component", "[fs][pathwalk]") +{ + auto plan = planRelativePath("a/link/c", posixPathPolicy()); + REQUIRE(plan.has_value()); + REQUIRE(spliceSymlink(*plan, 1, "x/../y", posixPathPolicy()).has_value()); + CHECK(plan->components == std::vector { "a", "x", "..", "y", "c" }); +} + +TEST_CASE("spliceSymlink: a target is split on the policy's target separators", "[fs][pathwalk]") +{ + SECTION("posix keeps a backslash in the name") + { + auto plan = planRelativePath("link", posixPathPolicy()); + REQUIRE(plan.has_value()); + REQUIRE(spliceSymlink(*plan, 0, "..\\x", posixPathPolicy()).has_value()); + CHECK(plan->components == std::vector { "..\\x" }); + } + SECTION("windows splits on it") + { + auto plan = planRelativePath("link", windowsPathPolicy()); + REQUIRE(plan.has_value()); + REQUIRE(spliceSymlink(*plan, 0, "..\\x", windowsPathPolicy()).has_value()); + CHECK(plan->components == std::vector { "..", "x" }); + } +} + +TEST_CASE("spliceSymlink: absolute and empty targets are refused", "[fs][pathwalk]") +{ + auto const& policy = GENERATE(std::cref(posixPathPolicy()), std::cref(windowsPathPolicy())); + auto plan = planRelativePath("link", policy); + REQUIRE(plan.has_value()); + auto const before = plan->components; + CHECK(outcomeOf(spliceSymlink(*plan, 0, "/etc/passwd", policy)) == FsErrorCode::NotPermitted); + CHECK(outcomeOf(spliceSymlink(*plan, 0, "", policy)) == FsErrorCode::NoEntry); + CHECK(plan->components == before); +} + +TEST_CASE("spliceSymlink: a target of the directory itself leaves the rest", "[fs][pathwalk]") +{ + auto plan = planRelativePath("a/link/b", posixPathPolicy()); + REQUIRE(plan.has_value()); + REQUIRE(spliceSymlink(*plan, 1, ".", posixPathPolicy()).has_value()); + CHECK(plan->components == std::vector { "a", "b" }); +} + +TEST_CASE("planRelativePath: a trailing separator or dot asks for a directory", "[fs][pathwalk]") +{ + auto const& policy = GENERATE(std::cref(posixPathPolicy()), std::cref(windowsPathPolicy())); + struct Case + { + std::string_view path; + std::vector components; + FinalComponent finalComponent; + }; + auto const testCase = GENERATE(Case { "a", { "a" }, FinalComponent::Any }, + Case { "a/", { "a" }, FinalComponent::Directory }, + Case { "a//", { "a" }, FinalComponent::Directory }, + Case { "a/.", { "a", "." }, FinalComponent::Directory }, + Case { "a/./", { "a", "." }, FinalComponent::Directory }, + Case { "a/./.", { "a", "." }, FinalComponent::Directory }, + Case { "a/b/..", { "a", "b", ".." }, FinalComponent::Any }, + Case { "a/./b", { "a", "b" }, FinalComponent::Any }); + CAPTURE(testCase.path); + auto const plan = planRelativePath(testCase.path, policy); + REQUIRE(plan.has_value()); + CHECK(plan->components == testCase.components); + CHECK(plan->finalComponent == testCase.finalComponent); +} + +TEST_CASE("spliceSymlink: a final link whose target ends in a separator asks for a directory", + "[fs][pathwalk]") +{ + auto plan = planRelativePath("a/link", posixPathPolicy()); + REQUIRE(plan.has_value()); + REQUIRE(spliceSymlink(*plan, 1, "d/", posixPathPolicy()).has_value()); + CHECK(plan->finalComponent == FinalComponent::Directory); + + auto inner = planRelativePath("link/b", posixPathPolicy()); + REQUIRE(inner.has_value()); + REQUIRE(spliceSymlink(*inner, 0, "d/", posixPathPolicy()).has_value()); + CHECK(inner->finalComponent == FinalComponent::Any); +} + +TEST_CASE("checkSymlinkTarget: what a link may not hold", "[fs][pathwalk]") +{ + using enum FsErrorCode; + CHECK(outcomeOf(checkSymlinkTarget("", posixPathPolicy())) == NoEntry); + CHECK(outcomeOf(checkSymlinkTarget(std::string_view { "a\0b", 3 }, posixPathPolicy())) == Invalid); + CHECK(outcomeOf(checkSymlinkTarget("/etc", posixPathPolicy())) == NotPermitted); + CHECK(checkSymlinkTarget("../x", posixPathPolicy()).has_value()); + CHECK(checkSymlinkTarget("C:x", posixPathPolicy()).has_value()); + CHECK(outcomeOf(checkSymlinkTarget("C:x", windowsPathPolicy())) == NotPermitted); + CHECK(outcomeOf(checkSymlinkTarget("C:\\x", windowsPathPolicy())) == NotPermitted); + CHECK(outcomeOf(checkSymlinkTarget("\\\\srv\\x", windowsPathPolicy())) == NotPermitted); + CHECK(outcomeOf(checkSymlinkTarget("a/b:c", windowsPathPolicy())) == Invalid); +} + +namespace +{ + +/// A cursor over one directory where every name is a link to itself, counting what it is asked: +/// whatever the walk enforces, it enforces without the cursor's help. +class SelfLinkCursor final: public core::fs::detail::IBeneathCursor +{ + public: + [[nodiscard]] bool atRoot() const noexcept override { return true; } + [[nodiscard]] core::fs::FsResult enter(std::string const&) override + { + return EntryKind::SymbolicLink; + } + void leave() override { ++leaves; } + [[nodiscard]] core::fs::FsResult inspect(std::string const&) override + { + return EntryKind::SymbolicLink; + } + [[nodiscard]] core::fs::FsResult readLink(std::string const& name) override + { + ++reads; + return name; + } + [[nodiscard]] core::fs::FsResult shortcut( + std::span) override + { + return core::fs::detail::Shortcut::Declined; + } + void restart() override {} + + std::size_t reads = 0; + std::size_t leaves = 0; +}; + +core::fs::detail::WalkRules followingRules(std::size_t maxSymlinkHops) +{ + return core::fs::detail::WalkRules { .policy = &posixPathPolicy(), + .finalPolicy = core::fs::SymlinkPolicy::Follow, + .onLink = core::fs::detail::TrailingSlashOnLink::Follow, + .maxSymlinkHops = maxSymlinkHops, + .kernelSeparators = "/" }; +} + +} // namespace + +TEST_CASE("walkBeneath: the walk owns the hop limit and `..` at the root", "[fs][walk]") +{ + auto const hops = GENERATE(std::size_t { 0 }, std::size_t { 3 }, core::fs::DefaultMaxSymlinkHops); + CAPTURE(hops); + auto cursor = SelfLinkCursor {}; + auto const looped = + walkBeneath(cursor, planRelativePath("a/b", posixPathPolicy()).value(), followingRules(hops)); + REQUIRE_FALSE(looped.has_value()); + CHECK(looped.error().code == FsErrorCode::Loop); + CHECK(cursor.reads == hops); + + auto const climbed = + walkBeneath(cursor, planRelativePath("../x", posixPathPolicy()).value(), followingRules(hops)); + REQUIRE_FALSE(climbed.has_value()); + CHECK(climbed.error().code == FsErrorCode::NotPermitted); + CHECK(cursor.leaves == 0); +} diff --git a/src/core/fs/detail/ResolveBeneath.hpp b/src/core/fs/detail/ResolveBeneath.hpp new file mode 100644 index 00000000..bb5e7e97 --- /dev/null +++ b/src/core/fs/detail/ResolveBeneath.hpp @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// How a native descriptor resolves a path beneath itself: the @c walkBeneath walk over directory +/// handles it holds, with the one step a kernel may take for it (`openat2(RESOLVE_BENEATH)` on +/// Linux) behind @c IBeneathOpener. Which opener `BeneathStrategy::Best` stands for is decided by +/// the one `BeneathDefault.cpp` the build compiles. Private to the fs module. + +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace core::fs::detail +{ + +/// Opens a directory several components beneath a held one in a single call, refusing whatever +/// would leave it, where the kernel can be asked to. +class IBeneathOpener +{ + public: + IBeneathOpener() = default; + IBeneathOpener(IBeneathOpener const&) = delete; + IBeneathOpener(IBeneathOpener&&) = delete; + IBeneathOpener& operator=(IBeneathOpener const&) = delete; + IBeneathOpener& operator=(IBeneathOpener&&) = delete; + virtual ~IBeneathOpener() = default; + + /// @param root The directory @p path is relative to. + /// @param path Components joined by `/`: names and `..`, no final name to act on. + /// @return The directory, held; one holding no handle where the call declines and the caller + /// should walk instead; `NotPermitted` where @p path leaves @p root, and what else + /// refused it. + [[nodiscard]] virtual FsResult openDirectoryBeneath(platform::NativeHandle root, + std::string const& path) const = 0; +}; + +/// What `BeneathStrategy::Best` stands for on this system, decided once, when a file system is +/// built: the `openat2` opener where Linux has the call, and none (the walk alone) elsewhere. +/// Defined by the `BeneathDefault.cpp` the build compiles. +/// @return The opener, or null. +[[nodiscard]] std::unique_ptr makeBestBeneathOpener(); + +/// Where a path resolved to. +struct Resolved +{ + UniqueHandle held; ///< The directory, where the walk left the root. + platform::NativeHandle root = platform::InvalidHandle; ///< The root it started from, borrowed. + std::string name; ///< The final name; empty for the directory itself. + EntryKind kind = EntryKind::Missing; ///< What the name is, unfollowed. + FinalComponent finalComponent = FinalComponent::Any; ///< What the path asked it to be. + + /// @return The directory that holds @c name: @c held, or the root. + [[nodiscard]] platform::NativeHandle directory() const noexcept + { + return held.get() != platform::InvalidHandle ? held.get() : root; + } +}; + +/// Resolves @p plan beneath @p root. The final name is never resolved: it is acted on, by the +/// caller, without following, in @c Resolved::directory. +/// @param root The descriptor's directory handle; borrowed for the call. +/// @param plan The planned path. +/// @param rules How links, `..` and the kernel's separators are treated. +/// @param opener The kernel's beneath step, or null to walk one component at a time. +/// @return Where it resolved to, or what @c walkBeneath answers. +[[nodiscard]] CORE_FS_API FsResult resolveBeneath(platform::NativeHandle root, + PathPlan plan, + WalkRules const& rules, + IBeneathOpener const* opener); + +} // namespace core::fs::detail diff --git a/src/core/fs/linux/Append.cpp b/src/core/fs/linux/Append.cpp new file mode 100644 index 00000000..478a9c41 --- /dev/null +++ b/src/core/fs/linux/Append.cpp @@ -0,0 +1,111 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// Appending on Linux: `pwritev2` with `RWF_APPEND` (Linux 4.16) appends through the descriptor's own +// handle, which stays without `O_APPEND`, so its positioned writes still land where they are aimed. +// Where the kernel or a seccomp filter refuses the flag, the append writes at the end `fstat` +// reports, through the same handle, under the descriptor's append lock: no reopen, which would +// need write permission granted again (a 0444 file, a chmod after open) and would drop the +// handle's O_SYNC/O_DSYNC. +#include + +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace core::fs::detail +{ + +namespace +{ + + /// The errnos that say `RWF_APPEND` itself is what was refused. + constexpr auto FlagRefusedErrnos = std::to_array({ EOPNOTSUPP, EINVAL, ENOSYS, EPERM }); + + bool flagRefused(int error) noexcept + { + return std::ranges::find(FlagRefusedErrnos, error) != FlagRefusedErrnos.end(); + } + + /// Writes @p bytes through @p handle, one call at a time, until all are written or one fails. + template + FsResult writeAll(std::span bytes, Write write, char const* call) + { + auto written = std::size_t { 0 }; + while (written < bytes.size()) + { + auto const count = retryOnInterrupt([&] { return write(bytes.subspan(written)); }); + if (count < 0) + { + if (written > 0) + break; + return errnoError(call); + } + if (count == 0) + break; + written += static_cast(count); + } + return written; + } + +} // namespace + +FsResult openAppendHandle(int, std::string const&, int, int) +{ + return UniqueHandle { platform::InvalidHandle }; +} + +FsResult appendAtEnd(int handle, std::mutex& appendLock, std::span bytes) +{ + auto const lock = std::scoped_lock { appendLock }; + struct ::stat status {}; + if (::fstat(handle, &status) != 0) + return errnoError("fstat"); + auto const end = static_cast(status.st_size); + if (bytes.size() > static_cast(std::numeric_limits::max()) - end) + return std::unexpected { FsError { + .code = FsErrorCode::FileTooLarge, .systemCode = 0, .context = {} } }; + return writeAll( + bytes, + [&](std::span rest) { + auto const done = static_cast(rest.data() - bytes.data()); + return ::pwrite(handle, rest.data(), rest.size(), static_cast(end + done)); + }, + "pwrite(end)"); +} + +FsResult appendBytes(int handle, + OwnedHandle const*, + std::mutex& appendLock, + std::span bytes) +{ + auto const appended = writeAll( + bytes, + [&](std::span rest) { + auto vector = ::iovec { .iov_base = const_cast(rest.data()), .iov_len = rest.size() }; + // With RWF_APPEND the offset does not place the write; 0 leaves the handle's own offset alone. + return ::pwritev2(handle, &vector, 1, 0, RWF_APPEND); + }, + "pwritev2(RWF_APPEND)"); + if (!appended && flagRefused(static_cast(appended.error().systemCode))) + return appendAtEnd(handle, appendLock, bytes); + return appended; +} + +} // namespace core::fs::detail diff --git a/src/core/fs/linux/Append.hpp b/src/core/fs/linux/Append.hpp new file mode 100644 index 00000000..42a0ccf3 --- /dev/null +++ b/src/core/fs/linux/Append.hpp @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// Linux's append where `RWF_APPEND` is refused. Private to the fs module. + +#include +#include + +#include +#include +#include + +namespace core::fs::detail +{ + +/// Writes @p bytes at the end of the file, found with `fstat`, through the descriptor's own +/// handle: no new open, so the handle's write integrity (`O_SYNC`, `O_DSYNC`) and the access it +/// was opened with hold, whatever the file's mode now says. @p appendLock serialises this +/// descriptor's appends, so two of them never find the same end. Any other writer can still land +/// between the `fstat` and the write: another process, and another descriptor on the same file in +/// this one, which holds a lock of its own. An `O_APPEND` handle would rule that out. +/// @param handle The descriptor's handle, open for writing. +/// @param appendLock The descriptor's append lock. +/// @param bytes What to write. +/// @return How many bytes were written. +[[nodiscard]] CORE_FS_API FsResult appendAtEnd(int handle, + std::mutex& appendLock, + std::span bytes); + +} // namespace core::fs::detail diff --git a/src/core/fs/linux/Append_test.cpp b/src/core/fs/linux/Append_test.cpp new file mode 100644 index 00000000..96d73fb3 --- /dev/null +++ b/src/core/fs/linux/Append_test.cpp @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// Linux's append where RWF_APPEND is refused: it writes at the end through the descriptor's own +// handle, so a file that is read-only by now (chmod after open) still takes the append, and the +// handle's integrity flags stay what they were. +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace +{ + +std::span bytesOf(std::string const& text) +{ + return std::as_bytes(std::span { text }); +} + +} // namespace + +TEST_CASE("linux append: without RWF_APPEND, the end is written through the handle itself", "[fs][native]") +{ + auto const directory = core::testing::ScopedTempDir { "core-cpp-fs-append" }; + auto const path = directory.path() / "f"; + auto const file = core::fs::detail::UniqueHandle { ::open( + path.c_str(), O_RDWR | O_CREAT | O_EXCL | O_DSYNC | O_CLOEXEC, 0644) }; + REQUIRE(file.get() >= 0); + REQUIRE(::write(file.get(), "abc", 3) == 3); + // Read-only from here on: a reopen for writing would be refused. + std::filesystem::permissions(path, + std::filesystem::perms::owner_read | std::filesystem::perms::group_read + | std::filesystem::perms::others_read); + auto lock = std::mutex {}; + + auto const first = std::string { "de" }; + auto const second = std::string { "f!" }; + CHECK(core::fs::detail::appendAtEnd(file.get(), lock, bytesOf(first)) == 2U); + CHECK(core::fs::detail::appendAtEnd(file.get(), lock, bytesOf(second)) == 2U); + + auto text = std::array {}; + auto const length = ::pread(file.get(), text.data(), text.size(), 0); + CHECK(std::string(text.data(), static_cast(length)) == "abcdef!"); + CHECK((::fcntl(file.get(), F_GETFL) & O_DSYNC) == O_DSYNC); +} diff --git a/src/core/fs/linux/BeneathDefault.cpp b/src/core/fs/linux/BeneathDefault.cpp new file mode 100644 index 00000000..e5540a5e --- /dev/null +++ b/src/core/fs/linux/BeneathDefault.cpp @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// What BeneathStrategy::Best is on Linux: openat2(RESOLVE_BENEATH) where the kernel has it, probed +// once per file system, and the walk where it does not. The walk opens each directory as a path +// handle (O_PATH), so a directory the process may search but not read is walked through. CMake +// compiles exactly one BeneathDefault.cpp, so no `#ifdef` chooses either. +#include +#include +#include + +#include + +#include + +namespace core::fs::detail +{ + +namespace +{ + + constexpr int WalkDirectoryOpenFlags = O_PATH | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC; + +} // namespace + +std::unique_ptr makeBestBeneathOpener() +{ + return makeOpenat2Opener(systemOpenat2()); +} + +int walkDirectoryOpenFlags() noexcept +{ + return WalkDirectoryOpenFlags; +} + +} // namespace core::fs::detail diff --git a/src/core/fs/linux/DescriptorEscape_test.cpp b/src/core/fs/linux/DescriptorEscape_test.cpp new file mode 100644 index 00000000..1a4a17bc --- /dev/null +++ b/src/core/fs/linux/DescriptorEscape_test.cpp @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// Linux's magic links: /proc/self/cwd, /proc/self/root and /proc/self/fd/N name objects anywhere, +// whatever their text says. Beneath a preopen of /proc/self no path may go through one: openat2 +// refuses them (RESOLVE_NO_MAGICLINKS, Loop), the walk reads their absolute text (NotPermitted). +#include +#include +#include +#include +#include + +#include +#include + +#include +#include + +#include + +using core::fs::BeneathStrategy; +using core::fs::DescriptorFlags; +using core::fs::FsErrorCode; +using core::fs::OpenFlags; +using core::fs::SymlinkPolicy; +using core::fs::test::DescriptorFixture; +using core::fs::test::Outcome; +using core::fs::test::outcomeOf; + +TEST_CASE("no path goes through a magic link of /proc", "[fs][escape]") +{ + auto const strategy = GENERATE(BeneathStrategy::Best, BeneathStrategy::ComponentWalk); + CAPTURE(strategy == BeneathStrategy::Best ? "Best" : "ComponentWalk"); + auto fixture = DescriptorFixture::createNative({ .strategy = strategy }); + auto proc = fixture.run( + fixture.fileSystem().openPreopen(std::filesystem::path { "/proc/self" }, DescriptorFlags::Read)); + if (!proc) + SKIP("/proc/self is not mounted here"); + auto& self = **proc; + auto const refused = [](Outcome const& outcome) { + return outcome == FsErrorCode::NotPermitted || outcome == FsErrorCode::Loop; + }; + + // A descriptor this process surely has, open on the file system's root: a magic link that, + // followed, would reach every directory there is. + auto const slash = core::fs::detail::UniqueHandle { ::open("/", O_RDONLY | O_DIRECTORY | O_CLOEXEC) }; + REQUIRE(slash.get() >= 0); + auto const throughDescriptor = "fd/" + std::to_string(slash.get()) + "/etc"; + + for (auto const& path: + { std::string { "cwd/." }, std::string { "root/etc" }, throughDescriptor, std::string { "cwd/" } }) + { + CAPTURE(path); + CHECK(refused(outcomeOf(fixture.run(self.statAt(SymlinkPolicy::NoFollow, path))))); + CHECK(refused(outcomeOf(fixture.run( + self.openAt(SymlinkPolicy::NoFollow, path, OpenFlags::None, DescriptorFlags::Read))))); + } + for (auto const* path: { "cwd", "root", "exe" }) + { + CAPTURE(path); + CHECK(refused(outcomeOf(fixture.run(self.statAt(SymlinkPolicy::Follow, path))))); + CHECK(fixture.run(self.statAt(SymlinkPolicy::NoFollow, path)).has_value()); + } +} diff --git a/src/core/fs/linux/DirectoryRead.cpp b/src/core/fs/linux/DirectoryRead.cpp new file mode 100644 index 00000000..c2439bff --- /dev/null +++ b/src/core/fs/linux/DirectoryRead.cpp @@ -0,0 +1,118 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// A directory stream's reads on Linux: getdents64 into one fixed buffer per stream, each record read +// field by field within what the call returned. No DIR, so no readdir and its shared entry buffer. +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace core::fs::detail +{ + +/// The stream's own handle on the directory, which keeps its position, and the buffer its records +/// are read into; a batch holds @c lock while it reads. +struct DirectoryReader +{ + SharedHandle handle; ///< Opened for the stream alone. + std::mutex lock; ///< Held by the batch that reads. + std::vector records; ///< @c DirectoryBufferBytes, 8-byte aligned. + + explicit DirectoryReader(SharedHandle directory): + handle { std::move(directory) }, records(DirectoryBufferBytes / sizeof(std::uint64_t)) + { + } +}; + +namespace +{ + + /// Where each field of a `dirent64` is, in bytes from the start of its record. + constexpr std::size_t LengthOffset = offsetof(struct ::dirent64, d_reclen); + constexpr std::size_t TypeOffset = offsetof(struct ::dirent64, d_type); + constexpr std::size_t NameOffset = offsetof(struct ::dirent64, d_name); + + std::unexpected invalid() + { + return std::unexpected { FsError { .code = FsErrorCode::Invalid, + .systemCode = 0, + .context = "getdents64 record beyond its buffer" } }; + } + +} // namespace + +FsResult parseDirentRecords(int directory, std::span bytes, DirectoryBatch& batch) +{ + auto offset = std::size_t { 0 }; + while (offset < bytes.size()) + { + auto const record = bytes.subspan(offset); + if (record.size() <= NameOffset) + return invalid(); + auto length = std::uint16_t {}; + std::memcpy(&length, record.data() + LengthOffset, sizeof(length)); + if (length <= NameOffset || length > record.size()) + return invalid(); + auto const name = record.subspan(NameOffset, length - NameOffset); + auto const end = std::ranges::find(name, std::byte { 0 }); + if (end == name.end()) + return invalid(); + auto text = std::string(static_cast(end - name.begin()), '\0'); + std::memcpy(text.data(), name.data(), text.size()); + if (auto entry = entryOf(directory, text.c_str(), std::to_integer(record[TypeOffset]))) + batch.entries.push_back(std::move(*entry)); + offset += length; + } + return {}; +} + +FsResult> openDirectoryReader(int directory, async::IExecutor& closer) +{ + auto const opened = + retryOnInterrupt([&] { return ::openat(directory, ".", O_RDONLY | O_DIRECTORY | O_CLOEXEC); }); + if (opened < 0) + return errnoError("openat"); + return std::make_shared(shareHandle(UniqueHandle { opened }, closer)); +} + +FsResult readDirectoryBatch(DirectoryReader& reader) +{ + auto const held = std::scoped_lock { reader.lock }; + auto const buffer = std::as_writable_bytes(std::span { reader.records }); + auto const count = + retryOnInterrupt([&] { return ::getdents64(reader.handle->get(), buffer.data(), buffer.size()); }); + auto batch = DirectoryBatch {}; + // A directory removed while it is read has nothing more (ENOENT), as readdir says too. + if (count == 0 || (count < 0 && errno == ENOENT)) + { + batch.end = StreamEnd::Reached; + return batch; + } + if (count < 0) + return errnoError("getdents64"); + return parseDirentRecords(reader.handle->get(), buffer.first(static_cast(count)), batch) + .transform([&] { return std::move(batch); }); +} + +} // namespace core::fs::detail diff --git a/src/core/fs/linux/DirectoryRead.hpp b/src/core/fs/linux/DirectoryRead.hpp new file mode 100644 index 00000000..c02da6ef --- /dev/null +++ b/src/core/fs/linux/DirectoryRead.hpp @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// The records Linux's `getdents64` writes, read field by field within the bytes it returned, so a +/// record that claims more than is there is refused rather than read past. Private to the fs module. + +#include +#include +#include + +#include +#include + +namespace core::fs::detail +{ + +/// Reads the `dirent64` records of @p bytes onto @p batch, through @c entryOf. +/// @param directory The directory they were read from, which an entry of unknown type is stat'ed in. +/// @param bytes What one `getdents64` call returned. +/// @param batch Where the entries go. +/// @return Nothing; `Invalid` where a record is shorter than its header, its length (`d_reclen`) is +/// no longer than the header or runs past @p bytes, or its name has no NUL within it. +[[nodiscard]] CORE_FS_API FsResult parseDirentRecords(int directory, + std::span bytes, + DirectoryBatch& batch); + +} // namespace core::fs::detail diff --git a/src/core/fs/linux/DirectoryRead_test.cpp b/src/core/fs/linux/DirectoryRead_test.cpp new file mode 100644 index 00000000..37b1ab72 --- /dev/null +++ b/src/core/fs/linux/DirectoryRead_test.cpp @@ -0,0 +1,129 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The records getdents64 writes, built by hand: read one after the other, `.` and `..` skipped, and +// a record that claims more than the bytes returned hold refused as a whole rather than read past. +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +#include + +using core::fs::DescriptorType; +using core::fs::FsErrorCode; +using core::fs::detail::DirectoryBatch; +using core::fs::detail::parseDirentRecords; +using core::fs::test::outcomeOf; + +namespace +{ + +constexpr auto LengthOffset = offsetof(struct ::dirent64, d_reclen); +constexpr auto TypeOffset = offsetof(struct ::dirent64, d_type); +constexpr auto NameOffset = offsetof(struct ::dirent64, d_name); + +struct Record +{ + std::string name; + unsigned char type = DT_REG; +}; + +/// @return @p records as the kernel writes them: each NUL-terminated name padded to 8 bytes. +std::vector encode(std::vector const& records) +{ + auto bytes = std::vector {}; + for (auto const& record: records) + { + auto const start = bytes.size(); + auto const length = (NameOffset + record.name.size() + 1 + 7) / 8 * 8; + bytes.resize(start + length); + auto const reclen = static_cast(length); + std::memcpy(bytes.data() + start + LengthOffset, &reclen, sizeof(reclen)); + bytes[start + TypeOffset] = std::byte { record.type }; + std::memcpy(bytes.data() + start + NameOffset, record.name.data(), record.name.size()); + } + return bytes; +} + +void setLength(std::vector& bytes, std::size_t record, std::uint16_t length) +{ + std::memcpy(bytes.data() + record + LengthOffset, &length, sizeof(length)); +} + +} // namespace + +TEST_CASE("linux records: each record is read once, without . and ..", "[fs][native][directory]") +{ + auto const bytes = + encode({ { ".", DT_DIR }, { "..", DT_DIR }, { "file" }, { "dir", DT_DIR }, { "link", DT_LNK } }); + auto batch = DirectoryBatch {}; + REQUIRE(parseDirentRecords(-1, bytes, batch).has_value()); + auto seen = std::vector> {}; + for (auto const& entry: batch.entries) + { + REQUIRE(entry.has_value()); + seen.emplace_back(entry->name, entry->type); + } + CHECK( + seen + == std::vector> { { "file", DescriptorType::RegularFile }, + { "dir", DescriptorType::Directory }, + { "link", DescriptorType::SymbolicLink } }); +} + +TEST_CASE("linux records: a record beyond what was returned is Invalid", "[fs][native][directory]") +{ + auto const whole = encode({ { "first" }, { "second" } }); + auto const second = static_cast(whole.size() / 2); + REQUIRE(second * 2 == whole.size()); // both names pad to one record size + auto batch = DirectoryBatch {}; + + SECTION("a zero length, which would never move on") + { + auto bytes = whole; + setLength(bytes, 0, 0); + CHECK(outcomeOf(parseDirentRecords(-1, bytes, batch)) == FsErrorCode::Invalid); + } + SECTION("a length no longer than the header") + { + auto bytes = whole; + setLength(bytes, 0, static_cast(NameOffset)); + CHECK(outcomeOf(parseDirentRecords(-1, bytes, batch)) == FsErrorCode::Invalid); + } + SECTION("a length past the bytes returned") + { + auto bytes = whole; + setLength(bytes, second, static_cast(second + 8)); + CHECK(outcomeOf(parseDirentRecords(-1, bytes, batch)) == FsErrorCode::Invalid); + } + SECTION("a name without its NUL") + { + auto bytes = whole; + std::memset(bytes.data() + NameOffset, 'x', second - NameOffset); + CHECK(outcomeOf(parseDirentRecords(-1, bytes, batch)) == FsErrorCode::Invalid); + } + SECTION("a header cut short") + { + auto bytes = whole; + bytes.resize(second + NameOffset - 1); + CHECK(outcomeOf(parseDirentRecords(-1, bytes, batch)) == FsErrorCode::Invalid); + } + SECTION("nothing returned is no record") + { + CHECK(parseDirentRecords(-1, {}, batch).has_value()); + CHECK(batch.entries.empty()); + } + auto intact = DirectoryBatch {}; + CHECK(parseDirentRecords(-1, whole, intact).has_value()); + CHECK(intact.entries.size() == 2); +} diff --git a/src/core/fs/linux/Lease.cpp b/src/core/fs/linux/Lease.cpp new file mode 100644 index 00000000..67803c80 --- /dev/null +++ b/src/core/fs/linux/Lease.cpp @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// Waiting for a lease on Linux. An O_NONBLOCK open of a regular file under a lease answers +// EWOULDBLOCK instead of breaking the lease; the open is made again, waiting, but never by the name: +// the name is opened as a path handle (O_PATH opens nothing and breaks no lease), checked by that +// handle to be a regular file, and reopened through /proc/self/fd, which names that very inode. A +// FIFO renamed over the name in between is seen by the check and never opened blocking. +#include +#include +#include + +#include + +#include +#include +#include + +#include + +namespace core::fs::detail +{ + +FsResult openAfterWouldBlock(int directory, std::string const& name, int flags) +{ + auto const wouldBlock = [](char const* why) { + return std::unexpected { FsError { + .code = FsErrorCode::WouldBlock, .systemCode = EWOULDBLOCK, .context = why } }; + }; + auto const path = UniqueHandle { retryOnInterrupt( + [&] { return ::openat(directory, name.c_str(), O_PATH | O_NOFOLLOW | O_CLOEXEC); }) }; + if (path.get() < 0) + return errnoError("openat(O_PATH)"); + struct ::stat status {}; + if (::fstat(path.get(), &status) != 0) + return errnoError("fstat"); + if (!S_ISREG(status.st_mode)) + return wouldBlock("the name no longer names a regular file"); + // The magic link resolves to the inode itself, so O_NOFOLLOW (which would refuse the link) and + // the creating flags (it exists) are dropped. + auto const reopen = "/proc/self/fd/" + std::to_string(path.get()); + auto const opened = retryOnInterrupt( + [&] { return ::open(reopen.c_str(), flags & ~(O_NOFOLLOW | O_CREAT | O_EXCL | O_NONBLOCK)); }); + if (opened < 0) + { + if (errno == ENOENT) + return wouldBlock("no /proc to wait for the lease through"); + return errnoError("open(/proc/self/fd)"); + } + return UniqueHandle { opened }; +} + +} // namespace core::fs::detail diff --git a/src/core/fs/linux/Lease_test.cpp b/src/core/fs/linux/Lease_test.cpp new file mode 100644 index 00000000..937694de --- /dev/null +++ b/src/core/fs/linux/Lease_test.cpp @@ -0,0 +1,101 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The open made again after a lease answered EWOULDBLOCK: it opens only a regular file blocking. A +// FIFO renamed over the name between the non-blocking open and this one is what the case below +// stands for, deterministically: the name is a FIFO when the retry looks, and the retry answers +// WouldBlock at once rather than waiting for a writer that never comes. Then the whole way, through +// openAt: a real lease the open must wait for, released by a thread that sees it being broken. +#include +#include +#include +#include +#include +#include + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +using core::fs::DescriptorFlags; +using core::fs::FsErrorCode; +using core::fs::OpenFlags; +using core::fs::SymlinkPolicy; +using core::fs::detail::openAfterWouldBlock; +using core::fs::detail::UniqueHandle; +using core::fs::test::DescriptorFixture; + +TEST_CASE("lease retry: only a regular file is opened again, waiting", "[fs][native]") +{ + auto const directory = core::testing::ScopedTempDir { "core-cpp-fs-lease" }; + { + auto file = std::ofstream { directory.path() / "f" }; + file << "abc"; + } + REQUIRE(::mkfifo((directory.path() / "fifo").c_str(), 0600) == 0); + auto const held = UniqueHandle { ::open(directory.path().c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC) }; + REQUIRE(held.get() >= 0); + + auto const fifo = openAfterWouldBlock(held.get(), "fifo", O_RDONLY | O_NOFOLLOW | O_CLOEXEC); + REQUIRE_FALSE(fifo.has_value()); + CHECK(fifo.error().code == FsErrorCode::WouldBlock); + + auto const file = openAfterWouldBlock(held.get(), "f", O_RDWR | O_NOFOLLOW | O_CLOEXEC); + REQUIRE(file.has_value()); + CHECK((::fcntl(file->get(), F_GETFL) & (O_ACCMODE | O_NONBLOCK)) == O_RDWR); + auto text = std::array {}; + CHECK(::pread(file->get(), text.data(), text.size(), 0) == 3); +} + +TEST_CASE("lease retry: openAt waits for a lease rather than answering WouldBlock", "[fs][native]") +{ + auto fixture = DescriptorFixture::createNative(); + { + auto file = std::ofstream { fixture.hostDirectory() / "leased" }; + file << "abc"; + } + // A read lease, broken by any open for writing, this process's own included. The break is + // signalled with SIGURG, whose default is to be ignored, rather than SIGIO, which would end the + // process; the kernel makes this process the lease's owner on F_SETLEASE. + auto const holder = + UniqueHandle { ::open((fixture.hostDirectory() / "leased").c_str(), O_RDONLY | O_CLOEXEC) }; + REQUIRE(holder.get() >= 0); + REQUIRE(::fcntl(holder.get(), F_SETSIG, SIGURG) == 0); + if (::fcntl(holder.get(), F_SETLEASE, F_RDLCK) != 0) + SKIP("this file system grants no lease"); + + // Releases the lease once its break has begun (F_GETLEASE then reports the lease it is being + // broken down to), within a bound, so a regression fails rather than hangs. + auto broken = std::atomic { false }; + auto releaser = std::thread { [&] { + for ([[maybe_unused]] auto const attempt: std::views::iota(0, 10'000)) + { + if (::fcntl(holder.get(), F_GETLEASE) == F_UNLCK) + { + broken.store(true); + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds { 1 }); + } + std::ignore = ::fcntl(holder.get(), F_SETLEASE, F_UNLCK); + } }; + + auto const opened = fixture.run( + fixture.root().openAt(SymlinkPolicy::NoFollow, "leased", OpenFlags::None, DescriptorFlags::Write)); + releaser.join(); + CHECK(broken.load()); + REQUIRE(opened.has_value()); + CHECK(fixture.run((*opened)->write(core::fs::test::bytesOf("x"), 0)).value() == 1); +} diff --git a/src/core/fs/linux/Openat2.cpp b/src/core/fs/linux/Openat2.cpp new file mode 100644 index 00000000..33e5ed11 --- /dev/null +++ b/src/core/fs/linux/Openat2.cpp @@ -0,0 +1,106 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The openat2 opener (Linux 5.6): the directory before a path's final name is opened in one call +// with RESOLVE_BENEATH, which refuses `..` above the starting directory, an absolute path and a +// link that leaves it (EXDEV), and RESOLVE_NO_MAGICLINKS, which refuses /proc's magic links +// (ELOOP). The final name is still the walk's, acted on without following. +#include + +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace core::fs::detail +{ + +namespace +{ + + /// What every directory is opened with: a path handle, so a directory the process may search but + /// not read is still resolved through. + constexpr auto DirectoryHow = OpenHow { + .flags = static_cast(O_PATH | O_DIRECTORY | O_CLOEXEC), + .mode = 0, + .resolve = + static_cast(Resolve::Beneath) | static_cast(Resolve::NoMagicLinks), + }; + + class KernelOpenat2 final: public IOpenat2System + { + public: + [[nodiscard]] int openat2(int directory, char const* path, OpenHow const& how) const noexcept override + { + return static_cast(::syscall(Openat2Syscall, directory, path, &how, sizeof how)); + } + }; + + class Openat2Opener final: public IBeneathOpener + { + public: + explicit Openat2Opener(std::shared_ptr system): _system { std::move(system) } {} + + [[nodiscard]] FsResult openDirectoryBeneath(platform::NativeHandle root, + std::string const& path) const override + { + for ([[maybe_unused]] auto const attempt: std::views::iota(std::size_t { 0 }, Openat2Retries + 1)) + { + auto const opened = + retryOnInterrupt([&] { return _system->openat2(root, path.c_str(), DirectoryHow); }); + if (opened >= 0) + return UniqueHandle { opened }; + switch (errno) + { + case EAGAIN: continue; + // The path, or a link on it, leaves the root. + case EXDEV: + return std::unexpected { FsError { + .code = FsErrorCode::NotPermitted, .systemCode = EXDEV, .context = "openat2" } }; + // The call was there at the probe and is refused now (a seccomp filter installed + // since, a flag the kernel will not take): this call walks instead. + case ENOSYS: + case EPERM: + case EINVAL: return UniqueHandle { platform::InvalidHandle }; + default: return errnoError("openat2"); + } + } + // The kernel kept racing a rename: this call walks instead. + return UniqueHandle { platform::InvalidHandle }; + } + + private: + std::shared_ptr _system; + }; + +} // namespace + +std::shared_ptr systemOpenat2() +{ + return std::make_shared(); +} + +std::unique_ptr makeOpenat2Opener(std::shared_ptr system) +{ + auto const probed = system->openat2(-1, ".", DirectoryHow); + if (probed >= 0) + closeNativeHandle(probed); + else if (errno != EBADF) + return nullptr; + return std::make_unique(std::move(system)); +} + +} // namespace core::fs::detail diff --git a/src/core/fs/linux/Openat2.hpp b/src/core/fs/linux/Openat2.hpp new file mode 100644 index 00000000..adce2509 --- /dev/null +++ b/src/core/fs/linux/Openat2.hpp @@ -0,0 +1,74 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// Linux's beneath step: `openat2` with `RESOLVE_BENEATH | RESOLVE_NO_MAGICLINKS`, which resolves a +/// whole directory path in the kernel and refuses, atomically, anything that would leave the +/// directory it starts from. The system call is reached through @c IOpenat2System, so a test can +/// script what it answers. Private to the fs module. + +#include +#include + +#include +#include +#include + +namespace core::fs::detail +{ + +/// `struct open_how`, `openat2`'s argument, spelled here rather than taken from ``: +/// the kernel's ABI, which does not change, so building needs neither UAPI 5.6 headers nor glibc +/// 2.32. Whether the running kernel has the call is still asked at run time. +struct OpenHow +{ + std::uint64_t flags = 0; ///< `open`'s flags. + std::uint64_t mode = 0; ///< The mode of a file created. + std::uint64_t resolve = 0; ///< The `Resolve` bits. +}; + +/// `openat2`'s resolve bits this module asks for, as `` numbers them. +enum class Resolve : std::uint8_t +{ + NoMagicLinks = 0x02, ///< `RESOLVE_NO_MAGICLINKS`: no /proc magic link is followed. + Beneath = 0x08, ///< `RESOLVE_BENEATH`: nothing resolves above the starting directory. +}; + +/// `openat2`'s system call number: 437 in the table every architecture shares since Linux 5.6. +inline constexpr long Openat2Syscall = 437; + +/// How many times an `openat2` the kernel answered `EAGAIN` (a rename or mount raced the lookup +/// of `..`) is made again before that one call walks instead. +inline constexpr std::size_t Openat2Retries = 8; + +/// The `openat2` system call. +class IOpenat2System +{ + public: + IOpenat2System() = default; + IOpenat2System(IOpenat2System const&) = delete; + IOpenat2System(IOpenat2System&&) = delete; + IOpenat2System& operator=(IOpenat2System const&) = delete; + IOpenat2System& operator=(IOpenat2System&&) = delete; + virtual ~IOpenat2System() = default; + + /// @param directory The directory @p path is relative to. + /// @param path The path. + /// @param how What to open it with. + /// @return The new descriptor; -1 with `errno` set on failure. + [[nodiscard]] virtual int openat2(int directory, char const* path, OpenHow const& how) const noexcept = 0; +}; + +/// @return The kernel's `openat2`, through `syscall`. +[[nodiscard]] CORE_FS_API std::shared_ptr systemOpenat2(); + +/// Builds the `openat2` opener over @p system, once it has asked @p system whether the call is +/// there: with a descriptor no process has (-1), so the probe touches no file system, and the +/// kernel's answer tells `EBADF` (the call is there) from `ENOSYS` (too old a kernel) and `EPERM` +/// (a seccomp filter refusing it). +/// @param system The system call. +/// @return The opener; null where the call is not there, and the walk alone resolves. +[[nodiscard]] CORE_FS_API std::unique_ptr makeOpenat2Opener( + std::shared_ptr system); + +} // namespace core::fs::detail diff --git a/src/core/fs/linux/Openat2_test.cpp b/src/core/fs/linux/Openat2_test.cpp new file mode 100644 index 00000000..7ed571f1 --- /dev/null +++ b/src/core/fs/linux/Openat2_test.cpp @@ -0,0 +1,196 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The openat2 opener through a scripted system call: the construction-time probe, the bounded EAGAIN +// retry that ends in the walk for that call, and the kernel's own refusal of a directory swapped for +// an outward link just before the call. +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +// Only the ABI cross-check reads the kernel's spelling, and only where the headers have it: the +// module itself builds without them (`Openat2.hpp`), and so must its tests. +#if __has_include() + #include +#endif + +using core::fs::FsErrorCode; +using core::fs::SymlinkPolicy; +using core::fs::detail::IOpenat2System; +using core::fs::detail::makeOpenat2Opener; +using core::fs::detail::Openat2Retries; +using core::fs::detail::systemOpenat2; +using core::fs::detail::UniqueHandle; +using core::fs::detail::WalkRules; + +namespace +{ + +/// The kernel's openat2, answering `EAGAIN` the first @c refusals times after the probe, and +/// running a hook before the first real call. +class ScriptedOpenat2 final: public IOpenat2System +{ + public: + ScriptedOpenat2(std::size_t refusals, int probeErrno = EBADF): + _refusals { refusals }, _probeErrno { probeErrno } + { + } + + [[nodiscard]] int openat2(int directory, + char const* path, + core::fs::detail::OpenHow const& how) const noexcept override + { + if (directory == -1) + { + errno = _probeErrno; + return -1; + } + ++_calls; + if (_calls <= _refusals) + { + errno = EAGAIN; + return -1; + } + if (_beforeCall) + std::exchange(_beforeCall, nullptr)(); + return _kernel->openat2(directory, path, how); + } + + /// @return How many calls were made beside the probe. + [[nodiscard]] std::size_t calls() const noexcept { return _calls; } + + /// @param hook What runs just before the first call that reaches the kernel. + void beforeCall(std::function hook) { _beforeCall = std::move(hook); } + + private: + std::shared_ptr _kernel = systemOpenat2(); + std::size_t _refusals; + int _probeErrno; + // The seam's call is const, as the kernel's is; the script counts what it was asked. + mutable std::size_t _calls = 0; + mutable std::function _beforeCall; +}; + +/// `/root/d/inside.txt`, with the root held open. +class Tree +{ + public: + Tree() + { + std::filesystem::create_directories(rootPath() / "d"); + std::filesystem::create_directory(rootPath() / "d" / "e"); + _root = UniqueHandle { ::open(rootPath().c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC) }; + if (_root.get() < 0) + throw std::runtime_error { "Tree: the root did not open" }; + } + + [[nodiscard]] int root() const noexcept { return _root.get(); } + + [[nodiscard]] std::filesystem::path rootPath() const { return _directory.path() / "root"; } + + private: + core::testing::ScopedTempDir _directory { "core-cpp-fs-openat2" }; + UniqueHandle _root { -1 }; +}; + +WalkRules rules() +{ + return WalkRules { .policy = &core::fs::posixPathPolicy(), + .finalPolicy = SymlinkPolicy::NoFollow, + .onLink = core::fs::detail::TrailingSlashOnLink::Follow, + .maxSymlinkHops = core::fs::DefaultMaxSymlinkHops, + .kernelSeparators = "/" }; +} + +core::fs::detail::PathPlan plan(std::string const& path) +{ + return core::fs::detail::planRelativePath(path, core::fs::posixPathPolicy()).value(); +} + +} // namespace + +TEST_CASE("openat2: the probe tells a missing call from one that is there", "[fs][openat2]") +{ + CHECK(makeOpenat2Opener(std::make_shared(0, EBADF)) != nullptr); + CHECK(makeOpenat2Opener(std::make_shared(0, ENOSYS)) == nullptr); + CHECK(makeOpenat2Opener(std::make_shared(0, EPERM)) == nullptr); +} + +TEST_CASE("openat2: EAGAIN is retried, then that call walks instead", "[fs][openat2]") +{ + if (makeOpenat2Opener(systemOpenat2()) == nullptr) + SKIP("this kernel, or a seccomp filter, refuses openat2"); + auto const tree = Tree {}; + auto const refusals = GENERATE( + std::size_t { 0 }, std::size_t { 3 }, Openat2Retries, Openat2Retries + 1, std::size_t { 100 }); + CAPTURE(refusals); + auto const system = std::make_shared(refusals); + auto const opener = makeOpenat2Opener(system); + REQUIRE(opener != nullptr); + + auto const resolved = core::fs::detail::resolveBeneath(tree.root(), plan("d/e/x"), rules(), opener.get()); + REQUIRE(resolved.has_value()); + CHECK(resolved->name == "x"); + CHECK(resolved->held.get() != -1); + // At most one call and its retries; past them, the walk resolved `d/e` itself. + CHECK(system->calls() == std::min(refusals, Openat2Retries + 1) + (refusals <= Openat2Retries ? 1 : 0)); +} + +TEST_CASE("openat2: a directory swapped for an outward link just before the call is refused", "[fs][escape]") +{ + if (makeOpenat2Opener(systemOpenat2()) == nullptr) + SKIP("this kernel, or a seccomp filter, refuses openat2"); + auto const tree = Tree {}; + auto const system = std::make_shared(0); + system->beforeCall([&] { + std::filesystem::rename(tree.rootPath() / "d", tree.rootPath() / "d.directory"); + std::filesystem::create_directory_symlink("../", tree.rootPath() / "d"); + }); + auto const opener = makeOpenat2Opener(system); + REQUIRE(opener != nullptr); + + auto const resolved = core::fs::detail::resolveBeneath(tree.root(), plan("d/e/x"), rules(), opener.get()); + REQUIRE_FALSE(resolved.has_value()); + CHECK(resolved.error().code == FsErrorCode::NotPermitted); +} + +TEST_CASE("openat2: the ABI spelled here is the kernel headers'", "[fs][native]") +{ +#if __has_include() + // The module builds without ; where the headers are present, they must agree. + using core::fs::detail::OpenHow; + using core::fs::detail::Resolve; + STATIC_CHECK(sizeof(OpenHow) == sizeof(::open_how)); + STATIC_CHECK(offsetof(OpenHow, flags) == offsetof(::open_how, flags)); + STATIC_CHECK(offsetof(OpenHow, mode) == offsetof(::open_how, mode)); + STATIC_CHECK(offsetof(OpenHow, resolve) == offsetof(::open_how, resolve)); + STATIC_CHECK(static_cast(Resolve::Beneath) == RESOLVE_BENEATH); + STATIC_CHECK(static_cast(Resolve::NoMagicLinks) == RESOLVE_NO_MAGICLINKS); + #ifdef SYS_openat2 + STATIC_CHECK(core::fs::detail::Openat2Syscall == SYS_openat2); + #endif +#else + SKIP("these kernel headers have no to compare against"); +#endif +} diff --git a/src/core/fs/posix/Append.cpp b/src/core/fs/posix/Append.cpp new file mode 100644 index 00000000..1ed78e6a --- /dev/null +++ b/src/core/fs/posix/Append.cpp @@ -0,0 +1,76 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// Appending where no write flag appends through a handle opened without `O_APPEND` (Apple, the BSDs, +// any POSIX system but Linux): a second handle, opened `O_APPEND` from the parent directory the +// first was opened beneath, by the same name, and checked by `(st_dev, st_ino)` to be the same +// object. Never `dup`, which shares the first handle's status flags and offset. The first is a +// regular file, so the O_NONBLOCK that keeps this open from waiting on a swapped-in FIFO changes +// nothing about its writes. +#include +#include +#include + +#include + +#include +#include +#include +#include +#include + +#include +#include + +namespace core::fs::detail +{ + +FsResult openAppendHandle(int directory, std::string const& name, int first, int integrityFlags) +{ + auto const second = retryOnInterrupt([&] { + return ::openat(directory, + name.c_str(), + O_WRONLY | O_APPEND | O_NOFOLLOW | O_NOCTTY | O_CLOEXEC | O_NONBLOCK + | integrityFlags); + }); + if (second < 0) + return errnoError("openat(O_APPEND)"); + auto handle = UniqueHandle { second }; + struct ::stat firstStatus {}; + struct ::stat secondStatus {}; + if (::fstat(first, &firstStatus) != 0 || ::fstat(second, &secondStatus) != 0) + return errnoError("fstat"); + if (firstStatus.st_dev != secondStatus.st_dev || firstStatus.st_ino != secondStatus.st_ino) + return std::unexpected { FsError { .code = FsErrorCode::Busy, + .systemCode = 0, + .context = "the name was replaced while it was opened" } }; + return handle; +} + +FsResult appendBytes(int, + OwnedHandle const* appendHandle, + std::mutex&, + std::span bytes) +{ + if (appendHandle == nullptr) + return std::unexpected { FsError { + .code = FsErrorCode::BadDescriptor, .systemCode = 0, .context = "no append handle was opened" } }; + auto written = std::size_t { 0 }; + while (written < bytes.size()) + { + auto const rest = bytes.subspan(written); + auto const count = + retryOnInterrupt([&] { return ::write(appendHandle->get(), rest.data(), rest.size()); }); + if (count < 0) + { + if (written > 0) + break; + return errnoError("write(O_APPEND)"); + } + if (count == 0) + break; + written += static_cast(count); + } + return written; +} + +} // namespace core::fs::detail diff --git a/src/core/fs/posix/BeneathDefault.cpp b/src/core/fs/posix/BeneathDefault.cpp new file mode 100644 index 00000000..04bea5c1 --- /dev/null +++ b/src/core/fs/posix/BeneathDefault.cpp @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// What BeneathStrategy::Best is on every POSIX system but Linux: the walk, one component at a +// time, since no kernel here resolves a path beneath a directory for the caller. Each directory is +// opened as a path handle where the system has O_PATH (FreeBSD 13), so a directory the process +// may search but not read is walked through; elsewhere (macOS) it is opened for reading, and +// O_NONBLOCK keeps a FIFO swapped in for a directory from holding the open. CMake compiles exactly +// one BeneathDefault.cpp, so no `#ifdef` chooses the strategy; the one below picks a flag inside +// the data, as the errno tables do. +#include +#include + +#include + +#include + +namespace core::fs::detail +{ + +namespace +{ + +#ifdef O_PATH + constexpr int WalkAccess = O_PATH; +#else + constexpr int WalkAccess = O_RDONLY | O_NONBLOCK; +#endif + + constexpr int WalkDirectoryOpenFlags = WalkAccess | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC; + +} // namespace + +std::unique_ptr makeBestBeneathOpener() +{ + return nullptr; +} + +int walkDirectoryOpenFlags() noexcept +{ + return WalkDirectoryOpenFlags; +} + +} // namespace core::fs::detail diff --git a/src/core/fs/posix/DirectoryEntries.cpp b/src/core/fs/posix/DirectoryEntries.cpp new file mode 100644 index 00000000..4eec2236 --- /dev/null +++ b/src/core/fs/posix/DirectoryEntries.cpp @@ -0,0 +1,96 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// What a POSIX directory entry is: its d_type, or a stat of its name without following where the +// file system does not say; the same on every POSIX system. +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace core::fs::detail +{ + +namespace +{ + + struct ModeRow + { + ::mode_t format; + DescriptorType type; + }; + + constexpr auto ModeRows = std::to_array({ + { .format = S_IFREG, .type = DescriptorType::RegularFile }, + { .format = S_IFDIR, .type = DescriptorType::Directory }, + { .format = S_IFLNK, .type = DescriptorType::SymbolicLink }, + { .format = S_IFCHR, .type = DescriptorType::CharacterDevice }, + { .format = S_IFBLK, .type = DescriptorType::BlockDevice }, + { .format = S_IFIFO, .type = DescriptorType::Fifo }, + { .format = S_IFSOCK, .type = DescriptorType::Socket }, + }); + + struct EntryTypeRow + { + unsigned char entryType; ///< `d_type`. + DescriptorType type; + }; + + constexpr auto EntryTypeRows = std::to_array({ + { .entryType = DT_REG, .type = DescriptorType::RegularFile }, + { .entryType = DT_DIR, .type = DescriptorType::Directory }, + { .entryType = DT_LNK, .type = DescriptorType::SymbolicLink }, + { .entryType = DT_CHR, .type = DescriptorType::CharacterDevice }, + { .entryType = DT_BLK, .type = DescriptorType::BlockDevice }, + { .entryType = DT_FIFO, .type = DescriptorType::Fifo }, + { .entryType = DT_SOCK, .type = DescriptorType::Socket }, + }); + + /// @return What the entry is; `Unknown` where its stat fails too (it went meanwhile). + DescriptorType typeOfEntry(int directory, char const* name, unsigned char entryType) + { + auto const row = std::ranges::find(EntryTypeRows, entryType, &EntryTypeRow::entryType); + if (row != EntryTypeRows.end()) + return row->type; + struct ::stat status {}; + if (directory < 0 || ::fstatat(directory, name, &status, AT_SYMLINK_NOFOLLOW) != 0) + return DescriptorType::Unknown; + return typeOfMode(status.st_mode); + } + +} // namespace + +DescriptorType typeOfMode(::mode_t mode) noexcept +{ + auto const row = std::ranges::find(ModeRows, mode & S_IFMT, &ModeRow::format); + return row == ModeRows.end() ? DescriptorType::Unknown : row->type; +} + +std::optional> entryOf(int directory, char const* name, unsigned char entryType) +{ + auto const text = std::string_view { name }; + if (text == "." || text == "..") + return std::nullopt; + // No file system hands out such a name; one that did would name another entry, or a path. + if (text.empty() || text.contains('/')) + return FsResult { std::unexpected { + FsError { .code = FsErrorCode::Io, .systemCode = 0, .context = "directory entry name" } } }; + if (!isUtf8(text)) + return FsResult { std::unexpected { FsError { + .code = FsErrorCode::IllegalByteSequence, .systemCode = 0, .context = "directory entry" } } }; + return FsResult { DirectoryEntry { .type = typeOfEntry(directory, name, entryType), + .name = std::string { text } } }; +} + +} // namespace core::fs::detail diff --git a/src/core/fs/posix/DirectoryEntries_test.cpp b/src/core/fs/posix/DirectoryEntries_test.cpp new file mode 100644 index 00000000..695dea5d --- /dev/null +++ b/src/core/fs/posix/DirectoryEntries_test.cpp @@ -0,0 +1,79 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// What a POSIX directory entry is, decided by entryOf over a real directory: d_type where the file +// system reports one, and a stat of the name that never follows a link where it does not (DT_UNKNOWN, +// which ext4, tmpfs and btrfs never report, so the streams over them never reach it). +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include + +#include +#include + +using core::fs::DescriptorType; +using core::fs::FsErrorCode; +using core::fs::detail::entryOf; +using core::fs::detail::UniqueHandle; +using core::fs::test::outcomeOf; + +namespace +{ + +/// @return What entryOf says @p name in @p directory is, when the file system reports @p entryType. +std::optional typeOf(UniqueHandle const& directory, char const* name, unsigned char entryType) +{ + auto const entry = entryOf(directory.get(), name, entryType); + REQUIRE(entry.has_value()); + REQUIRE(entry->has_value()); + CHECK((*entry)->name == name); + return (*entry)->type; +} + +} // namespace + +TEST_CASE("posix entries: DT_UNKNOWN is stat'ed, never following a link", "[fs][native][directory]") +{ + auto const temp = core::testing::ScopedTempDir { "core-cpp-fs-entries" }; + std::ofstream { temp.path() / "file" } << "x"; + std::filesystem::create_directory(temp.path() / "dir"); + std::filesystem::create_directory_symlink("dir", temp.path() / "link-to-dir"); + std::filesystem::create_symlink("file", temp.path() / "link-to-file"); + auto const directory = UniqueHandle { ::open(temp.path().c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC) }; + REQUIRE(directory.get() >= 0); + + CHECK(typeOf(directory, "file", DT_UNKNOWN) == DescriptorType::RegularFile); + CHECK(typeOf(directory, "dir", DT_UNKNOWN) == DescriptorType::Directory); + CHECK(typeOf(directory, "link-to-dir", DT_UNKNOWN) == DescriptorType::SymbolicLink); + CHECK(typeOf(directory, "link-to-file", DT_UNKNOWN) == DescriptorType::SymbolicLink); + // Gone by the time it is stat'ed: reported, but as what it can no longer be said to be. + CHECK(typeOf(directory, "gone", DT_UNKNOWN) == DescriptorType::Unknown); + // A d_type that is known is taken as it is, without a stat. + CHECK(typeOf(directory, "gone", DT_REG) == DescriptorType::RegularFile); + CHECK(typeOf(directory, "file", DT_LNK) == DescriptorType::SymbolicLink); +} + +TEST_CASE("posix entries: . and .. are no entries, and a name no file system gives is refused", + "[fs][native][directory]") +{ + CHECK(entryOf(-1, ".", DT_DIR) == std::nullopt); + CHECK(entryOf(-1, "..", DT_DIR) == std::nullopt); + auto const nonUtf8 = entryOf(-1, "bad-\xff", DT_REG); + REQUIRE(nonUtf8.has_value()); + CHECK(outcomeOf(*nonUtf8) == FsErrorCode::IllegalByteSequence); + for (auto const* name: { "", "a/b", "/" }) + { + CAPTURE(name); + auto const entry = entryOf(-1, name, DT_REG); + REQUIRE(entry.has_value()); + CHECK(outcomeOf(*entry) == FsErrorCode::Io); + } +} diff --git a/src/core/fs/posix/DirectoryRead.cpp b/src/core/fs/posix/DirectoryRead.cpp new file mode 100644 index 00000000..2bf49e43 --- /dev/null +++ b/src/core/fs/posix/DirectoryRead.cpp @@ -0,0 +1,135 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// A directory stream's reads on every POSIX system but Linux: fdopendir over the stream's own +// handle, and readdir, whose entry buffer belongs to that DIR alone and is read under the stream's +// lock. Up to detail::DirectoryBatchEntries entries a batch. +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace core::fs::detail +{ + +namespace +{ + + struct DirectoryCloser + { + void operator()(DIR* directory) const noexcept + { + // Closes the handle fdopendir took over, too; not retried, as closeNativeHandle says. + ::closedir(directory); + } + }; + + using UniqueDirectory = std::unique_ptr; + + /// Closes @p directory on @p closer, or there and then should the executor free the frame + /// without running it. + async::DetachedTask closeDirectoryOn(async::IExecutor* closer, UniqueDirectory directory) + { + co_await async::ResumeOn { *closer }; + directory.reset(); + } + +} // namespace + +/// The stream's own DIR, closed by its last owner on the blocking executor as an @c OwnedHandle is; +/// a batch holds @c lock while it reads. +struct DirectoryReader +{ + UniqueDirectory directory; + async::IExecutor* closer; + std::mutex lock; ///< Held by the batch that reads. + /// A readdir failure met after a batch's first entries, answered by the batch after it; under + /// @c lock. + std::optional failure; + + DirectoryReader(UniqueDirectory opened, async::IExecutor& closeOn) noexcept: + directory { std::move(opened) }, closer { &closeOn }, failure {} + { + } + + DirectoryReader(DirectoryReader const&) = delete; + DirectoryReader(DirectoryReader&&) = delete; + DirectoryReader& operator=(DirectoryReader const&) = delete; + DirectoryReader& operator=(DirectoryReader&&) = delete; + + ~DirectoryReader() + { + try + { + closeDirectoryOn(closer, std::move(directory)); + } + catch (std::bad_alloc const&) + { + directory.reset(); + } + } +}; + +FsResult> openDirectoryReader(int directory, async::IExecutor& closer) +{ + auto const opened = + retryOnInterrupt([&] { return ::openat(directory, ".", O_RDONLY | O_DIRECTORY | O_CLOEXEC); }); + if (opened < 0) + return errnoError("openat"); + auto handle = UniqueHandle { opened }; + auto* const stream = ::fdopendir(handle.get()); + if (stream == nullptr) + return errnoError("fdopendir"); + // fdopendir owns the handle from here on; closedir closes it. + std::ignore = handle.release(); + return std::make_shared(UniqueDirectory { stream }, closer); +} + +FsResult readDirectoryBatch(DirectoryReader& reader) +{ + auto const held = std::scoped_lock { reader.lock }; + if (reader.failure) + return std::unexpected { *std::exchange(reader.failure, std::nullopt) }; + auto batch = DirectoryBatch {}; + auto const handle = ::dirfd(reader.directory.get()); + for ([[maybe_unused]] auto const read: std::views::iota(std::size_t { 0 }, DirectoryBatchEntries)) + { + errno = 0; + auto const* const entry = ::readdir(reader.directory.get()); + if (entry == nullptr) + { + if (errno == 0) + batch.end = StreamEnd::Reached; + else if (batch.entries.empty()) + return errnoError("readdir"); + else + // The entries read come first; the next batch answers the failure. + reader.failure = errnoError("readdir").error(); + return batch; + } + if (auto answer = entryOf(handle, entry->d_name, entry->d_type)) + batch.entries.push_back(std::move(*answer)); + } + return batch; +} + +} // namespace core::fs::detail diff --git a/src/core/fs/posix/DirectoryRead.hpp b/src/core/fs/posix/DirectoryRead.hpp new file mode 100644 index 00000000..8339c8a5 --- /dev/null +++ b/src/core/fs/posix/DirectoryRead.hpp @@ -0,0 +1,54 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// How a POSIX directory stream reads: from the directory opened again for the stream alone, so its +/// position is no one else's, one batch per call. Linux reads with `getdents64` into a fixed buffer +/// (`linux/DirectoryRead.cpp`); every other POSIX system through `fdopendir` and `readdir` +/// (`posix/DirectoryRead.cpp`), whose entry buffer is the stream's own and read under its lock. +/// Private to the fs module. + +#include +#include +#include +#include +#include + +#include + +#include +#include + +namespace core::fs::detail +{ + +/// A directory opened for one stream, and what it reads into; defined by the system's source. +struct DirectoryReader; + +/// Opens @p directory again for a stream of its own. +/// @param directory An open directory. +/// @param closer Where the reader's handle is closed once its last owner lets go: the blocking +/// executor. Must outlive the reader. +/// @return The reader; what refused it. +[[nodiscard]] FsResult> openDirectoryReader(int directory, + async::IExecutor& closer); + +/// Reads the next batch of @p reader's entries, where its last batch ended. Blocks. +/// @param reader The reader. +/// @return The batch; what refused it. +[[nodiscard]] FsResult readDirectoryBatch(DirectoryReader& reader); + +/// @param mode A `st_mode`. +/// @return What it says the object is. +[[nodiscard]] DescriptorType typeOfMode(::mode_t mode) noexcept; + +/// @param directory The directory the entry is in. +/// @param name The entry's name, NUL-terminated, as the system spells it. +/// @param entryType Its `d_type`; where that is `DT_UNKNOWN`, the name is stat'ed without following. +/// @return The entry; nullopt for `.` and `..`; `IllegalByteSequence` for a name that is not UTF-8; +/// `Io` for an empty name or one holding a `/`, which no file system should report. +[[nodiscard]] CORE_FS_API std::optional> entryOf(int directory, + char const* name, + unsigned char entryType); + +} // namespace core::fs::detail diff --git a/src/core/fs/posix/DirectoryStreamMemory_test.cpp b/src/core/fs/posix/DirectoryStreamMemory_test.cpp new file mode 100644 index 00000000..14b4347c --- /dev/null +++ b/src/core/fs/posix/DirectoryStreamMemory_test.cpp @@ -0,0 +1,102 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// What a directory stream holds while it reads a large directory: one batch, never the listing. +// This binary replaces the global allocation functions to count the bytes alive, which is why it is a +// binary of its own: a replacement reaches every test linked beside it. POSIX, where a directory of +// tens of thousands of entries is cheap to make. +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace +{ + +/// What precedes each allocation: its size, and room to keep the storage after it aligned. +constexpr auto HeaderBytes = std::size_t { alignof(std::max_align_t) }; + +std::atomic liveBytes { 0 }; +std::atomic peakBytes { 0 }; + +} // namespace + +void* core::testing::replacedAllocate(std::size_t size) +{ + auto* const block = static_cast(std::malloc(HeaderBytes + size)); + if (block == nullptr) + throw std::bad_alloc {}; + std::memcpy(block, &size, sizeof(size)); + auto const live = liveBytes.fetch_add(size) + size; + auto peak = peakBytes.load(); + while (live > peak && !peakBytes.compare_exchange_weak(peak, live)) + { + } + return block + HeaderBytes; +} + +void core::testing::replacedRelease(void* storage) noexcept +{ + if (storage == nullptr) + return; + auto* const block = static_cast(storage) - HeaderBytes; + auto size = std::size_t { 0 }; + std::memcpy(&size, block, sizeof(size)); + liveBytes.fetch_sub(size); + std::free(block); +} + +TEST_CASE("a stream over a large directory holds a batch, not the listing", "[fs][native][directory]") +{ + /// What the stream may hold above what was alive before it was read: a batch's buffer and the + /// entries of one batch, with room to spare. + constexpr auto Budget = std::size_t { 1 } << 20U; + // Derived from the entry's size rather than written down, because that size is the standard + // library's: a `std::string` is 32 bytes in libstdc++ and 24 in libc++, so a fixed count that + // outgrew the budget on Linux did not on macOS. Holding the listing takes more than twice the + // budget in entries alone, before their names, on every library. + constexpr auto Count = (2 * Budget / sizeof(core::fs::DirectoryEntry)) + 1; + static_assert(Count * sizeof(core::fs::DirectoryEntry) > 2 * Budget); + // Bounded, so the run stays capped and every name fits the fixed five-digit pattern below. + static_assert(Count <= 99'999); + + auto fixture = core::fs::test::DescriptorFixture::createNative(); + for (auto const index: std::views::iota(std::size_t { 0 }, Count)) + { + auto const path = fixture.hostDirectory() / std::format("entry-{:05}", index); + auto const made = ::open(path.c_str(), O_CREAT | O_EXCL | O_WRONLY | O_CLOEXEC, 0600); + REQUIRE(made >= 0); + ::close(made); + } + auto stream = fixture.run(fixture.root().readDirectory()); + REQUIRE(stream.has_value()); + + auto const before = liveBytes.load(); + peakBytes.store(before); + auto entries = std::size_t { 0 }; + while (entries <= Count) + { + auto const next = fixture.run((*stream)->next()); + REQUIRE(next.has_value()); + if (!*next) + break; + ++entries; + } + auto const held = peakBytes.load() - before; + CAPTURE(held); + CHECK(entries == Count); + CHECK(held < Budget); +} diff --git a/src/core/fs/posix/ErrnoRows.hpp b/src/core/fs/posix/ErrnoRows.hpp new file mode 100644 index 00000000..c9810b9e --- /dev/null +++ b/src/core/fs/posix/ErrnoRows.hpp @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// The errno classification every POSIX system shares, spelled by macro so each system's own values +/// fill it. Private: included by `posix/ErrnoTable.cpp` and `bsd/ErrnoTable.cpp`, which differ only +/// in what an `O_NOFOLLOW` open answers for a symbolic link. + +#include + +#include +#include + +namespace core::fs::detail +{ + +/// Every errno the WASI `error-code` has a case for. `EWOULDBLOCK` and `EOPNOTSUPP` have rows of +/// their own because a system may give them values of their own; where they equal `EAGAIN` and +/// `ENOTSUP` the first row answers. +inline constexpr auto ErrnoRows = std::to_array({ + { .systemCode = EACCES, .code = FsErrorCode::Access }, + { .systemCode = EAGAIN, .code = FsErrorCode::WouldBlock }, + { .systemCode = EWOULDBLOCK, .code = FsErrorCode::WouldBlock }, + { .systemCode = EALREADY, .code = FsErrorCode::Already }, + { .systemCode = EBADF, .code = FsErrorCode::BadDescriptor }, + { .systemCode = EBUSY, .code = FsErrorCode::Busy }, + { .systemCode = EDEADLK, .code = FsErrorCode::Deadlock }, + { .systemCode = EDQUOT, .code = FsErrorCode::Quota }, + { .systemCode = EEXIST, .code = FsErrorCode::Exist }, + { .systemCode = EFBIG, .code = FsErrorCode::FileTooLarge }, + { .systemCode = EILSEQ, .code = FsErrorCode::IllegalByteSequence }, + { .systemCode = EINPROGRESS, .code = FsErrorCode::InProgress }, + { .systemCode = EINTR, .code = FsErrorCode::Interrupted }, + { .systemCode = EINVAL, .code = FsErrorCode::Invalid }, + { .systemCode = EIO, .code = FsErrorCode::Io }, + { .systemCode = EISDIR, .code = FsErrorCode::IsDirectory }, + { .systemCode = ELOOP, .code = FsErrorCode::Loop }, + { .systemCode = EMLINK, .code = FsErrorCode::TooManyLinks }, + { .systemCode = EMSGSIZE, .code = FsErrorCode::MessageSize }, + { .systemCode = ENAMETOOLONG, .code = FsErrorCode::NameTooLong }, + { .systemCode = ENODEV, .code = FsErrorCode::NoDevice }, + { .systemCode = ENOENT, .code = FsErrorCode::NoEntry }, + { .systemCode = ENOLCK, .code = FsErrorCode::NoLock }, + { .systemCode = ENOMEM, .code = FsErrorCode::InsufficientMemory }, + { .systemCode = ENOSPC, .code = FsErrorCode::InsufficientSpace }, + { .systemCode = ENOTDIR, .code = FsErrorCode::NotDirectory }, + { .systemCode = ENOTEMPTY, .code = FsErrorCode::NotEmpty }, + { .systemCode = ENOTRECOVERABLE, .code = FsErrorCode::NotRecoverable }, + { .systemCode = ENOTSUP, .code = FsErrorCode::Unsupported }, + { .systemCode = EOPNOTSUPP, .code = FsErrorCode::Unsupported }, + { .systemCode = ENOTTY, .code = FsErrorCode::NoTty }, + { .systemCode = ENXIO, .code = FsErrorCode::NoSuchDevice }, + { .systemCode = EOVERFLOW, .code = FsErrorCode::Overflow }, + { .systemCode = EPERM, .code = FsErrorCode::NotPermitted }, + { .systemCode = EPIPE, .code = FsErrorCode::Pipe }, + { .systemCode = EROFS, .code = FsErrorCode::ReadOnly }, + { .systemCode = ESPIPE, .code = FsErrorCode::InvalidSeek }, + { .systemCode = ETXTBSY, .code = FsErrorCode::TextFileBusy }, + { .systemCode = EXDEV, .code = FsErrorCode::CrossDevice }, +}); + +} // namespace core::fs::detail diff --git a/src/core/fs/posix/ErrnoTable.cpp b/src/core/fs/posix/ErrnoTable.cpp new file mode 100644 index 00000000..79b2a123 --- /dev/null +++ b/src/core/fs/posix/ErrnoTable.cpp @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The errno tables of a POSIX system that is neither Apple nor a BSD (Linux, and the rest). +#include +#include + +#include +#include +#include + +namespace core::fs +{ + +namespace +{ + + // Linux and the others answer an O_NOFOLLOW open of a symbolic link with ELOOP alone. + constexpr auto NoFollowSymlinkErrnos = std::to_array({ ELOOP }); + +} // namespace + +std::span systemErrorTable() noexcept +{ + return detail::ErrnoRows; +} + +std::span ntStatusTable() noexcept +{ + return {}; +} + +std::span noFollowSymlinkErrnos() noexcept +{ + return NoFollowSymlinkErrnos; +} + +} // namespace core::fs diff --git a/src/core/fs/posix/Lease.cpp b/src/core/fs/posix/Lease.cpp new file mode 100644 index 00000000..13585da2 --- /dev/null +++ b/src/core/fs/posix/Lease.cpp @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// Waiting for a lease on every POSIX system but Linux: none of them has leases, so an O_NONBLOCK +// open that answered EWOULDBLOCK is answered WouldBlock, and never opened again blocking. +#include +#include +#include + +#include +#include +#include + +namespace core::fs::detail +{ + +FsResult openAfterWouldBlock(int, std::string const&, int) +{ + return std::unexpected { FsError { + .code = FsErrorCode::WouldBlock, .systemCode = EWOULDBLOCK, .context = "openat" } }; +} + +} // namespace core::fs::detail diff --git a/src/core/fs/posix/NativePathPolicy.cpp b/src/core/fs/posix/NativePathPolicy.cpp new file mode 100644 index 00000000..7cacaaa6 --- /dev/null +++ b/src/core/fs/posix/NativePathPolicy.cpp @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The native name rules of a POSIX system. +#include + +namespace core::fs +{ + +PathPolicy const& nativePathPolicy() noexcept +{ + return posixPathPolicy(); +} + +} // namespace core::fs diff --git a/src/core/fs/posix/OwnedHandleAllocation_test.cpp b/src/core/fs/posix/OwnedHandleAllocation_test.cpp new file mode 100644 index 00000000..eb13722c --- /dev/null +++ b/src/core/fs/posix/OwnedHandleAllocation_test.cpp @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// What the last owner of a handle does when the close it queues cannot be allocated: it closes the +// handle there and then, rather than ending the process from a destructor. This binary replaces the +// global allocation functions so a case can fail exactly the next one, which is why it is a binary +// of its own: a replacement reaches every test linked beside it. +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace +{ + +/// Whether the next allocation on this thread fails. +thread_local bool failNextAllocation = false; + +} // namespace + +void* core::testing::replacedAllocate(std::size_t size) +{ + if (std::exchange(failNextAllocation, false)) + throw std::bad_alloc {}; + if (auto* const storage = std::malloc(size == 0 ? 1 : size)) + return storage; + throw std::bad_alloc {}; +} + +void core::testing::replacedRelease(void* storage) noexcept +{ + std::free(storage); +} + +TEST_CASE("an owned handle whose queued close cannot be allocated closes inline", "[fs][native]") +{ + auto closer = core::async::testing::ManualExecutor {}; + auto pipe = std::array {}; + REQUIRE(::pipe(pipe.data()) == 0); + auto const writeEnd = core::fs::detail::UniqueHandle { pipe[1] }; + { + auto const handle = + core::fs::detail::OwnedHandle { core::fs::detail::UniqueHandle { pipe[0] }, closer }; + failNextAllocation = true; + } + CHECK_FALSE(failNextAllocation); + CHECK(closer.pending() == 0); + errno = 0; + CHECK(::fcntl(pipe[0], F_GETFD) == -1); + CHECK(errno == EBADF); +} diff --git a/src/core/fs/posix/PosixDescriptor.cpp b/src/core/fs/posix/PosixDescriptor.cpp new file mode 100644 index 00000000..f8f89189 --- /dev/null +++ b/src/core/fs/posix/PosixDescriptor.cpp @@ -0,0 +1,904 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The native descriptors of a POSIX system. Every system call is made inside async::offload, on the +// blocking executor, by a job that holds the descriptor's handle by shared ownership (decision C2), +// and the caller resumes on its home executor. Rights are checked from rightsTable() before +// anything else, inside the job. A path is resolved beneath the descriptor by detail::resolveBeneath +// (openat2 or the component walk), and the final name is acted on without following, in the +// directory the walk holds. What differs between POSIX systems is behind posix/PosixSystem.hpp. +// +// A directory stream opens the directory again (`.`, beneath its handle), so its position is its +// own, and reads it a batch per offload through posix/DirectoryRead.hpp; an entry whose type the +// system does not report is stat'ed without following, in the same job. +#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 +#include +#include +#include + +#include +#include + +namespace core::fs +{ + +void detail::closeNativeHandle(platform::NativeHandle handle) noexcept +{ + // Not retried on EINTR: POSIX leaves the descriptor's state unspecified then, and Linux has + // already closed it, so a retry could close a number another thread just opened. + ::close(handle); +} + +namespace +{ + + using detail::NativeContext; + using detail::refuse; + using detail::SharedContext; + using detail::SharedHandle; + using detail::UniqueHandle; + + /// What the kernel splits a name on; never part of a name handed to it, whatever the policy. + constexpr std::string_view KernelSeparators = "/"; + + /// The largest offset a system call takes. + constexpr auto OffsetMax = static_cast(std::numeric_limits::max()); + + /// What an O_NONBLOCK open answers where it would wait: EAGAIN and EWOULDBLOCK, one value on + /// some systems and two on others. + constexpr auto WouldBlockErrnos = std::to_array({ EAGAIN, EWOULDBLOCK }); + + /// The mode a new file or directory is created with, before the process's umask. + constexpr ::mode_t NewFileMode = 0666; + constexpr ::mode_t NewDirectoryMode = 0777; + + using detail::typeOfMode; + + DescriptorStat statOf(struct ::stat const& status) noexcept + { + auto const times = detail::timesOf(status); + return DescriptorStat { .type = typeOfMode(status.st_mode), + .linkCount = static_cast(status.st_nlink), + .size = static_cast(status.st_size), + .accessed = times.accessed, + .modified = times.modified, + .statusChanged = times.statusChanged }; + } + + MetadataHash hashOf(NativeContext const& context, struct ::stat const& status) noexcept + { + auto const times = detail::timesOf(status); + return detail::hashMetadata( + context.secret, + detail::MetadataFields { .device = static_cast(status.st_dev), + .fileIdLow = static_cast(status.st_ino), + .fileIdHigh = 0, + .size = static_cast(status.st_size), + .modified = times.modified, + .statusChanged = times.statusChanged }); + } + + FsResult statHandle(int handle) + { + struct ::stat status {}; + if (::fstat(handle, &status) != 0) + return detail::errnoError("fstat"); + return status; + } + + /// `fstat` of @p directory itself for an empty @p name, `fstatat` without following otherwise. + FsResult statEntry(int directory, std::string const& name) + { + if (name.empty()) + return statHandle(directory); + struct ::stat status {}; + if (::fstatat(directory, name.c_str(), &status, AT_SYMLINK_NOFOLLOW) != 0) + return detail::errnoError("fstatat"); + return status; + } + + using detail::EntryKind; + using detail::FinalComponent; + using detail::Resolved; + using detail::TrailingSlashOnLink; + + /// Resolves @p path beneath @p root, following a final link where @p finalPolicy, or a trailing + /// `/` under @p onLink, says so. + FsResult resolve(int root, + std::string_view path, + NativeContext const& context, + SymlinkPolicy finalPolicy, + TrailingSlashOnLink onLink) + { + return detail::planRelativePath(path, *context.policy).and_then([&](detail::PathPlan plan) { + return detail::resolveBeneath(root, + std::move(plan), + detail::walkRulesOf(context, finalPolicy, onLink), + context.beneathOpener.get()); + }); + } + + /// @return @p resolved, where it names a place an entry of @p creating can be made; `Exist` + /// where something is there already (the directory itself included), `NotDirectory` + /// where the path ends in `/` and @p creating is not a directory. + FsResult vacant(Resolved resolved, DescriptorType creating) + { + if (resolved.name.empty() || resolved.kind != EntryKind::Missing) + return refuse(FsErrorCode::Exist); + if (creating != DescriptorType::Directory && resolved.finalComponent == FinalComponent::Directory) + return refuse(FsErrorCode::NotDirectory); + return resolved; + } + + struct OpenFlagRow + { + OpenFlags flag; + int openFlag; + }; + + constexpr auto OpenFlagRows = std::to_array({ + { .flag = OpenFlags::Create, .openFlag = O_CREAT }, + { .flag = OpenFlags::Directory, .openFlag = O_DIRECTORY }, + { .flag = OpenFlags::Exclusive, .openFlag = O_EXCL }, + { .flag = OpenFlags::Truncate, .openFlag = O_TRUNC }, + }); + + /// The `openat` flags for @p open and @p flags; the final component is never followed. + FsResult openFlagsOf(OpenFlags open, DescriptorFlags flags) + { + auto const reads = hasFlag(flags, DescriptorFlags::Read); + auto const writes = hasFlag(flags, DescriptorFlags::Write); + auto openFlags = O_NOFOLLOW | O_CLOEXEC | O_NOCTTY; + if (writes) + openFlags |= reads ? O_RDWR : O_WRONLY; + else + openFlags |= O_RDONLY; + for (auto const& row: OpenFlagRows) + if (hasFlag(open, row.flag)) + openFlags |= row.openFlag; + return detail::syncOpenFlags(flags).transform([openFlags](int sync) { return openFlags | sync; }); + } + + ::timespec timespecOf(NewTimestamp const& change) noexcept + { + if (std::holds_alternative(change)) + return ::timespec { .tv_sec = 0, .tv_nsec = UTIME_OMIT }; + if (std::holds_alternative(change)) + return ::timespec { .tv_sec = 0, .tv_nsec = UTIME_NOW }; + auto const time = std::get(change); + return ::timespec { .tv_sec = static_cast<::time_t>(time.seconds), + .tv_nsec = static_cast(time.nanoseconds) }; + } + + FsResult> timespecsOf(NewTimestamp const& accessed, + NewTimestamp const& modified) + { + for (auto const& change: { accessed, modified }) + if (auto const* time = std::get_if(&change); + time != nullptr && time->nanoseconds >= 1'000'000'000) + return refuse(FsErrorCode::Invalid); + return std::array { timespecOf(accessed), timespecOf(modified) }; + } + + /// Clears the O_NONBLOCK an open was made with, so reads and writes on a FIFO or a device wait + /// as the descriptor's other calls do, on the blocking executor, where a guest asked them to. + FsResult clearNonBlocking(int handle) + { + auto const statusFlags = ::fcntl(handle, F_GETFL); + if (statusFlags == -1 || ::fcntl(handle, F_SETFL, statusFlags & ~O_NONBLOCK) == -1) + return detail::errnoError("fcntl(F_SETFL)"); + return {}; + } + + /// Opens @p name beneath @p directory without ever waiting on the way in: with O_NONBLOCK, so a + /// FIFO opens at once whatever was renamed over the name since the walk looked at it, and the + /// flag cleared once open. A regular file under a lease answers EWOULDBLOCK then; it is opened + /// again, waiting for the lease, through @c detail::openAfterWouldBlock, which never opens + /// anything but a regular file blocking. + FsResult openEntry(int directory, std::string const& name, int flags) + { + auto const* const path = name.empty() ? "." : name.c_str(); + auto const opened = detail::retryOnInterrupt( + [&] { return ::openat(directory, path, flags | O_NONBLOCK, NewFileMode); }); + if (opened >= 0) + { + auto handle = UniqueHandle { opened }; + return clearNonBlocking(opened).transform([&] { return std::move(handle); }); + } + auto const error = errno; + if (std::ranges::find(WouldBlockErrnos, error) != WouldBlockErrnos.end()) + return detail::openAfterWouldBlock(directory, path, flags); + return std::unexpected { detail::openFailure(directory, path, flags, error) }; + } + + FsResult succeededOr(int result, char const* call) + { + if (result != 0) + return detail::errnoError(call); + return {}; + } + + class PosixDirectoryStream final: public detail::BatchedDirectoryStream + { + public: + PosixDirectoryStream(SharedContext context, std::shared_ptr reader): + _context { std::move(context) }, _reader { std::move(reader) } + { + } + + protected: + async::Task> fetch() override + { + return async::offload(_context->home, _context->blocking, [reader = _reader]() { + return detail::readDirectoryBatch(*reader); + }); + } + + private: + SharedContext _context; + std::shared_ptr _reader; + }; + + class PosixDescriptor final: public detail::NativeDescriptorBase + { + public: + PosixDescriptor(SharedContext context, + SharedHandle handle, + SharedHandle appendHandle, + DescriptorFlags flags, + DescriptorType type): + NativeDescriptorBase { std::move(context), std::move(handle), flags, type }, + _appendHandle { std::move(appendHandle) }, + _appendLock { std::make_shared() } + { + } + + async::Task> read(std::size_t maxBytes, std::uint64_t offset) override + { + return submit([handle = handle(), + flags = flags(), + want = std::min(maxBytes, context()->options.maxReadChunk), + offset]() -> FsResult { + return checkRights(flags, Operation::Read).and_then([&]() -> FsResult { + // Nothing can lie beyond the largest offset a file can have. + if (offset > OffsetMax) + return ReadChunk { .bytes = {}, .end = StreamEnd::Reached }; + auto bytes = std::vector(want); + auto const count = detail::retryOnInterrupt([&] { + return ::pread(handle->get(), bytes.data(), bytes.size(), static_cast(offset)); + }); + if (count < 0) + return detail::errnoError("pread"); + bytes.resize(static_cast(count)); + auto const end = bytes.size() < want ? StreamEnd::Reached : StreamEnd::More; + return ReadChunk { .bytes = std::move(bytes), .end = end }; + }); + }); + } + + async::Task> write(std::vector bytes, std::uint64_t offset) override + { + return submit([handle = handle(), flags = flags(), bytes = std::move(bytes), offset]() + -> FsResult { + return checkRights(flags, Operation::Write).and_then([&]() -> FsResult { + if (offset > OffsetMax || bytes.size() > OffsetMax - offset) + return refuse(FsErrorCode::FileTooLarge); + auto written = std::size_t { 0 }; + while (written < bytes.size()) + { + auto const count = detail::retryOnInterrupt([&] { + return ::pwrite(handle->get(), + bytes.data() + written, + bytes.size() - written, + static_cast(offset + written)); + }); + if (count < 0) + { + if (written > 0) + break; + return detail::errnoError("pwrite"); + } + if (count == 0) + break; + written += static_cast(count); + } + return written; + }); + }); + } + + async::Task> append(std::vector bytes) override + { + return submit([handle = handle(), + appendHandle = _appendHandle, + appendLock = _appendLock, + flags = flags(), + bytes = std::move(bytes)]() { + return checkRights(flags, Operation::Append).and_then([&] { + return detail::appendBytes(handle->get(), appendHandle.get(), *appendLock, bytes); + }); + }); + } + + async::Task> advise(std::uint64_t offset, std::uint64_t length, Advice advice) override + { + return submit([handle = handle(), flags = flags(), offset, length, advice]() { + return checkRights(flags, Operation::Advise).and_then([&] { + return detail::adviseRange(handle->get(), offset, length, advice); + }); + }); + } + + async::Task> syncData() override + { + return submit([handle = handle(), flags = flags()]() { + return checkRights(flags, Operation::Sync).and_then([&] { + return detail::syncData(handle->get()); + }); + }); + } + + async::Task> sync() override + { + return submit([handle = handle(), flags = flags()]() { + return checkRights(flags, Operation::Sync).and_then([&] { + return detail::syncAll(handle->get()); + }); + }); + } + + async::Task> type() override + { + return submit([handle = handle(), flags = flags()]() { + return checkRights(flags, Operation::Stat) + .and_then([&] { return statHandle(handle->get()); }) + .transform([](struct ::stat const& status) { return typeOfMode(status.st_mode); }); + }); + } + + async::Task> setSize(std::uint64_t size) override + { + return submit([handle = handle(), flags = flags(), size]() { + return checkRights(flags, Operation::SetSize).and_then([&]() -> FsResult { + if (size > OffsetMax) + return refuse(FsErrorCode::FileTooLarge); + return succeededOr(detail::retryOnInterrupt([&] { + return ::ftruncate(handle->get(), static_cast(size)); + }), + "ftruncate"); + }); + }); + } + + async::Task> setTimes(NewTimestamp accessed, NewTimestamp modified) override + { + return submit([handle = handle(), flags = flags(), accessed, modified]() { + return checkRights(flags, Operation::SetTimes) + .and_then([&] { return timespecsOf(accessed, modified); }) + .and_then([&](std::array<::timespec, 2> const& times) { + return succeededOr(::futimens(handle->get(), times.data()), "futimens"); + }); + }); + } + + async::Task> stat() override + { + return submit([handle = handle(), flags = flags()]() { + return checkRights(flags, Operation::Stat) + .and_then([&] { return statHandle(handle->get()); }) + .transform([](struct ::stat const& status) { return statOf(status); }); + }); + } + + async::Task> metadataHash() override + { + return submit([context = context(), handle = handle(), flags = flags()]() { + return checkRights(flags, Operation::MetadataHash) + .and_then([&] { return statHandle(handle->get()); }) + .transform([&](struct ::stat const& status) { return hashOf(*context, status); }); + }); + } + + async::Task>> readDirectory() override + { + return submit([context = context(), handle = handle(), flags = flags(), type = objectType()]() { + return checkRights(flags, Operation::ReadDirectory) + .and_then([&] { return detail::requireDirectory(type); }) + .and_then([&] { return detail::openDirectoryReader(handle->get(), *context->blocking); }) + .transform([&](std::shared_ptr reader) + -> std::unique_ptr { + return std::make_unique(context, std::move(reader)); + }); + }); + } + + async::Task>> openAt(SymlinkPolicy policy, + std::string path, + OpenFlags open, + DescriptorFlags childFlags) override + { + return submit([context = context(), + handle = handle(), + flags = flags(), + type = objectType(), + policy, + path = std::move(path), + open, + childFlags]() -> FsResult> { + // O_CREAT | O_EXCL never follows a final link: a dangling one is Exist rather than + // created through. + auto const exclusive = + hasFlag(open, OpenFlags::Create) && hasFlag(open, OpenFlags::Exclusive); + auto const resolved = checkRights(flags, Operation::OpenAt) + .and_then([&] { return checkOpenRights(flags, open, childFlags); }) + .and_then([&] { return detail::requireDirectory(type); }) + .and_then([&] { + return resolve(handle->get(), + path, + *context, + exclusive ? SymlinkPolicy::NoFollow : policy, + TrailingSlashOnLink::Follow); + }); + if (!resolved) + return std::unexpected { resolved.error() }; + // A link not followed is Loop, decided here as Windows decides it, before the kernel + // answers in its own words: FreeBSD's O_NOFOLLOW says EMLINK, which is TooManyLinks. + if (!exclusive && resolved->kind == EntryKind::SymbolicLink) + return refuse(FsErrorCode::Loop); + auto openFlags = openFlagsOf(open, childFlags); + if (!openFlags) + return std::unexpected { openFlags.error() }; + if (resolved->finalComponent == FinalComponent::Directory && !resolved->name.empty()) + { + // `name/` opens nothing but a directory, and creates none: the kernel is handed + // the name without its `/`, so the walk's answer is enforced here. + if (resolved->kind == EntryKind::Missing && hasFlag(open, OpenFlags::Create)) + return refuse(FsErrorCode::NotDirectory); + *openFlags |= O_DIRECTORY; + } + auto const directory = resolved->directory(); + auto const& name = resolved->name; + auto child = openEntry(directory, name, *openFlags); + if (!child) + return std::unexpected { child.error() }; + auto const opened = child->get(); + auto const status = statHandle(opened); + if (!status) + return std::unexpected { status.error() }; + auto const childType = typeOfMode(status->st_mode); + // Create opens no directory: Linux refuses it with EISDIR, but macOS opens one + // `O_CREAT | O_RDONLY` without a word. The handle closes here, unshared. + if (hasFlag(open, OpenFlags::Create) && !hasFlag(open, OpenFlags::Directory) + && childType == DescriptorType::Directory) + return refuse(FsErrorCode::IsDirectory); + auto appendHandle = SharedHandle {}; + if (hasFlag(childFlags, DescriptorFlags::Write) && childType == DescriptorType::RegularFile) + { + // The append handle writes with the same integrity as the first. + auto second = detail::openAppendHandle( + directory, + name, + opened, + *openFlags & ~(O_ACCMODE | O_CREAT | O_EXCL | O_TRUNC | O_DIRECTORY)); + if (!second) + return std::unexpected { second.error() }; + if (second->get() != platform::InvalidHandle) + appendHandle = detail::shareHandle(std::move(*second), *context->blocking); + } + return std::make_unique( + context, + detail::shareHandle(std::move(*child), *context->blocking), + std::move(appendHandle), + grantedFlags(childType, childFlags), + childType); + }); + } + + async::Task> createDirectoryAt(std::string path) override + { + return submit([context = context(), + handle = handle(), + flags = flags(), + type = objectType(), + path = std::move(path)]() { + return checkRights(flags, Operation::CreateDirectoryAt) + .and_then([&] { return detail::requireDirectory(type); }) + .and_then([&] { + return resolve(handle->get(), + path, + *context, + SymlinkPolicy::NoFollow, + TrailingSlashOnLink::Follow); + }) + .and_then([](Resolved resolved) { + return vacant(std::move(resolved), DescriptorType::Directory); + }) + .and_then([](Resolved const& resolved) { + return succeededOr( + ::mkdirat(resolved.directory(), resolved.name.c_str(), NewDirectoryMode), + "mkdirat"); + }); + }); + } + + async::Task> statAt(SymlinkPolicy policy, std::string path) override + { + return submit([context = context(), + handle = handle(), + flags = flags(), + type = objectType(), + policy, + path = std::move(path)]() { + return checkRights(flags, Operation::StatAt) + .and_then([&] { return detail::requireDirectory(type); }) + .and_then([&] { + return resolve(handle->get(), path, *context, policy, TrailingSlashOnLink::Follow); + }) + .and_then([](Resolved const& resolved) { + return statEntry(resolved.directory(), resolved.name); + }) + .transform([](struct ::stat const& status) { return statOf(status); }); + }); + } + + async::Task> setTimesAt(SymlinkPolicy policy, + std::string path, + NewTimestamp accessed, + NewTimestamp modified) override + { + return submit([context = context(), + handle = handle(), + flags = flags(), + type = objectType(), + policy, + path = std::move(path), + accessed, + modified]() { + return checkRights(flags, Operation::SetTimesAt) + .and_then([&] { return detail::requireDirectory(type); }) + .and_then([&] { + return resolve(handle->get(), path, *context, policy, TrailingSlashOnLink::Follow); + }) + .and_then([&](Resolved const& resolved) -> FsResult { + auto const times = timespecsOf(accessed, modified); + if (!times) + return std::unexpected { times.error() }; + // The directory itself is named by `.` beneath its own handle, which may be a + // path handle (O_PATH) that futimens refuses; `.` is never a link. + auto const* const name = resolved.name.empty() ? "." : resolved.name.c_str(); + return succeededOr( + ::utimensat(resolved.directory(), name, times->data(), AT_SYMLINK_NOFOLLOW), + "utimensat"); + }); + }); + } + + async::Task> linkAt(SymlinkPolicy policy, + std::string oldPath, + IDescriptor* newDirectory, + std::string newPath) override + { + auto const target = sameSystemTarget(newDirectory); + return submit([context = context(), + handle = handle(), + flags = flags(), + type = objectType(), + policy, + oldPath = std::move(oldPath), + target, + newPath = std::move(newPath)]() -> FsResult { + if (auto checked = checkRights(flags, Operation::LinkAt); !checked) + return checked; + if (policy == SymlinkPolicy::Follow) + return refuse(FsErrorCode::Invalid); + if (!target) + return std::unexpected { target.error() }; + if (auto checked = checkRights(target->flags, Operation::LinkAt); !checked) + return checked; + if (auto checked = detail::requireDirectory(type).and_then( + [&] { return detail::requireDirectory(target->type); }); + !checked) + return checked; + auto const from = resolve( + handle->get(), oldPath, *context, SymlinkPolicy::NoFollow, TrailingSlashOnLink::Follow); + if (!from) + return std::unexpected { from.error() }; + if (from->name.empty()) + return refuse(FsErrorCode::NotPermitted); + if (from->kind == EntryKind::Missing) + return refuse(FsErrorCode::NoEntry); + auto const to = resolve(target->handle->get(), + newPath, + *context, + SymlinkPolicy::NoFollow, + TrailingSlashOnLink::Follow) + .and_then([](Resolved resolved) { + return vacant(std::move(resolved), DescriptorType::RegularFile); + }); + if (!to) + return std::unexpected { to.error() }; + return succeededOr( + ::linkat(from->directory(), from->name.c_str(), to->directory(), to->name.c_str(), 0), + "linkat"); + }); + } + + async::Task> readlinkAt(std::string path) override + { + return submit([context = context(), + handle = handle(), + flags = flags(), + type = objectType(), + path = std::move(path)]() { + return checkRights(flags, Operation::ReadlinkAt) + .and_then([&] { return detail::requireDirectory(type); }) + .and_then([&] { + return resolve(handle->get(), + path, + *context, + SymlinkPolicy::NoFollow, + TrailingSlashOnLink::Follow); + }) + .and_then([](Resolved const& resolved) -> FsResult { + if (resolved.name.empty()) + return refuse(FsErrorCode::Invalid); + return detail::readLinkAt(resolved.directory(), resolved.name); + }); + }); + } + + async::Task> removeDirectoryAt(std::string path) override + { + return submit([context = context(), + handle = handle(), + flags = flags(), + type = objectType(), + path = std::move(path)]() { + return checkRights(flags, Operation::RemoveDirectoryAt) + .and_then([&] { return detail::requireDirectory(type); }) + .and_then([&] { + return resolve(handle->get(), + path, + *context, + SymlinkPolicy::NoFollow, + TrailingSlashOnLink::Refuse); + }) + .and_then([](Resolved const& resolved) -> FsResult { + if (resolved.name.empty()) + return refuse(FsErrorCode::Invalid); + return succeededOr( + ::unlinkat(resolved.directory(), resolved.name.c_str(), AT_REMOVEDIR), + "unlinkat"); + }); + }); + } + + async::Task> renameAt(std::string oldPath, + IDescriptor* newDirectory, + std::string newPath) override + { + auto const target = sameSystemTarget(newDirectory); + return submit([context = context(), + handle = handle(), + flags = flags(), + type = objectType(), + oldPath = std::move(oldPath), + target, + newPath = std::move(newPath)]() -> FsResult { + if (auto checked = checkRights(flags, Operation::RenameAt); !checked) + return checked; + if (!target) + return std::unexpected { target.error() }; + if (auto checked = checkRights(target->flags, Operation::RenameAt); !checked) + return checked; + if (auto checked = detail::requireDirectory(type).and_then( + [&] { return detail::requireDirectory(target->type); }); + !checked) + return checked; + auto const from = resolve( + handle->get(), oldPath, *context, SymlinkPolicy::NoFollow, TrailingSlashOnLink::Refuse); + if (!from) + return std::unexpected { from.error() }; + auto const to = resolve(target->handle->get(), + newPath, + *context, + SymlinkPolicy::NoFollow, + TrailingSlashOnLink::Refuse); + if (!to) + return std::unexpected { to.error() }; + if (from->kind == EntryKind::Missing && !from->name.empty()) + return refuse(FsErrorCode::NoEntry); + if (from->name.empty() || to->name.empty()) + return refuse(FsErrorCode::Invalid); + // `to/` names a directory: the kernel sees the name without its `/`. + if (from->kind != EntryKind::Directory && to->finalComponent == FinalComponent::Directory) + return refuse(FsErrorCode::NotDirectory); + return succeededOr( + ::renameat(from->directory(), from->name.c_str(), to->directory(), to->name.c_str()), + "renameat"); + }); + } + + async::Task> symlinkAt(std::string target, std::string newPath) override + { + return submit([context = context(), + handle = handle(), + flags = flags(), + type = objectType(), + target = std::move(target), + newPath = std::move(newPath)]() { + return checkRights(flags, Operation::SymlinkAt) + .and_then([&] { return detail::requireDirectory(type); }) + .and_then([&] { return detail::checkSymlinkTarget(target, *context->policy); }) + .and_then([&] { + return resolve(handle->get(), + newPath, + *context, + SymlinkPolicy::NoFollow, + TrailingSlashOnLink::Follow); + }) + .and_then([](Resolved resolved) { + return vacant(std::move(resolved), DescriptorType::SymbolicLink); + }) + .and_then([&](Resolved const& resolved) { + return succeededOr( + ::symlinkat(target.c_str(), resolved.directory(), resolved.name.c_str()), + "symlinkat"); + }); + }); + } + + async::Task> unlinkFileAt(std::string path) override + { + return submit([context = context(), + handle = handle(), + flags = flags(), + type = objectType(), + path = std::move(path)]() { + return checkRights(flags, Operation::UnlinkFileAt) + .and_then([&] { return detail::requireDirectory(type); }) + .and_then([&] { + return resolve(handle->get(), + path, + *context, + SymlinkPolicy::NoFollow, + TrailingSlashOnLink::Refuse); + }) + .and_then([](Resolved const& resolved) -> FsResult { + // A directory is IsDirectory on every system: macOS and the BSDs would answer + // EPERM for it, where Linux says EISDIR. + if (resolved.name.empty() || resolved.kind == EntryKind::Directory) + return refuse(FsErrorCode::IsDirectory); + return succeededOr(::unlinkat(resolved.directory(), resolved.name.c_str(), 0), + "unlinkat"); + }); + }); + } + + async::Task> metadataHashAt(SymlinkPolicy policy, std::string path) override + { + return submit([context = context(), + handle = handle(), + flags = flags(), + type = objectType(), + policy, + path = std::move(path)]() { + return checkRights(flags, Operation::MetadataHashAt) + .and_then([&] { return detail::requireDirectory(type); }) + .and_then([&] { + return resolve(handle->get(), path, *context, policy, TrailingSlashOnLink::Follow); + }) + .and_then([](Resolved const& resolved) { + return statEntry(resolved.directory(), resolved.name); + }) + .transform([&](struct ::stat const& status) { return hashOf(*context, status); }); + }); + } + + async::Task> isSameObject(IDescriptor* other) override + { + return submit([handle = handle(), candidate = sameObjectCandidate(other)]() -> FsResult { + if (!candidate) + return std::unexpected { candidate.error() }; + if (!*candidate) + return false; + return statHandle(handle->get()).and_then([&](struct ::stat const& mine) { + return statHandle((*candidate)->handle->get()) + .transform([&](struct ::stat const& theirs) { + return mine.st_dev == theirs.st_dev && mine.st_ino == theirs.st_ino; + }); + }); + }); + } + + private: + SharedHandle _appendHandle; ///< The second handle `append` writes through, where one is needed. + /// Held by an append that finds the end itself; shared with the jobs, which may outlive the + /// descriptor. + std::shared_ptr _appendLock; + }; + + class PosixFileSystem final: public IDescriptorFileSystem + { + public: + explicit PosixFileSystem(SharedContext context): _context { std::move(context) } {} + + async::Task>> openPreopen(std::filesystem::path hostDirectory, + DescriptorFlags flags) override + { + return async::offload(_context->home, + _context->blocking, + [context = _context, + path = std::move(hostDirectory), + flags]() -> FsResult> { + if (hasFlag(flags, DescriptorFlags::Write)) + return refuse(FsErrorCode::IsDirectory); + // The host chose this directory, so the kernel resolves its path; + // O_PATH is not used, because the preopen itself is read and stat'ed. + auto const opened = detail::retryOnInterrupt([&] { + return ::open(path.c_str(), + O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOCTTY); + }); + if (opened < 0) + return detail::errnoError("open"); + return std::make_unique( + context, + detail::shareHandle(UniqueHandle { opened }, *context->blocking), + SharedHandle {}, + grantedFlags(DescriptorType::Directory, flags), + DescriptorType::Directory); + }); + } + + private: + SharedContext _context; + }; + +} // namespace + +FsResult> makeNativeDescriptorFileSystem( + async::IExecutor& home, + async::IExecutor& blocking, + platform::IWallClock const& wallClock, + IRandom& random, + NativeFileSystemOptions options) +{ + return detail::checkOptions(options).transform([&] -> std::unique_ptr { + return std::make_unique(std::make_shared( + home, blocking, wallClock, random, options, KernelSeparators, nullptr)); + }); +} + +} // namespace core::fs diff --git a/src/core/fs/posix/PosixDescriptor_test.cpp b/src/core/fs/posix/PosixDescriptor_test.cpp new file mode 100644 index 00000000..c95b13ba --- /dev/null +++ b/src/core/fs/posix/PosixDescriptor_test.cpp @@ -0,0 +1,76 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// What only the POSIX descriptors owe: an open of a FIFO never waits for its other end, while a +// regular file is opened blocking (a lease is broken and waited for rather than refused); a name +// that is not UTF-8, which only a POSIX file system holds, is refused for its entry alone. +#include +#include +#include + +#include + +#include + +#include +#include +#include +#include + +#include +#include + +using core::fs::DescriptorFlags; +using core::fs::DescriptorType; +using core::fs::FsErrorCode; +using core::fs::OpenFlags; +using core::fs::SymlinkPolicy; +using core::fs::test::DescriptorFixture; +using core::fs::test::outcomeOf; + +TEST_CASE("posix: a FIFO with no other end opens without waiting", "[fs][native]") +{ + auto fixture = DescriptorFixture::createNative(); + REQUIRE(::mkfifo((fixture.hostDirectory() / "fifo").c_str(), 0600) == 0); + + // Reading opens at once; writing has no reader, which O_NONBLOCK reports as ENXIO. + auto reader = fixture.run( + fixture.root().openAt(SymlinkPolicy::NoFollow, "fifo", OpenFlags::None, DescriptorFlags::Read)); + REQUIRE(reader.has_value()); + CHECK(fixture.run((*reader)->type()) == DescriptorType::Fifo); + reader->reset(); + CHECK(outcomeOf(fixture.run(fixture.root().openAt( + SymlinkPolicy::NoFollow, "fifo", OpenFlags::None, DescriptorFlags::Write))) + == FsErrorCode::NoSuchDevice); +} + +TEST_CASE("posix: a name that is not UTF-8 is IllegalByteSequence, and the stream goes on", + "[fs][native][directory]") +{ + auto fixture = DescriptorFixture::createNative(); + fixture.createFile("before", "x"); + // Through the host, which takes any bytes; a file system that refuses such a name (APFS answers + // EILSEQ) cannot hold the case. + auto const host = (fixture.hostDirectory() / "bad-").native() + "\xff\xfe"; + auto const made = ::open(host.c_str(), O_CREAT | O_EXCL | O_WRONLY | O_CLOEXEC, 0600); + if (made < 0) + SKIP("the file system refuses a name that is not UTF-8 (errno " << errno << ")"); + ::close(made); + fixture.createFile("after", "x"); + + auto stream = fixture.run(fixture.root().readDirectory()); + REQUIRE(stream.has_value()); + auto const answers = fixture.readEntries(**stream, 16); + REQUIRE(answers.size() == 3); + auto names = std::vector {}; + auto refused = std::vector {}; + for (auto const& answer: answers) + { + if (answer) + names.push_back(answer->name); + else + refused.push_back(answer.error().code); + } + std::ranges::sort(names); + CHECK(names == std::vector { "after", "before" }); + CHECK(refused == std::vector { FsErrorCode::IllegalByteSequence }); +} diff --git a/src/core/fs/posix/PosixPathWalk.cpp b/src/core/fs/posix/PosixPathWalk.cpp new file mode 100644 index 00000000..7cb99336 --- /dev/null +++ b/src/core/fs/posix/PosixPathWalk.cpp @@ -0,0 +1,183 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The component walker of every POSIX system: each directory is opened beneath the one before it +// with O_NOFOLLOW and held by its descriptor, so the walk never names a directory by a path again. +// A component the open refuses as a link (an errno of noFollowSymlinkErrnos(), or ENOTDIR where +// O_PATH opened the link and O_DIRECTORY refused it) is read with readlinkat and spliced by the +// shared walk, which also owns the hop limit and `..` at the root. +#include + +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace core::fs::detail +{ + +namespace +{ + + /// @return Whether @p error is how this system refuses to open a link it was told not to follow. + bool refusedAsLink(int error) noexcept + { + return error == ENOTDIR + || std::ranges::find(noFollowSymlinkErrnos(), error) != noFollowSymlinkErrnos().end(); + } + + EntryKind kindOf(::mode_t mode) noexcept + { + if (S_ISDIR(mode)) + return EntryKind::Directory; + if (S_ISLNK(mode)) + return EntryKind::SymbolicLink; + return EntryKind::Other; + } + +} // namespace + +FsResult readLinkAt(int directory, std::string const& name) +{ + auto target = std::string(256, '\0'); + while (true) + { + auto const length = ::readlinkat(directory, name.c_str(), target.data(), target.size()); + if (length < 0) + return errnoError("readlinkat"); + if (static_cast(length) < target.size()) + { + target.resize(static_cast(length)); + return target; + } + target.resize(target.size() * 2); + } +} + +PosixCursor::PosixCursor(int root, IBeneathOpener const* opener) noexcept: _root { root }, _opener { opener } +{ +} + +bool PosixCursor::atRoot() const noexcept +{ + return _entered.empty(); +} + +int PosixCursor::current() const noexcept +{ + return _entered.empty() ? _root : _entered.back().get(); +} + +FsResult PosixCursor::enter(std::string const& name) +{ + auto const opened = + retryOnInterrupt([&] { return ::openat(current(), name.c_str(), walkDirectoryOpenFlags()); }); + if (opened >= 0) + { + _entered.emplace_back(opened); + return EntryKind::Directory; + } + auto const failure = errno; + if (!refusedAsLink(failure)) + return std::unexpected { fsErrorFromSystemCode(failure, "openat") }; + // ENOTDIR is a link only where it is one: a file in the way stays NotDirectory. + return inspect(name).and_then([failure](EntryKind kind) -> FsResult { + switch (kind) + { + case EntryKind::Missing: return std::unexpected { fsErrorFromSystemCode(ENOENT, "openat") }; + // A directory here changed under the walk since the open refused it: reported as a + // link, whose read answers Invalid, so the walk looks at the name again. + case EntryKind::Directory: + case EntryKind::SymbolicLink: return EntryKind::SymbolicLink; + case EntryKind::Other: break; + } + return std::unexpected { fsErrorFromSystemCode(failure, "openat") }; + }); +} + +void PosixCursor::leave() +{ + _entered.pop_back(); +} + +FsResult PosixCursor::inspect(std::string const& name) +{ + struct ::stat status {}; + if (::fstatat(current(), name.c_str(), &status, AT_SYMLINK_NOFOLLOW) != 0) + { + if (errno == ENOENT) + return EntryKind::Missing; + return errnoError("fstatat"); + } + return kindOf(status.st_mode); +} + +FsResult PosixCursor::readLink(std::string const& name) +{ + return readLinkAt(current(), name); +} + +FsResult PosixCursor::shortcut(std::span components) +{ + if (_opener == nullptr) + return Shortcut::Declined; + auto path = std::string {}; + for (auto const& component: components) + { + if (!path.empty()) + path += '/'; + path += component; + } + return _opener->openDirectoryBeneath(_root, path).transform([this](UniqueHandle opened) { + if (opened.get() == platform::InvalidHandle) + return Shortcut::Declined; + _entered.clear(); + _entered.push_back(std::move(opened)); + return Shortcut::Taken; + }); +} + +void PosixCursor::restart() +{ + _entered.clear(); +} + +UniqueHandle PosixCursor::release() noexcept +{ + if (_entered.empty()) + return UniqueHandle { platform::InvalidHandle }; + auto top = std::move(_entered.back()); + _entered.clear(); + return top; +} + +FsResult resolveBeneath(platform::NativeHandle root, + PathPlan plan, + WalkRules const& rules, + IBeneathOpener const* opener) +{ + auto cursor = PosixCursor { root, opener }; + return walkBeneath(cursor, std::move(plan), rules).transform([&cursor, root](WalkEnd end) { + return Resolved { .held = cursor.release(), + .root = root, + .name = std::move(end.name), + .kind = end.kind, + .finalComponent = end.finalComponent }; + }); +} + +} // namespace core::fs::detail diff --git a/src/core/fs/posix/PosixPathWalk.hpp b/src/core/fs/posix/PosixPathWalk.hpp new file mode 100644 index 00000000..8fca6ecf --- /dev/null +++ b/src/core/fs/posix/PosixPathWalk.hpp @@ -0,0 +1,71 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// The POSIX side of @c walkBeneath: a cursor over directory file descriptors, each opened beneath +/// the one before it without following, so a directory swapped for a link between two components +/// is met as a link, never crossed. The one exception is the shortcut, where an @c IBeneathOpener +/// is given: the components before the final name go to the kernel as one path relative to the +/// root, which `openat2(RESOLVE_BENEATH)` resolves without leaving it. Private to the fs module. + +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace core::fs::detail +{ + +/// The `openat` flags a walk opens each directory with: `O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC`, +/// and `O_PATH` where the system has it, so a directory the process may search but not read is +/// still walked through. Defined by the `BeneathDefault.cpp` the build compiles. +/// @return The flags. +[[nodiscard]] int walkDirectoryOpenFlags() noexcept; + +/// A cursor over directory file descriptors: the root, borrowed, and a stack of the directories +/// entered beneath it, each held open by this cursor and closed where it is left. +class CORE_FS_API PosixCursor final: public IBeneathCursor +{ + public: + /// @param root The directory the walk starts on; borrowed, and must outlive the cursor. + /// @param opener The kernel's beneath step, offered on the root, or null. + PosixCursor(int root, IBeneathOpener const* opener) noexcept; + + PosixCursor(PosixCursor const&) = delete; + PosixCursor(PosixCursor&&) = delete; + PosixCursor& operator=(PosixCursor const&) = delete; + PosixCursor& operator=(PosixCursor&&) = delete; + ~PosixCursor() override = default; + + [[nodiscard]] bool atRoot() const noexcept override; + [[nodiscard]] FsResult enter(std::string const& name) override; + void leave() override; + [[nodiscard]] FsResult inspect(std::string const& name) override; + [[nodiscard]] FsResult readLink(std::string const& name) override; + [[nodiscard]] FsResult shortcut(std::span components) override; + void restart() override; + + /// @return The directory the cursor stands on, borrowed. + [[nodiscard]] int current() const noexcept; + + /// Hands over the directory the cursor stands on, where it is not the root. + /// @return It; one holding no handle where the cursor stands on the root. + [[nodiscard]] UniqueHandle release() noexcept; + + private: + int _root; + IBeneathOpener const* _opener; + std::vector _entered; +}; + +/// @param directory A directory. +/// @param name A name in it. +/// @return The link's target; `Invalid` where @p name is no link. +[[nodiscard]] FsResult readLinkAt(int directory, std::string const& name); + +} // namespace core::fs::detail diff --git a/src/core/fs/posix/PosixPathWalk_test.cpp b/src/core/fs/posix/PosixPathWalk_test.cpp new file mode 100644 index 00000000..878458da --- /dev/null +++ b/src/core/fs/posix/PosixPathWalk_test.cpp @@ -0,0 +1,208 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The component walker against a directory swapped for an outward link at a chosen step, not by +// timing: a cursor wrapped around the real one makes the swap just before or just after it enters +// the directory, or just before it reads the link back. Whichever step it lands on, the walk either +// keeps the directory it holds or meets the link and refuses it. +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +using core::fs::FsErrorCode; +using core::fs::FsResult; +using core::fs::SymlinkPolicy; +using core::fs::detail::EntryKind; +using core::fs::detail::IBeneathCursor; +using core::fs::detail::PosixCursor; +using core::fs::detail::Shortcut; +using core::fs::detail::UniqueHandle; +using core::fs::detail::WalkRules; + +namespace +{ + +/// `/root/d/inside.txt` holding "inside", and the decoy `/inside.txt` holding "outside", +/// where `d -> ../` would lead; the root held open. +class SwapTree +{ + public: + SwapTree() + { + std::filesystem::create_directories(rootPath() / "d"); + write(rootPath() / "d" / "inside.txt", "inside"); + write(_directory.path() / "inside.txt", "outside"); + _root = UniqueHandle { ::open(rootPath().c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC) }; + if (_root.get() < 0) + throw std::runtime_error { "SwapTree: the root did not open" }; + } + + [[nodiscard]] int root() const noexcept { return _root.get(); } + + /// Puts the link `d -> ../` where the directory was. + void swapInLink() const + { + std::filesystem::rename(rootPath() / "d", rootPath() / "d.directory"); + std::filesystem::create_directory_symlink("../", rootPath() / "d"); + } + + /// Puts the directory back where the link is. + void swapInDirectory() const + { + std::filesystem::remove(rootPath() / "d"); + std::filesystem::rename(rootPath() / "d.directory", rootPath() / "d"); + } + + /// @return What @p name holds beneath @p directory, read without following. + [[nodiscard]] static std::string readAt(int directory, std::string const& name) + { + auto const file = + UniqueHandle { ::openat(directory, name.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC) }; + auto text = std::string(64, '\0'); + auto const length = ::read(file.get(), text.data(), text.size()); + text.resize(length < 0 ? 0 : static_cast(length)); + return text; + } + + private: + [[nodiscard]] std::filesystem::path rootPath() const { return _directory.path() / "root"; } + + static void write(std::filesystem::path const& path, std::string const& text) + { + auto stream = std::ofstream { path }; + stream << text; + } + + core::testing::ScopedTempDir _directory { "core-cpp-fs-walk" }; + UniqueHandle _root { -1 }; +}; + +/// When a hook runs, relative to the cursor's steps. +struct Hooks +{ + std::function beforeEnter; + std::function afterEnter; + std::function beforeReadLink; +}; + +/// The real cursor, with a hook at each step. +class HookedCursor final: public IBeneathCursor +{ + public: + HookedCursor(PosixCursor& inner, Hooks hooks): _inner { &inner }, _hooks { std::move(hooks) } {} + + [[nodiscard]] bool atRoot() const noexcept override { return _inner->atRoot(); } + + [[nodiscard]] FsResult enter(std::string const& name) override + { + run(_hooks.beforeEnter); + auto entered = _inner->enter(name); + run(_hooks.afterEnter); + return entered; + } + + void leave() override { _inner->leave(); } + + [[nodiscard]] FsResult inspect(std::string const& name) override + { + return _inner->inspect(name); + } + + [[nodiscard]] FsResult readLink(std::string const& name) override + { + run(_hooks.beforeReadLink); + return _inner->readLink(name); + } + + [[nodiscard]] FsResult shortcut(std::span components) override + { + return _inner->shortcut(components); + } + + void restart() override { _inner->restart(); } + + private: + /// Runs @p hook once, then forgets it. + static void run(std::function& hook) + { + if (hook) + std::exchange(hook, nullptr)(); + } + + PosixCursor* _inner; + Hooks _hooks; +}; + +WalkRules rules() +{ + return WalkRules { .policy = &core::fs::posixPathPolicy(), + .finalPolicy = SymlinkPolicy::Follow, + .onLink = core::fs::detail::TrailingSlashOnLink::Follow, + .maxSymlinkHops = core::fs::DefaultMaxSymlinkHops, + .kernelSeparators = "/" }; +} + +core::fs::detail::PathPlan plan(std::string const& path) +{ + return core::fs::detail::planRelativePath(path, core::fs::posixPathPolicy()).value(); +} + +} // namespace + +TEST_CASE("walker: a directory swapped for a link before it is entered is met as the link", "[fs][escape]") +{ + auto const tree = SwapTree {}; + auto inner = PosixCursor { tree.root(), nullptr }; + auto cursor = HookedCursor { + inner, Hooks { .beforeEnter = [&] { tree.swapInLink(); }, .afterEnter = {}, .beforeReadLink = {} } + }; + + auto const walked = core::fs::detail::walkBeneath(cursor, plan("d/inside.txt"), rules()); + REQUIRE_FALSE(walked.has_value()); + CHECK(walked.error().code == FsErrorCode::NotPermitted); +} + +TEST_CASE("walker: a directory swapped after it was entered stays the one the walk holds", "[fs][escape]") +{ + auto const tree = SwapTree {}; + auto inner = PosixCursor { tree.root(), nullptr }; + auto cursor = HookedCursor { + inner, Hooks { .beforeEnter = {}, .afterEnter = [&] { tree.swapInLink(); }, .beforeReadLink = {} } + }; + + auto const walked = core::fs::detail::walkBeneath(cursor, plan("d/inside.txt"), rules()); + REQUIRE(walked.has_value()); + CHECK(walked->name == "inside.txt"); + CHECK(walked->kind == EntryKind::Other); + CHECK(SwapTree::readAt(inner.current(), walked->name) == "inside"); +} + +TEST_CASE("walker: a link that is a directory again when it is read is entered after all", "[fs][escape]") +{ + auto const tree = SwapTree {}; + auto inner = PosixCursor { tree.root(), nullptr }; + auto cursor = HookedCursor { inner, + Hooks { .beforeEnter = [&] { tree.swapInLink(); }, + .afterEnter = {}, + .beforeReadLink = [&] { tree.swapInDirectory(); } } }; + + auto const walked = core::fs::detail::walkBeneath(cursor, plan("d/inside.txt"), rules()); + REQUIRE(walked.has_value()); + CHECK(SwapTree::readAt(inner.current(), walked->name) == "inside"); +} diff --git a/src/core/fs/posix/PosixSystem.cpp b/src/core/fs/posix/PosixSystem.cpp new file mode 100644 index 00000000..0f7be5bb --- /dev/null +++ b/src/core/fs/posix/PosixSystem.cpp @@ -0,0 +1,134 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The descriptor calls of Linux, the BSDs and any POSIX system but Apple's: the `st_atim` family of +// times, `posix_fadvise`, `fdatasync` and `fsync`. A write-integrity mode the system lacks (FreeBSD +// has no `O_RSYNC`) is a row whose flag is 0, chosen by the macro test inside the data. +#include + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace core::fs::detail +{ + +namespace +{ + + FileTime fileTimeOf(struct ::timespec const& time) noexcept + { + return FileTime { .seconds = time.tv_sec, .nanoseconds = static_cast(time.tv_nsec) }; + } + + struct AdviceRow + { + Advice advice; + int systemAdvice; + }; + + constexpr auto AdviceRows = std::to_array({ + { .advice = Advice::Normal, .systemAdvice = POSIX_FADV_NORMAL }, + { .advice = Advice::Sequential, .systemAdvice = POSIX_FADV_SEQUENTIAL }, + { .advice = Advice::Random, .systemAdvice = POSIX_FADV_RANDOM }, + { .advice = Advice::WillNeed, .systemAdvice = POSIX_FADV_WILLNEED }, + { .advice = Advice::DontNeed, .systemAdvice = POSIX_FADV_DONTNEED }, + { .advice = Advice::NoReuse, .systemAdvice = POSIX_FADV_NOREUSE }, + }); + + struct SyncFlagRow + { + DescriptorFlags flag; + int openFlag; ///< 0 where this system has no such mode. + }; + + constexpr auto SyncFlagRows = std::to_array({ + { .flag = DescriptorFlags::FileIntegritySync, .openFlag = O_SYNC }, +#ifdef O_DSYNC + { .flag = DescriptorFlags::DataIntegritySync, .openFlag = O_DSYNC }, +#else + { .flag = DescriptorFlags::DataIntegritySync, .openFlag = 0 }, +#endif +#ifdef O_RSYNC + { .flag = DescriptorFlags::RequestedWriteSync, .openFlag = O_RSYNC }, +#else + { .flag = DescriptorFlags::RequestedWriteSync, .openFlag = 0 }, +#endif + }); + +} // namespace + +StatTimes timesOf(struct ::stat const& status) noexcept +{ + return StatTimes { .accessed = fileTimeOf(status.st_atim), + .modified = fileTimeOf(status.st_mtim), + .statusChanged = fileTimeOf(status.st_ctim) }; +} + +FsResult adviseRange(int handle, std::uint64_t offset, std::uint64_t length, Advice advice) +{ + constexpr auto OffsetMax = static_cast(std::numeric_limits::max()); + if (offset > OffsetMax || length > OffsetMax) + return refuse(FsErrorCode::Invalid); + auto const row = std::ranges::find(AdviceRows, advice, &AdviceRow::advice); + if (row == AdviceRows.end()) + return refuse(FsErrorCode::Invalid); + // posix_fadvise answers the error number rather than setting errno. + if (auto const error = ::posix_fadvise( + handle, static_cast(offset), static_cast(length), row->systemAdvice); + error != 0) + return std::unexpected { fsErrorFromSystemCode(error, "posix_fadvise") }; + return {}; +} + +FsResult syncAll(int handle) +{ + if (retryOnInterrupt([handle] { return ::fsync(handle); }) != 0) + return errnoError("fsync"); + return {}; +} + +FsResult syncData(int handle) +{ + // Where fdatasync fails (a file system without it answers EINVAL), fsync, as SQLite and libuv do. + if (retryOnInterrupt([handle] { return ::fdatasync(handle); }) == 0) + return {}; + return syncAll(handle); +} + +FsResult syncOpenFlags(DescriptorFlags flags) +{ + auto openFlags = 0; + for (auto const& row: SyncFlagRows) + { + if (!hasFlag(flags, row.flag)) + continue; + if (row.openFlag == 0) + return refuse(FsErrorCode::Unsupported); + openFlags |= row.openFlag; + } + return openFlags; +} + +FsError openFailure(int, std::string const&, int flags, int error) +{ + // A link that became the final component after the walk looked: FreeBSD's O_NOFOLLOW answers + // EMLINK, which no other open sends, where the rest say ELOOP. + if ((flags & O_NOFOLLOW) != 0 + && std::ranges::find(noFollowSymlinkErrnos(), error) != noFollowSymlinkErrnos().end()) + return FsError { .code = FsErrorCode::Loop, .systemCode = error, .context = "openat" }; + return fsErrorFromSystemCode(error, "openat"); +} + +} // namespace core::fs::detail diff --git a/src/core/fs/posix/PosixSystem.hpp b/src/core/fs/posix/PosixSystem.hpp new file mode 100644 index 00000000..1631654b --- /dev/null +++ b/src/core/fs/posix/PosixSystem.hpp @@ -0,0 +1,133 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// The calls in which POSIX systems differ, each defined once per system by a source the build +/// chooses (`posix/PosixSystem.cpp` or `bsd/PosixSystem.cpp`; `linux/Append.cpp` or +/// `posix/Append.cpp`), so the descriptor itself names no system. Private to the fs module. + +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace core::fs::detail +{ + +/// @param call The system call that failed. +/// @return `errno`, classified, naming @p call. +[[nodiscard]] inline std::unexpected errnoError(char const* call) +{ + return std::unexpected { fsErrorFromSystemCode(errno, call) }; +} + +/// Calls @p call again for as long as a signal interrupts it. +/// @param call A system call that answers -1 and sets `errno` on failure. +/// @return What its last attempt answered. +template +[[nodiscard]] auto retryOnInterrupt(F call) +{ + auto result = call(); + while (result == -1 && errno == EINTR) + result = call(); + return result; +} + +/// The three times of a `struct stat`. +struct StatTimes +{ + FileTime accessed; ///< `st_atim`. + FileTime modified; ///< `st_mtim`. + FileTime statusChanged; ///< `st_ctim`. +}; + +/// @param status What `fstat` filled in. +/// @return Its times, read through the fields this system names them by. +[[nodiscard]] StatTimes timesOf(struct ::stat const& status) noexcept; + +/// Advises the system how a range of @p handle will be read, through this system's call for it. +/// @param handle An open file. +/// @param offset Where the range starts. +/// @param length How long it is; 0 to the end. +/// @param advice How. +/// @return Nothing, or why it was refused. +[[nodiscard]] FsResult adviseRange(int handle, + std::uint64_t offset, + std::uint64_t length, + Advice advice); + +/// @param handle An open file. +/// @return Nothing once its data is on stable storage. +[[nodiscard]] FsResult syncData(int handle); + +/// @param handle An open file. +/// @return Nothing once its data and metadata are on stable storage. +[[nodiscard]] FsResult syncAll(int handle); + +/// @param flags The flags a descriptor is opened with. +/// @return The `open` flags its write-integrity mode needs; `Unsupported` for a mode this system +/// lacks. +[[nodiscard]] FsResult syncOpenFlags(DescriptorFlags flags); + +/// Classifies an open of @p name in @p directory that the kernel refused with @p error, where a +/// system's answer differs from Linux's: macOS refuses `O_CREAT` on an existing directory with +/// `EACCES` where Linux says `EISDIR`. +/// @param directory The directory @p name is in. +/// @param name The name the open was given. +/// @param flags The flags it was given. +/// @param error The `errno` it failed with. +/// @return The error. +[[nodiscard]] FsError openFailure(int directory, std::string const& name, int flags, int error); + +/// Opens @p name again, waiting, after an `O_NONBLOCK` open of it answered `EWOULDBLOCK`, which +/// only a lease on a regular file makes it answer. Where the system has leases (Linux), the name is +/// opened as a path handle, checked by that handle to be a regular file, and reopened through it +/// with @p flags, waiting for the lease to be broken: whatever was renamed over the name between +/// the two opens, a FIFO is never opened blocking. Elsewhere the answer is `WouldBlock`. +/// @param directory The directory @p name is in. +/// @param name The name. +/// @param flags The open's flags, without `O_NONBLOCK`. +/// @return The handle; `WouldBlock` where @p name no longer names a regular file or the system +/// cannot wait for a lease. +[[nodiscard]] CORE_FS_API FsResult openAfterWouldBlock(int directory, + std::string const& name, + int flags); + +/// Opens the second handle `append` writes through, where this system cannot append through the +/// first without changing how its positioned writes land (an `O_APPEND` handle ignores the offset +/// of `pwrite` on Linux). Never `dup`: a duplicate shares the first handle's status flags. +/// @param directory The directory @p name was opened beneath, still held. +/// @param name The name the first handle was opened by. +/// @param first The first handle; the second must open the same object. +/// @param integrityFlags The write-integrity `open` flags of the first (`O_SYNC`, `O_DSYNC`), so +/// an append is as durable as a positioned write. +/// @return The second handle, or one holding no handle where this system appends through the +/// first; `Busy` where @p name no longer names the object @p first is open on. +[[nodiscard]] FsResult openAppendHandle(int directory, + std::string const& name, + int first, + int integrityFlags); + +/// Writes @p bytes at the end of the file. +/// @param handle The descriptor's handle. +/// @param appendHandle What @c openAppendHandle opened for it, or null where it opened none. +/// @param appendLock The descriptor's own, held by an append that has to find the end itself, so +/// two of its appends never land on the same end. +/// @param bytes What to write. +/// @return How many bytes were written. +[[nodiscard]] FsResult appendBytes(int handle, + OwnedHandle const* appendHandle, + std::mutex& appendLock, + std::span bytes); + +} // namespace core::fs::detail diff --git a/src/core/fs/testing/InMemoryDescriptorFileSystem.cpp b/src/core/fs/testing/InMemoryDescriptorFileSystem.cpp new file mode 100644 index 00000000..577ebe20 --- /dev/null +++ b/src/core/fs/testing/InMemoryDescriptorFileSystem.cpp @@ -0,0 +1,1025 @@ +// SPDX-License-Identifier: Apache-2.0 +#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 core::fs::testing +{ + +namespace +{ + + /// The largest file the model holds: a write or a size beyond it is `FileTooLarge`, so a guest + /// cannot make the host allocate what it asks for. + constexpr std::uint64_t MaxFileSize = std::uint64_t { 1 } << 30U; + + /// The inode number of the model's root directory. + constexpr std::uint64_t RootInode = 1; + + std::unexpected refuse(FsErrorCode code) + { + return std::unexpected { FsError { .code = code, .systemCode = 0, .context = {} } }; + } + +} // namespace + +/// The model, and what its descriptors need to reach it. Every member function expects @c mutex held. +struct InMemoryState +{ + // The model's types are nested, so they share the linkage of the struct the header declares. + + /// A name in a directory, as given, and what it names. + struct Entry + { + std::string name; + std::uint64_t inode = 0; + }; + + /// A directory, a regular file or a symbolic link. Only the members of its type are used. + struct Node + { + std::vector data; ///< A file's bytes. + std::map entries; ///< A directory's entries, keyed by folded name. + std::string target; ///< A link's target. + std::uint64_t linkCount = 1; + std::uint64_t changes = 0; ///< Bumped by every change, for the metadata hash. + FileTime accessed; + FileTime modified; + FileTime statusChanged; + DescriptorType type = DescriptorType::Unknown; + }; + + /// Where a path resolved to: the directories walked from the descriptor down to the one holding + /// the final name, the name, what it names, if anything, and whether the path required that to + /// be a directory (`name/`). An empty name means the path named the last directory itself (`.`, + /// `a/..`). + struct Location + { + std::vector directories; + std::string name; + std::optional node; + fs::detail::FinalComponent finalComponent = fs::detail::FinalComponent::Any; + + [[nodiscard]] std::uint64_t parent() const { return directories.back(); } + }; + + using TrailingSlashOnLink = fs::detail::TrailingSlashOnLink; + + /// The directories a walk of the model moves through, by inode: what @c fs::detail::walkBeneath + /// walks, so the model and the native descriptors share every rule of resolution. + class Cursor final: public fs::detail::IBeneathCursor + { + public: + Cursor(InMemoryState const& state, std::uint64_t start): _state { &state }, _directories { start } {} + + [[nodiscard]] bool atRoot() const noexcept override { return _directories.size() == 1; } + + [[nodiscard]] FsResult enter(std::string const& name) override + { + auto const found = _state->lookup(_directories.back(), name); + if (!found) + return refuse(FsErrorCode::NoEntry); + auto const type = _state->nodes.at(*found).type; + if (type == DescriptorType::SymbolicLink) + return fs::detail::EntryKind::SymbolicLink; + if (type != DescriptorType::Directory) + return refuse(FsErrorCode::NotDirectory); + _directories.push_back(*found); + return fs::detail::EntryKind::Directory; + } + + void leave() override { _directories.pop_back(); } + + [[nodiscard]] FsResult inspect(std::string const& name) override + { + auto const found = _state->lookup(_directories.back(), name); + if (!found) + return fs::detail::EntryKind::Missing; + auto const type = _state->nodes.at(*found).type; + if (type == DescriptorType::Directory) + return fs::detail::EntryKind::Directory; + if (type == DescriptorType::SymbolicLink) + return fs::detail::EntryKind::SymbolicLink; + return fs::detail::EntryKind::Other; + } + + [[nodiscard]] FsResult readLink(std::string const& name) override + { + auto const found = _state->lookup(_directories.back(), name); + if (!found || _state->nodes.at(*found).type != DescriptorType::SymbolicLink) + return refuse(FsErrorCode::Invalid); + return _state->nodes.at(*found).target; + } + + [[nodiscard]] FsResult shortcut(std::span) override + { + return fs::detail::Shortcut::Declined; + } + + void restart() override { _directories.resize(1); } + + /// @return The directories entered, from the start down to the current one. + [[nodiscard]] std::vector const& directories() const noexcept { return _directories; } + + private: + InMemoryState const* _state; + std::vector _directories; + }; + + async::IExecutor* home; + async::IExecutor* blocking; + platform::IWallClock const* clock; + PathPolicy const* policy; + std::size_t maxReadChunk; + std::mutex mutex; + std::map nodes; + std::uint64_t nextInode = RootInode; + + InMemoryState(async::IExecutor& homeExecutor, + async::IExecutor& blockingExecutor, + platform::IWallClock const& wallClock, + PathPolicy const& pathPolicy, + std::size_t readChunk): + home { &homeExecutor }, + blocking { &blockingExecutor }, + clock { &wallClock }, + policy { &pathPolicy }, + maxReadChunk { readChunk } + { + std::ignore = createNode(DescriptorType::Directory); + } + + [[nodiscard]] FileTime now() const + { + auto const sinceEpoch = clock->now().time_since_epoch(); + auto const seconds = std::chrono::floor(sinceEpoch); + return FileTime { + .seconds = seconds.count(), + .nanoseconds = static_cast( + std::chrono::duration_cast(sinceEpoch - seconds).count()), + }; + } + + void touch(Node& node, FileTime when) + { + node.modified = when; + node.statusChanged = when; + ++node.changes; + } + + [[nodiscard]] std::uint64_t createNode(DescriptorType type) + { + auto const inode = nextInode++; + auto const when = now(); + nodes.emplace(inode, + Node { .data = {}, + .entries = {}, + .target = {}, + .linkCount = 1, + .changes = 0, + .accessed = when, + .modified = when, + .statusChanged = when, + .type = type }); + return inode; + } + + /// @return @p name as a directory's key: as given, or with ASCII letters folded where the policy + /// says case does not distinguish names. + [[nodiscard]] std::string keyOf(std::string_view name) const + { + auto key = std::string { name }; + if (policy->caseRule == CaseRule::Insensitive) + std::ranges::transform(key, key.begin(), [](char c) { + return c >= 'a' && c <= 'z' ? static_cast(c - 'a' + 'A') : c; + }); + return key; + } + + [[nodiscard]] std::optional lookup(std::uint64_t directory, std::string_view name) const + { + auto const& entries = nodes.at(directory).entries; + auto const found = entries.find(keyOf(name)); + if (found == entries.end()) + return std::nullopt; + return found->second.inode; + } + + void insert(std::uint64_t directory, std::string name, std::uint64_t inode) + { + auto& parent = nodes.at(directory); + auto key = keyOf(name); + parent.entries.insert_or_assign(std::move(key), Entry { .name = std::move(name), .inode = inode }); + touch(parent, now()); + } + + void erase(std::uint64_t directory, std::string_view name) + { + auto& parent = nodes.at(directory); + parent.entries.erase(keyOf(name)); + touch(parent, now()); + } + + void dropLink(std::uint64_t inode) + { + auto& node = nodes.at(inode); + --node.linkCount; + node.statusChanged = now(); + } + + /// Resolves @p path beneath @p start through @c fs::detail::walkBeneath, following the final + /// link where @p policyForFinal, or a trailing `/` under @c TrailingSlashOnLink::Follow, says so. + /// @return Where it led; `NotDirectory` where @p start is not a directory, and what the walk + /// answers. + [[nodiscard]] FsResult walk(std::uint64_t start, + std::string_view path, + SymlinkPolicy policyForFinal, + TrailingSlashOnLink onLink = TrailingSlashOnLink::Follow) const + { + if (nodes.at(start).type != DescriptorType::Directory) + return refuse(FsErrorCode::NotDirectory); + auto cursor = Cursor { *this, start }; + auto const rules = fs::detail::WalkRules { .policy = policy, + .finalPolicy = policyForFinal, + .onLink = onLink, + .maxSymlinkHops = DefaultMaxSymlinkHops, + .kernelSeparators = {} }; + return fs::detail::planRelativePath(path, *policy) + .and_then([&](fs::detail::PathPlan plan) { + return fs::detail::walkBeneath(cursor, std::move(plan), rules); + }) + .transform([&](fs::detail::WalkEnd end) { + auto const parent = cursor.directories().back(); + auto const node = end.name.empty() ? std::optional { parent } : lookup(parent, end.name); + return Location { .directories = cursor.directories(), + .name = std::move(end.name), + .node = node, + .finalComponent = end.finalComponent }; + }); + } + + /// @return What @p path names; `NoEntry` where nothing does. + [[nodiscard]] FsResult existing(std::uint64_t start, + std::string_view path, + SymlinkPolicy policyForFinal) const + { + return walk(start, path, policyForFinal) + .and_then([](Location const& location) -> FsResult { + if (!location.node) + return refuse(FsErrorCode::NoEntry); + return *location.node; + }); + } + + /// @return Where @p path would be created as a @p creating; `Exist` where something is there + /// already, `NotDirectory` where the path ends in `/` and @p creating is not a directory. + [[nodiscard]] FsResult vacant(std::uint64_t start, + std::string_view path, + DescriptorType creating) const + { + return walk(start, path, SymlinkPolicy::NoFollow) + .and_then([creating](Location location) -> FsResult { + if (location.node) + return refuse(FsErrorCode::Exist); + if (creating != DescriptorType::Directory + && location.finalComponent == fs::detail::FinalComponent::Directory) + return refuse(FsErrorCode::NotDirectory); + return location; + }); + } + + /// Resizes a file to @p size bytes, refusing what a guest could ask for and the host cannot give. + /// @return Nothing; `FileTooLarge` above @c MaxFileSize, `InsufficientMemory` where the + /// allocation fails. + [[nodiscard]] static FsResult resizeData(Node& node, std::uint64_t size) + { + if (size > MaxFileSize) + return refuse(FsErrorCode::FileTooLarge); + try + { + node.data.resize(static_cast(size)); + } + catch (std::bad_alloc const&) + { + return refuse(FsErrorCode::InsufficientMemory); + } + return {}; + } + + [[nodiscard]] DescriptorStat statOf(std::uint64_t inode) const + { + auto const& node = nodes.at(inode); + auto size = std::uint64_t { 0 }; + if (node.type == DescriptorType::RegularFile) + size = node.data.size(); + else if (node.type == DescriptorType::SymbolicLink) + size = node.target.size(); + return DescriptorStat { .type = node.type, + .linkCount = node.linkCount, + .size = size, + .accessed = node.accessed, + .modified = node.modified, + .statusChanged = node.statusChanged }; + } + + void applyTimes(std::uint64_t inode, NewTimestamp const& accessed, NewTimestamp const& modified) + { + auto& node = nodes.at(inode); + auto const when = now(); + auto const apply = [when](FileTime& slot, NewTimestamp const& change) { + if (std::holds_alternative(change)) + slot = when; + else if (auto const* time = std::get_if(&change)) + slot = *time; + }; + apply(node.accessed, accessed); + apply(node.modified, modified); + node.statusChanged = when; + ++node.changes; + } + + [[nodiscard]] FsResult writeAt(std::uint64_t inode, + std::vector const& bytes, + std::uint64_t offset) + { + auto& node = nodes.at(inode); + if (node.type == DescriptorType::Directory) + return refuse(FsErrorCode::IsDirectory); + if (offset > MaxFileSize || bytes.size() > MaxFileSize - offset) + return refuse(FsErrorCode::FileTooLarge); + auto const end = offset + bytes.size(); + if (end > node.data.size()) + if (auto resized = resizeData(node, end); !resized) + return std::unexpected { std::move(resized.error()) }; + std::ranges::copy(bytes, node.data.begin() + static_cast(offset)); + touch(node, now()); + return bytes.size(); + } + + /// Creates a node at @p path, and every directory above it, for a test's setup. + std::uint64_t add(std::string_view path, DescriptorType type) + { + auto names = std::vector {}; + for (auto const piece: path | std::views::split('/')) + if (auto const name = std::string_view { piece }; !name.empty() && name != ".") + names.push_back(name); + if (names.empty()) + throw std::invalid_argument { "InMemoryDescriptorFileSystem: an empty path names the root" }; + auto directory = RootInode; + for (auto const name: names | std::views::take(names.size() - 1)) + { + auto found = lookup(directory, name); + if (!found) + { + found = createNode(DescriptorType::Directory); + insert(directory, std::string { name }, *found); + } + if (nodes.at(*found).type != DescriptorType::Directory) + throw std::invalid_argument { "InMemoryDescriptorFileSystem: '" + std::string { name } + + "' is in the way of '" + std::string { path } + "'" }; + directory = *found; + } + if (auto const found = lookup(directory, names.back())) + { + if (type == DescriptorType::Directory && nodes.at(*found).type == DescriptorType::Directory) + return *found; + throw std::invalid_argument { "InMemoryDescriptorFileSystem: '" + std::string { path } + + "' exists" }; + } + auto const inode = createNode(type); + insert(directory, std::string { names.back() }, inode); + return inode; + } +}; + +namespace +{ + + using Location = InMemoryState::Location; + using TrailingSlashOnLink = InMemoryState::TrailingSlashOnLink; + + /// A stream over a directory of the model: it reads the entries after the last key it handed + /// out, a batch of @c fs::detail::DirectoryBatchEntries at a time, so a change to the directory + /// between two batches is met as a native stream meets it: a name removed ahead is not read, a + /// name added ahead is, and nothing is read twice. + class InMemoryDirectoryStream final: public fs::detail::BatchedDirectoryStream + { + public: + InMemoryDirectoryStream(std::shared_ptr state, std::uint64_t inode): + _state { std::move(state) }, _inode { inode } + { + } + + protected: + async::Task> fetch() override + { + auto read = co_await async::offload( + _state->home, _state->blocking, [state = _state, inode = _inode, after = _after]() { + auto const lock = std::scoped_lock { state->mutex }; + return readBatch(*state, inode, after); + }); + _after = std::move(read.last); + co_return std::move(read.batch); + } + + private: + struct Read + { + fs::detail::DirectoryBatch batch; + std::optional last; ///< The key of the last entry read. + }; + + static Read readBatch(InMemoryState const& state, + std::uint64_t inode, + std::optional const& after) + { + auto const& entries = state.nodes.at(inode).entries; + auto position = after ? entries.upper_bound(*after) : entries.begin(); + auto read = Read { .batch = {}, .last = after }; + while (position != entries.end() && read.batch.entries.size() < fs::detail::DirectoryBatchEntries) + { + read.batch.entries.emplace_back(DirectoryEntry { + .type = state.nodes.at(position->second.inode).type, .name = position->second.name }); + read.last = position->first; + ++position; + } + if (position == entries.end()) + read.batch.end = StreamEnd::Reached; + return read; + } + + std::shared_ptr _state; + std::uint64_t _inode; + std::optional _after; ///< The key of the last entry handed out; none yet. + }; + + /// A descriptor of the model: the node it is open on, and the rights it was opened with. + class InMemoryDescriptor final: public IDescriptor + { + private: + // First, because a function whose return type is deduced cannot be called above its definition. + + /// Runs @p work on the blocking executor with the model locked, and resumes on home; @p work + /// takes the model's owner, so it can hand a new descriptor its share. + template + [[nodiscard]] auto submitShared(F work) const + { + return async::offload( + _state->home, _state->blocking, [state = _state, work = std::move(work)]() mutable { + auto const lock = std::scoped_lock { state->mutex }; + return work(state); + }); + } + + /// @c submitShared for work that needs only the model. + template + [[nodiscard]] auto submit(F work) const + { + return submitShared( + [work = std::move(work)](std::shared_ptr const& state) mutable { + return work(*state); + }); + } + + public: + InMemoryDescriptor(std::shared_ptr state, std::uint64_t inode, DescriptorFlags flags): + _state { std::move(state) }, _inode { inode }, _flags { flags } + { + } + + async::Task> read(std::size_t maxBytes, std::uint64_t offset) override + { + return submit([inode = _inode, flags = _flags, maxBytes, offset]( + InMemoryState& state) -> FsResult { + return checkRights(flags, Operation::Read).and_then([&]() -> FsResult { + auto const& node = state.nodes.at(inode); + if (node.type == DescriptorType::Directory) + return refuse(FsErrorCode::IsDirectory); + auto const size = node.data.size(); + auto const begin = std::min(offset, size); + auto const count = + std::min({ maxBytes, state.maxReadChunk, static_cast(size - begin) }); + auto const first = node.data.begin() + static_cast(begin); + return ReadChunk { + .bytes = std::vector(first, first + static_cast(count)), + .end = begin + count >= size ? StreamEnd::Reached : StreamEnd::More, + }; + }); + }); + } + + async::Task> write(std::vector bytes, std::uint64_t offset) override + { + return submit( + [inode = _inode, flags = _flags, bytes = std::move(bytes), offset](InMemoryState& state) { + return checkRights(flags, Operation::Write).and_then([&] { + return state.writeAt(inode, bytes, offset); + }); + }); + } + + async::Task> append(std::vector bytes) override + { + return submit([inode = _inode, flags = _flags, bytes = std::move(bytes)](InMemoryState& state) { + return checkRights(flags, Operation::Append).and_then([&] { + return state.writeAt(inode, bytes, state.nodes.at(inode).data.size()); + }); + }); + } + + async::Task> advise(std::uint64_t, std::uint64_t, Advice) override + { + return submit([flags = _flags](InMemoryState&) { return checkRights(flags, Operation::Advise); }); + } + + async::Task> syncData() override + { + return submit([flags = _flags](InMemoryState&) { return checkRights(flags, Operation::Sync); }); + } + + async::Task> sync() override + { + return submit([flags = _flags](InMemoryState&) { return checkRights(flags, Operation::Sync); }); + } + + [[nodiscard]] DescriptorFlags flags() const noexcept override { return _flags; } + + async::Task> type() override + { + return submit([inode = _inode, flags = _flags](InMemoryState& state) { + return checkRights(flags, Operation::Stat).transform([&] { + return state.nodes.at(inode).type; + }); + }); + } + + async::Task> setSize(std::uint64_t size) override + { + return submit([inode = _inode, flags = _flags, size](InMemoryState& state) { + return checkRights(flags, Operation::SetSize).and_then([&]() -> FsResult { + auto& node = state.nodes.at(inode); + if (node.type == DescriptorType::Directory) + return refuse(FsErrorCode::IsDirectory); + return InMemoryState::resizeData(node, size).transform([&] { + state.touch(node, state.now()); + }); + }); + }); + } + + async::Task> setTimes(NewTimestamp accessed, NewTimestamp modified) override + { + return submit([inode = _inode, flags = _flags, accessed, modified](InMemoryState& state) { + return checkRights(flags, Operation::SetTimes).transform([&] { + state.applyTimes(inode, accessed, modified); + }); + }); + } + + async::Task> stat() override + { + return submit([inode = _inode, flags = _flags](InMemoryState& state) { + return checkRights(flags, Operation::Stat).transform([&] { return state.statOf(inode); }); + }); + } + + async::Task> metadataHash() override + { + return submit([inode = _inode, flags = _flags](InMemoryState& state) { + return checkRights(flags, Operation::MetadataHash).transform([&] { + return MetadataHash { .lower = inode, .upper = state.nodes.at(inode).changes }; + }); + }); + } + + async::Task>> readDirectory() override + { + return submitShared([inode = _inode, flags = _flags](std::shared_ptr const& shared) + -> FsResult> { + return checkRights(flags, Operation::ReadDirectory) + .and_then([&]() -> FsResult { + if (shared->nodes.at(inode).type != DescriptorType::Directory) + return refuse(FsErrorCode::NotDirectory); + return {}; + }) + .transform([&]() -> std::unique_ptr { + return std::make_unique(shared, inode); + }); + }); + } + + async::Task>> openAt(SymlinkPolicy policy, + std::string path, + OpenFlags open, + DescriptorFlags childFlags) override + { + return submitShared( + [inode = _inode, flags = _flags, policy, path = std::move(path), open, childFlags]( + std::shared_ptr const& shared) -> FsResult> { + auto& state = *shared; + auto const opened = + checkRights(flags, Operation::OpenAt) + .and_then([&] { return checkOpenRights(flags, open, childFlags); }) + .and_then([&] { return state.walk(inode, path, finalPolicy(policy, open)); }) + .and_then([&](Location const& location) { + return openLocation(state, location, open, childFlags); + }); + if (!opened) + return std::unexpected { opened.error() }; + return std::make_unique( + shared, *opened, grantedFlags(state.nodes.at(*opened).type, childFlags)); + }); + } + + async::Task> createDirectoryAt(std::string path) override + { + return submit([inode = _inode, flags = _flags, path = std::move(path)](InMemoryState& state) { + return checkRights(flags, Operation::CreateDirectoryAt) + .and_then([&] { return state.vacant(inode, path, DescriptorType::Directory); }) + .transform([&](Location const& location) { + state.insert( + location.parent(), location.name, state.createNode(DescriptorType::Directory)); + }); + }); + } + + async::Task> statAt(SymlinkPolicy policy, std::string path) override + { + return submit( + [inode = _inode, flags = _flags, policy, path = std::move(path)](InMemoryState& state) { + return checkRights(flags, Operation::StatAt) + .and_then([&] { return state.existing(inode, path, policy); }) + .transform([&](std::uint64_t found) { return state.statOf(found); }); + }); + } + + async::Task> setTimesAt(SymlinkPolicy policy, + std::string path, + NewTimestamp accessed, + NewTimestamp modified) override + { + return submit( + [inode = _inode, flags = _flags, policy, path = std::move(path), accessed, modified]( + InMemoryState& state) { + return checkRights(flags, Operation::SetTimesAt) + .and_then([&] { return state.existing(inode, path, policy); }) + .transform([&](std::uint64_t found) { state.applyTimes(found, accessed, modified); }); + }); + } + + async::Task> linkAt(SymlinkPolicy policy, + std::string oldPath, + IDescriptor* newDirectory, + std::string newPath) override + { + auto const target = sameSystemTarget(newDirectory); + return submit([inode = _inode, + flags = _flags, + policy, + oldPath = std::move(oldPath), + target, + newPath = std::move(newPath)](InMemoryState& state) -> FsResult { + if (auto checked = checkRights(flags, Operation::LinkAt); !checked) + return checked; + if (policy == SymlinkPolicy::Follow) + return refuse(FsErrorCode::Invalid); + if (!target) + return std::unexpected { target.error() }; + if (auto checked = checkRights(target->flags, Operation::LinkAt); !checked) + return checked; + return state.existing(inode, oldPath, SymlinkPolicy::NoFollow) + .and_then([&](std::uint64_t found) -> FsResult { + if (state.nodes.at(found).type == DescriptorType::Directory) + return refuse(FsErrorCode::NotPermitted); + return state.vacant(target->inode, newPath, DescriptorType::RegularFile) + .transform([&](Location const& location) { + state.insert(location.parent(), location.name, found); + ++state.nodes.at(found).linkCount; + }); + }); + }); + } + + async::Task> readlinkAt(std::string path) override + { + return submit([inode = _inode, flags = _flags, path = std::move(path)](InMemoryState& state) { + return checkRights(flags, Operation::ReadlinkAt) + .and_then([&] { return state.existing(inode, path, SymlinkPolicy::NoFollow); }) + .and_then([&](std::uint64_t found) -> FsResult { + auto const& node = state.nodes.at(found); + if (node.type != DescriptorType::SymbolicLink) + return refuse(FsErrorCode::Invalid); + return node.target; + }); + }); + } + + async::Task> removeDirectoryAt(std::string path) override + { + return submit([inode = _inode, flags = _flags, path = std::move(path)](InMemoryState& state) { + return checkRights(flags, Operation::RemoveDirectoryAt) + .and_then([&] { + return state.walk(inode, path, SymlinkPolicy::NoFollow, TrailingSlashOnLink::Refuse); + }) + .and_then([&](Location const& location) -> FsResult { + if (!location.node) + return refuse(FsErrorCode::NoEntry); + if (location.name.empty()) + return refuse(FsErrorCode::Invalid); + auto const& node = state.nodes.at(*location.node); + if (node.type != DescriptorType::Directory) + return refuse(FsErrorCode::NotDirectory); + if (!node.entries.empty()) + return refuse(FsErrorCode::NotEmpty); + state.erase(location.parent(), location.name); + state.dropLink(*location.node); + return {}; + }); + }); + } + + async::Task> renameAt(std::string oldPath, + IDescriptor* newDirectory, + std::string newPath) override + { + auto const target = sameSystemTarget(newDirectory); + return submit([inode = _inode, + flags = _flags, + oldPath = std::move(oldPath), + target, + newPath = std::move(newPath)](InMemoryState& state) -> FsResult { + if (auto checked = checkRights(flags, Operation::RenameAt); !checked) + return checked; + if (!target) + return std::unexpected { target.error() }; + if (auto checked = checkRights(target->flags, Operation::RenameAt); !checked) + return checked; + auto from = state.walk(inode, oldPath, SymlinkPolicy::NoFollow, TrailingSlashOnLink::Refuse); + if (!from) + return std::unexpected { std::move(from.error()) }; + auto to = + state.walk(target->inode, newPath, SymlinkPolicy::NoFollow, TrailingSlashOnLink::Refuse); + if (!to) + return std::unexpected { std::move(to.error()) }; + return renameLocation(state, *from, *to); + }); + } + + async::Task> symlinkAt(std::string target, std::string newPath) override + { + return submit( + [inode = _inode, flags = _flags, target = std::move(target), newPath = std::move(newPath)]( + InMemoryState& state) -> FsResult { + if (auto checked = checkRights(flags, Operation::SymlinkAt); !checked) + return checked; + if (auto checked = fs::detail::checkSymlinkTarget(target, *state.policy); !checked) + return checked; + return state.vacant(inode, newPath, DescriptorType::SymbolicLink) + .transform([&](Location const& location) { + auto const link = state.createNode(DescriptorType::SymbolicLink); + state.nodes.at(link).target = target; + state.insert(location.parent(), location.name, link); + }); + }); + } + + async::Task> unlinkFileAt(std::string path) override + { + return submit([inode = _inode, flags = _flags, path = std::move(path)](InMemoryState& state) { + return checkRights(flags, Operation::UnlinkFileAt) + .and_then([&] { + return state.walk(inode, path, SymlinkPolicy::NoFollow, TrailingSlashOnLink::Refuse); + }) + .and_then([&](Location const& location) -> FsResult { + if (!location.node) + return refuse(FsErrorCode::NoEntry); + if (location.name.empty() + || state.nodes.at(*location.node).type == DescriptorType::Directory) + return refuse(FsErrorCode::IsDirectory); + state.erase(location.parent(), location.name); + state.dropLink(*location.node); + return {}; + }); + }); + } + + async::Task> metadataHashAt(SymlinkPolicy policy, std::string path) override + { + return submit( + [inode = _inode, flags = _flags, policy, path = std::move(path)](InMemoryState& state) { + return checkRights(flags, Operation::MetadataHashAt) + .and_then([&] { return state.existing(inode, path, policy); }) + .transform([&](std::uint64_t found) { + return MetadataHash { .lower = found, .upper = state.nodes.at(found).changes }; + }); + }); + } + + async::Task> isSameObject(IDescriptor* other) override + { + auto target = sameSystemTarget(other); + return submit([inode = _inode, target = std::move(target)](InMemoryState&) -> FsResult { + if (target) + return target->inode == inode; + if (target.error().code == FsErrorCode::CrossDevice) + return false; + return std::unexpected { target.error() }; + }); + } + + private: + /// A directory passed as `newDirectory`: the node and the rights, read on the caller's thread. + struct Target + { + std::uint64_t inode = 0; + DescriptorFlags flags = DescriptorFlags::None; + }; + + /// @return @p other's node and rights; `CrossDevice` unless it is a descriptor of this very + /// model, `BadDescriptor` for none at all. + [[nodiscard]] FsResult sameSystemTarget(IDescriptor* other) const + { + if (other == nullptr) + return refuse(FsErrorCode::BadDescriptor); + auto const* mine = dynamic_cast(other); + if (mine == nullptr || mine->_state != _state) + return refuse(FsErrorCode::CrossDevice); + return Target { .inode = mine->_inode, .flags = mine->_flags }; + } + + /// @return How an `openAt` resolves its final component: `O_CREAT | O_EXCL` never follows a + /// final symbolic link, so a dangling one is `Exist` rather than created through. + static SymlinkPolicy finalPolicy(SymlinkPolicy policy, OpenFlags open) noexcept + { + if (hasFlag(open, OpenFlags::Create) && hasFlag(open, OpenFlags::Exclusive)) + return SymlinkPolicy::NoFollow; + return policy; + } + + /// The node an `openAt` opens, creating or truncating it as @p open says. + static FsResult openLocation(InMemoryState& state, + Location const& location, + OpenFlags open, + DescriptorFlags childFlags) + { + if (!location.node) + { + if (!hasFlag(open, OpenFlags::Create)) + return refuse(FsErrorCode::NoEntry); + if (location.finalComponent == fs::detail::FinalComponent::Directory) + return refuse(FsErrorCode::NotDirectory); + auto const file = state.createNode(DescriptorType::RegularFile); + state.insert(location.parent(), location.name, file); + return file; + } + if (hasFlag(open, OpenFlags::Create) && hasFlag(open, OpenFlags::Exclusive)) + return refuse(FsErrorCode::Exist); + auto& node = state.nodes.at(*location.node); + if (node.type == DescriptorType::SymbolicLink) + return refuse(FsErrorCode::Loop); + if (node.type == DescriptorType::Directory) + { + if (hasFlag(childFlags, DescriptorFlags::Write) || hasFlag(open, OpenFlags::Truncate) + || hasFlag(open, OpenFlags::Create)) + return refuse(FsErrorCode::IsDirectory); + } + else if (hasFlag(open, OpenFlags::Directory)) + return refuse(FsErrorCode::NotDirectory); + if (hasFlag(open, OpenFlags::Truncate) && !node.data.empty()) + { + node.data.clear(); + state.touch(node, state.now()); + } + return *location.node; + } + + /// Moves @p from to @p to, replacing what @p to names where POSIX `rename` would. + static FsResult renameLocation(InMemoryState& state, Location const& from, Location const& to) + { + if (!from.node) + return refuse(FsErrorCode::NoEntry); + if (from.name.empty() || to.name.empty()) + return refuse(FsErrorCode::Invalid); + auto const moving = *from.node; + auto const isDirectory = state.nodes.at(moving).type == DescriptorType::Directory; + if (isDirectory && std::ranges::find(to.directories, moving) != to.directories.end()) + return refuse(FsErrorCode::Invalid); + if (!isDirectory && to.finalComponent == fs::detail::FinalComponent::Directory) + return refuse(FsErrorCode::NotDirectory); + if (to.node == moving) + return {}; + if (to.node) + { + auto const& replaced = state.nodes.at(*to.node); + auto const replacesDirectory = replaced.type == DescriptorType::Directory; + if (isDirectory && !replacesDirectory) + return refuse(FsErrorCode::NotDirectory); + if (!isDirectory && replacesDirectory) + return refuse(FsErrorCode::IsDirectory); + if (replacesDirectory && !replaced.entries.empty()) + return refuse(FsErrorCode::NotEmpty); + state.dropLink(*to.node); + } + state.erase(from.parent(), from.name); + state.insert(to.parent(), to.name, moving); + return {}; + } + + std::shared_ptr _state; + std::uint64_t _inode; + DescriptorFlags _flags; + }; + +} // namespace + +InMemoryDescriptorFileSystem::InMemoryDescriptorFileSystem(async::IExecutor& home, + async::IExecutor& blocking, + platform::IWallClock const& clock, + PathPolicy const& policy, + std::size_t maxReadChunk): + _state { std::make_shared(home, blocking, clock, policy, maxReadChunk) } +{ +} + +InMemoryDescriptorFileSystem::~InMemoryDescriptorFileSystem() = default; + +void InMemoryDescriptorFileSystem::addDirectory(std::string_view path) +{ + auto const lock = std::scoped_lock { _state->mutex }; + std::ignore = _state->add(path, DescriptorType::Directory); +} + +void InMemoryDescriptorFileSystem::addFile(std::string_view path, std::string_view content) +{ + auto const lock = std::scoped_lock { _state->mutex }; + auto& node = _state->nodes.at(_state->add(path, DescriptorType::RegularFile)); + node.data.resize(content.size()); + std::ranges::transform(content, node.data.begin(), [](char c) { return static_cast(c); }); +} + +void InMemoryDescriptorFileSystem::addSymlink(std::string_view path, std::string target) +{ + auto const lock = std::scoped_lock { _state->mutex }; + _state->nodes.at(_state->add(path, DescriptorType::SymbolicLink)).target = std::move(target); +} + +async::Task>> InMemoryDescriptorFileSystem::openPreopen( + std::filesystem::path hostDirectory, DescriptorFlags flags) +{ + return async::offload(_state->home, + _state->blocking, + [state = _state, + path = hostDirectory.generic_string(), + flags]() -> FsResult> { + if (hasFlag(flags, DescriptorFlags::Write)) + return refuse(FsErrorCode::IsDirectory); + auto const lock = std::scoped_lock { state->mutex }; + auto directory = RootInode; + for (auto const piece: path | std::views::split('/')) + { + auto const name = std::string_view { piece }; + if (name.empty() || name == ".") + continue; + auto const found = state->lookup(directory, name); + if (!found) + return refuse(FsErrorCode::NoEntry); + if (state->nodes.at(*found).type != DescriptorType::Directory) + return refuse(FsErrorCode::NotDirectory); + directory = *found; + } + return std::make_unique(state, directory, flags); + }); +} + +} // namespace core::fs::testing diff --git a/src/core/fs/testing/InMemoryDescriptorFileSystem.hpp b/src/core/fs/testing/InMemoryDescriptorFileSystem.hpp new file mode 100644 index 00000000..20bef02d --- /dev/null +++ b/src/core/fs/testing/InMemoryDescriptorFileSystem.hpp @@ -0,0 +1,94 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// `testing::InMemoryDescriptorFileSystem` — an @c IDescriptorFileSystem held in memory, for tests. + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace core::fs::testing +{ + +/// The nodes and the configuration a file system and its descriptors share; defined in the source. +struct InMemoryState; + +/// A file system of nodes in memory: directories, regular files and symbolic links. +/// +/// It is held to the same contract as the native one, through the same code where there is code to +/// share: paths are planned by @c fs::detail::planRelativePath and links spliced by +/// @c fs::detail::spliceSymlink under the policy it is given, rights come from @c rightsTable and +/// @c checkOpenRights, and the policy's @c CaseRule decides whether two names are one. **Every +/// operation suspends through @c async::offload**, onto `blocking` and back onto `home`, as the +/// native one does: a model that answered inline could never be in the parked state a cancellation +/// or teardown case is about, and every assertion over it would hold whether the property were +/// implemented or not. +/// +/// A write or a size beyond 1 GiB is `FileTooLarge`, so a test can hand it any guest-sized number. +/// +/// An unlinked node stays readable through a descriptor that is open on it, and its memory is kept +/// until the file system is destroyed. +/// +/// The namespace is `core::fs::testing`, the directory's: inside `namespace core::fs` an unqualified +/// `testing::` names this one, so code there that means the module spells it `core::testing::`. +class CORE_FS_API InMemoryDescriptorFileSystem final: public IDescriptorFileSystem +{ + public: + /// @param home Where every operation resumes. Must outlive the file system and its descriptors. + /// @param blocking Where every operation runs. Must outlive them too. + /// @param clock What `SetToNow` and a new node's times read. Must outlive them too. + /// @param policy The name rules paths are held to. Must outlive the file system and its + /// descriptors: it is kept by address, and its rows are views. + /// @param maxReadChunk The most one read returns. + InMemoryDescriptorFileSystem(async::IExecutor& home, + async::IExecutor& blocking, + platform::IWallClock const& clock, + PathPolicy const& policy = posixPathPolicy(), + std::size_t maxReadChunk = std::size_t { 1 } << 20U); + + InMemoryDescriptorFileSystem(InMemoryDescriptorFileSystem const&) = delete; + InMemoryDescriptorFileSystem(InMemoryDescriptorFileSystem&&) = delete; + InMemoryDescriptorFileSystem& operator=(InMemoryDescriptorFileSystem const&) = delete; + InMemoryDescriptorFileSystem& operator=(InMemoryDescriptorFileSystem&&) = delete; + ~InMemoryDescriptorFileSystem() override; + + /// Creates the directory @p path, and every directory above it, at once (a test's setup). + /// @param path Relative to the root, `/`-separated. + /// @throws std::invalid_argument Where something that is not a directory is in the way. + void addDirectory(std::string_view path); + + /// Creates the regular file @p path holding @p content, and every directory above it. + /// @param path Relative to the root, `/`-separated. + /// @param content What it holds. + /// @throws std::invalid_argument Where something is in the way. + void addFile(std::string_view path, std::string_view content); + + /// Creates the symbolic link @p path holding @p target, and every directory above it. + /// @param path Relative to the root, `/`-separated. + /// @param target What the link names, stored as given. + /// @throws std::invalid_argument Where something is in the way. + void addSymlink(std::string_view path, std::string target); + + /// Opens the directory @p hostDirectory of the model: `/`, `.` and the empty path are its root. + /// @param hostDirectory A `/`-separated path from the root. + /// @param flags The rights the root carries; `Write` is `IsDirectory`. + /// @return The descriptor. + [[nodiscard]] async::Task>> openPreopen( + std::filesystem::path hostDirectory, DescriptorFlags flags) override; + + private: + std::shared_ptr _state; +}; + +} // namespace core::fs::testing diff --git a/src/core/fs/testing/InMemoryDescriptorFileSystem_test.cpp b/src/core/fs/testing/InMemoryDescriptorFileSystem_test.cpp new file mode 100644 index 00000000..fc595ff9 --- /dev/null +++ b/src/core/fs/testing/InMemoryDescriptorFileSystem_test.cpp @@ -0,0 +1,118 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// What the in-memory model owes the cases built on it beyond the contract: that it suspends where +// the native file system does, and that its setup helpers build what they say. +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include + +using core::async::testing::ManualExecutor; +using core::fs::DescriptorFlags; +using core::fs::DescriptorType; +using core::fs::FsErrorCode; +using core::fs::OpenFlags; +using core::fs::SymlinkPolicy; +using core::fs::test::outcomeOf; +using core::fs::test::textOf; +using core::fs::testing::InMemoryDescriptorFileSystem; +using core::platform::ManualWallClock; + +TEST_CASE("in-memory: an operation runs on blocking and completes on home", "[fs][inmemory]") +{ + auto home = ManualExecutor {}; + auto blocking = ManualExecutor {}; + auto const clock = ManualWallClock {}; + auto fileSystem = InMemoryDescriptorFileSystem { home, blocking, clock }; + fileSystem.addFile("f", "parked"); + + auto open = fileSystem.openPreopen(std::filesystem::path { "/" }, DescriptorFlags::Read); + open.handle().resume(); + CHECK_FALSE(open.done()); + CHECK(blocking.pending() == 1); + blocking.drain(); + CHECK_FALSE(open.done()); + CHECK(home.pending() == 1); + home.drain(); + REQUIRE(open.done()); + auto root = open.result(); + REQUIRE(root.has_value()); + + auto stat = (*root)->statAt(SymlinkPolicy::NoFollow, "f"); + stat.handle().resume(); + CHECK_FALSE(stat.done()); + CHECK(blocking.pending() == 1); + blocking.drain(); + CHECK_FALSE(stat.done()); + home.drain(); + REQUIRE(stat.done()); + CHECK(stat.result()->size == 6); +} + +TEST_CASE("in-memory: the setup helpers build directories, files and links", "[fs][inmemory]") +{ + auto home = ManualExecutor {}; + auto blocking = ManualExecutor {}; + auto const clock = ManualWallClock {}; + auto fileSystem = InMemoryDescriptorFileSystem { home, blocking, clock }; + fileSystem.addDirectory("a/b"); + fileSystem.addFile("a/b/file", "content"); + fileSystem.addSymlink("a/link", "b/file"); + CHECK_THROWS_AS(fileSystem.addFile("a/b/file", "again"), std::invalid_argument); + CHECK_THROWS_AS(fileSystem.addDirectory("a/b/file/below"), std::invalid_argument); + + auto const drive = [&](auto task) { + task.handle().resume(); + while (!task.done() && blocking.drain() + home.drain() != 0) + { + } + REQUIRE(task.done()); + return task.result(); + }; + auto preopen = drive(fileSystem.openPreopen(std::filesystem::path { "a" }, DescriptorFlags::Read)); + REQUIRE(preopen.has_value()); + auto& dir = **preopen; + CHECK(drive(dir.statAt(SymlinkPolicy::NoFollow, "b"))->type == DescriptorType::Directory); + CHECK(drive(dir.statAt(SymlinkPolicy::NoFollow, "link"))->type == DescriptorType::SymbolicLink); + auto file = drive(dir.openAt(SymlinkPolicy::Follow, "link", OpenFlags::None, DescriptorFlags::Read)); + REQUIRE(file.has_value()); + CHECK(textOf(drive((*file)->read(64, 0))->bytes) == "content"); + + CHECK( + outcomeOf(drive(fileSystem.openPreopen(std::filesystem::path { "a/b/file" }, DescriptorFlags::Read))) + == FsErrorCode::NotDirectory); + CHECK(outcomeOf(drive(fileSystem.openPreopen(std::filesystem::path { "missing" }, DescriptorFlags::Read))) + == FsErrorCode::NoEntry); + CHECK(outcomeOf(drive(fileSystem.openPreopen(std::filesystem::path { "a" }, + DescriptorFlags::Read | DescriptorFlags::Write))) + == FsErrorCode::IsDirectory); +} + +TEST_CASE("in-memory: a guest-sized write or size is refused, never allocated", "[fs][inmemory]") +{ + auto fixture = core::fs::test::DescriptorFixture::create(core::fs::test::FixtureKind::InMemory); + fixture.createFile("f", "content"); + auto file = fixture.run(fixture.root().openAt( + SymlinkPolicy::NoFollow, "f", OpenFlags::None, DescriptorFlags::Read | DescriptorFlags::Write)); + REQUIRE(file.has_value()); + auto const tooLarge = [&](auto task) { + return outcomeOf(fixture.run(std::move(task))) == FsErrorCode::FileTooLarge; + }; + + CHECK(tooLarge( + (*file)->write(core::fs::test::bytesOf("wraps"), std::numeric_limits::max() - 2))); + CHECK(tooLarge((*file)->write(core::fs::test::bytesOf("far"), std::uint64_t { 1 } << 40U))); + CHECK(tooLarge((*file)->setSize(std::uint64_t { 1 } << 40U))); + CHECK(tooLarge((*file)->setSize(std::numeric_limits::max()))); + CHECK(fixture.run((*file)->stat())->size == 7); +} diff --git a/src/core/fs/windows/BeneathDefault.cpp b/src/core/fs/windows/BeneathDefault.cpp new file mode 100644 index 00000000..37e5405b --- /dev/null +++ b/src/core/fs/windows/BeneathDefault.cpp @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// What BeneathStrategy::Best is on Windows: the walk, since NtCreateFile resolves a multi-component +// name with no beneath mode, so every component is opened relative to the handle before it. CMake +// compiles exactly one BeneathDefault.cpp, so no `#ifdef` chooses the strategy. +#include + +#include + +namespace core::fs::detail +{ + +std::unique_ptr makeBestBeneathOpener() +{ + return nullptr; +} + +} // namespace core::fs::detail diff --git a/src/core/fs/windows/DescriptorEscape_test.cpp b/src/core/fs/windows/DescriptorEscape_test.cpp new file mode 100644 index 00000000..3a259b63 --- /dev/null +++ b/src/core/fs/windows/DescriptorEscape_test.cpp @@ -0,0 +1,524 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// What only Windows has to get right about a path beneath its descriptor: junctions and mount +// points are links whose target is absolute, so none is traversed, even one that points inside; a +// symbolic link's relative target may be separated by `\`; a link is made a directory link where its +// target is a directory, which other programs need to follow it; and a reparse point that names +// nothing else opens as the file it is. The junctions are made through the host, as an attacker +// outside the guest would make them; making one needs no privilege. +#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 + +using core::fs::DescriptorFlags; +using core::fs::DescriptorType; +using core::fs::FsErrorCode; +using core::fs::OpenFlags; +using core::fs::SymlinkPolicy; +using core::fs::test::DescriptorFixture; +using core::fs::test::FixedRandom; +using core::fs::test::outcomeOf; +using core::fs::test::SymlinkSupport; +using core::fs::test::textOf; + +namespace +{ + +/// Whether the host could make a reparse point. +enum class Made : std::uint8_t +{ + No, + Yes, +}; + +/// Writes @p data as the reparse point of the existing @p path, through the host. +Made setReparsePoint(std::filesystem::path const& path, std::span data) +{ + auto const handle = core::fs::detail::UniqueHandle { ::CreateFileW( + path.c_str(), + GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + nullptr, + OPEN_EXISTING, + FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, + nullptr) }; + if (handle.get() == INVALID_HANDLE_VALUE) + return Made::No; + return core::fs::detail::writeReparseData(handle.get(), data) ? Made::Yes : Made::No; +} + +/// Makes @p path a junction to the absolute @p target, as `mklink /J` does. +Made makeJunction(std::filesystem::path const& path, std::wstring const& target) +{ + std::filesystem::create_directory(path); + return setReparsePoint(path, core::fs::detail::mountPointReparseData(L"\\??\\" + target + L"\\", target)); +} + +/// @return The `\??\Volume{...}\` name of the volume @p path is on, where the host tells it. +std::optional volumeNameOf(std::filesystem::path const& path) +{ + auto mountPoint = std::array {}; + auto volume = std::array {}; + if (::GetVolumePathNameW(path.c_str(), mountPoint.data(), static_cast(mountPoint.size())) == FALSE + || ::GetVolumeNameForVolumeMountPointW( + mountPoint.data(), volume.data(), static_cast(volume.size())) + == FALSE) + return std::nullopt; + auto name = std::wstring { volume.data() }; // `\\?\Volume{...}\` + if (!name.starts_with(L"\\\\?\\")) + return std::nullopt; + name[1] = L'?'; + name[2] = L'?'; + return name; +} + +/// @return What @p name beneath @p fixture's root is, unfollowed where @p policy says so; nothing +/// where the stat was refused. +std::optional typeAt(DescriptorFixture const& fixture, + SymlinkPolicy policy, + std::string const& name) +{ + auto const status = fixture.run(fixture.root().statAt(policy, name)); + if (!status) + return std::nullopt; + return status->type; +} + +/// @return The size of @p name beneath @p fixture's root, following links; nothing where refused. +std::optional sizeAt(DescriptorFixture const& fixture, std::string const& name) +{ + auto const status = fixture.run(fixture.root().statAt(SymlinkPolicy::Follow, name)); + if (!status) + return std::nullopt; + return status->size; +} + +/// What the host sees a link as, beside a link. +enum class HostEntry : std::uint8_t +{ + File, + Directory, +}; + +/// @return What the host sees @p path, unfollowed, as. +HostEntry hostEntryOf(std::filesystem::path const& path) +{ + auto const attributes = ::GetFileAttributesW(path.c_str()); + return attributes != INVALID_FILE_ATTRIBUTES && (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0 + ? HostEntry::Directory + : HostEntry::File; +} + +} // namespace + +TEST_CASE("windows: a junction or a mount point beneath the preopen is never traversed", + "[fs][escape][windows]") +{ + auto fixture = DescriptorFixture::createNative(); + auto& root = fixture.root(); + REQUIRE(fixture.run(root.createDirectoryAt("inside")).has_value()); + fixture.createFile("inside/decoy", "inside"); + fixture.writeOutsideFile("decoy", "outside"); + + auto names = std::vector {}; + if (makeJunction(fixture.hostDirectory() / "out", fixture.outsideDirectory().wstring()) == Made::Yes) + names.emplace_back("out"); + // Even a junction that points inside is refused: its target is an absolute path, which no walk + // beneath a handle may take. + if (makeJunction(fixture.hostDirectory() / "in", (fixture.hostDirectory() / "inside").wstring()) + == Made::Yes) + names.emplace_back("in"); + if (auto const volume = volumeNameOf(fixture.hostDirectory())) + { + std::filesystem::create_directory(fixture.hostDirectory() / "vol"); + if (setReparsePoint(fixture.hostDirectory() / "vol", + core::fs::detail::mountPointReparseData(*volume, L"")) + == Made::Yes) + names.emplace_back("vol"); + } + if (names.empty()) + SKIP("this file system makes no junction"); + + auto const notPermitted = std::optional { FsErrorCode::NotPermitted }; + for (auto const& name: names) + { + CAPTURE(name); + for (auto const policy: { SymlinkPolicy::NoFollow, SymlinkPolicy::Follow }) + { + CHECK(outcomeOf(fixture.run(root.statAt(policy, name + "/decoy"))) == notPermitted); + CHECK(outcomeOf(fixture.run( + root.openAt(policy, name + "/decoy", OpenFlags::None, DescriptorFlags::Read))) + == notPermitted); + CHECK(outcomeOf(fixture.run(root.metadataHashAt(policy, name + "/."))) == notPermitted); + } + CHECK(outcomeOf(fixture.run(root.statAt(SymlinkPolicy::Follow, name))) == notPermitted); + CHECK(outcomeOf(fixture.run(root.createDirectoryAt(name + "/new"))) == notPermitted); + CHECK(outcomeOf(fixture.run(root.unlinkFileAt(name + "/decoy"))) == notPermitted); + CHECK(outcomeOf(fixture.run(root.readlinkAt(name))) == notPermitted); + // Unfollowed, it is a link like any other, inside the root. + CHECK(typeAt(fixture, SymlinkPolicy::NoFollow, name) == DescriptorType::SymbolicLink); + } + CHECK(fixture.outsideUnchanged()); + CHECK(sizeAt(fixture, "inside/decoy") == 6U); +} + +TEST_CASE("windows: a relative link target separated by a backslash resolves beneath", + "[fs][escape][windows]") +{ + auto fixture = DescriptorFixture::createNative(); + if (fixture.requireSymlinks() == SymlinkSupport::Unavailable) + SKIP("this account cannot create symbolic links"); + auto& root = fixture.root(); + fixture.writeFile("a/b/f", "through the link"); + REQUIRE(fixture.run(root.symlinkAt("a\\b\\f", "filelink")).has_value()); + REQUIRE(fixture.run(root.symlinkAt("a\\b", "dirlink")).has_value()); + REQUIRE(fixture.run(root.symlinkAt("..\\..\\outside", "a/escape")).has_value()); + + auto const file = + fixture.run(root.openAt(SymlinkPolicy::Follow, "filelink", OpenFlags::None, DescriptorFlags::Read)); + REQUIRE(file.has_value()); + CHECK(textOf(fixture.run((*file)->read(64, 0)).value().bytes) == "through the link"); + CHECK(sizeAt(fixture, "dirlink/f") == 16U); + CHECK(fixture.run(root.readlinkAt("filelink")).value() == "a\\b\\f"); + CHECK(outcomeOf(fixture.run(root.statAt(SymlinkPolicy::Follow, "a/escape"))) + == FsErrorCode::NotPermitted); + + // What the system itself follows: the host reads the same file through the link. + CHECK(std::filesystem::file_size(fixture.hostDirectory() / "filelink") == 16); + CHECK(std::filesystem::is_regular_file(fixture.hostDirectory() / "dirlink" / "f")); +} + +TEST_CASE("windows: symlinkAt makes a directory link where the target is a directory", "[fs][windows]") +{ + auto fixture = DescriptorFixture::createNative(); + if (fixture.requireSymlinks() == SymlinkSupport::Unavailable) + SKIP("this account cannot create symbolic links"); + auto& root = fixture.root(); + fixture.writeFile("dir/f", "content"); + + struct Row + { + char const* target; + char const* name; + HostEntry entry; + }; + for (auto const& row: + { Row { .target = "dir", .name = "todir", .entry = HostEntry::Directory }, + Row { .target = "dir/f", .name = "tofile", .entry = HostEntry::File }, + Row { .target = "missing", .name = "dangling", .entry = HostEntry::File }, + Row { .target = "missing/", .name = "slashed", .entry = HostEntry::Directory }, + Row { .target = "..", .name = "up", .entry = HostEntry::Directory }, + Row { .target = "dir/../dir/.", .name = "dotted", .entry = HostEntry::Directory } }) + { + CAPTURE(row.target); + REQUIRE(fixture.run(root.symlinkAt(row.target, row.name)).has_value()); + CHECK(hostEntryOf(fixture.hostDirectory() / row.name) == row.entry); + CHECK(typeAt(fixture, SymlinkPolicy::NoFollow, row.name) == DescriptorType::SymbolicLink); + CHECK(fixture.run(root.readlinkAt(row.name)).value() == row.target); + REQUIRE(fixture.run(root.unlinkFileAt(row.name)).has_value()); + } +} + +TEST_CASE("windows: a reparse point that names nothing else opens as the file it is", "[fs][windows]") +{ + auto fixture = DescriptorFixture::createNative(); + fixture.createFile("tagged", "content"); + // A third-party tag that is no name surrogate, as a cloud or backup filter's own: an 8-byte + // head, the owner's GUID, then its data. No filter takes it, so the point is the file. + constexpr auto PrivateTag = std::uint32_t { 0x0000'7F10U }; + auto data = std::vector(8 + 16 + 4); + auto const length = std::uint16_t { 4 }; + std::memcpy(data.data(), &PrivateTag, sizeof(PrivateTag)); + std::memcpy(data.data() + 4, &length, sizeof(length)); + data[8] = std::byte { 0x5A }; + if (setReparsePoint(fixture.hostDirectory() / "tagged", data) == Made::No) + SKIP("this file system takes no private reparse tag from this account"); + + auto const file = fixture.run( + fixture.root().openAt(SymlinkPolicy::NoFollow, "tagged", OpenFlags::None, DescriptorFlags::Read)); + REQUIRE(file.has_value()); + CHECK(textOf(fixture.run((*file)->read(64, 0)).value().bytes) == "content"); + CHECK(typeAt(fixture, SymlinkPolicy::NoFollow, "tagged") == DescriptorType::RegularFile); + CHECK(outcomeOf(fixture.run(fixture.root().readlinkAt("tagged"))) == FsErrorCode::Invalid); +} + +TEST_CASE("windows: a link whose target the kernel reads as absolute is never followed", + "[fs][escape][windows]") +{ + auto fixture = DescriptorFixture::createNative(); + if (fixture.requireSymlinks() == SymlinkSupport::Unavailable) + SKIP("this account cannot create symbolic links"); + auto& root = fixture.root(); + fixture.writeOutsideFile("decoy", "outside"); + + auto names = std::vector {}; + auto error = std::error_code {}; + std::filesystem::create_symlink( + fixture.outsideDirectory() / "decoy", fixture.hostDirectory() / "absolute", error); + if (!error) + names.emplace_back("absolute"); + // Flagged relative, but read by the kernel from the volume's root, a drive or the object + // namespace: what a hostile writer of reparse data would plant. + struct Planted + { + char const* name; + wchar_t const* substitute; + }; + for (auto const& planted: { Planted { .name = "rooted", .substitute = L"\\x" }, + Planted { .name = "drive", .substitute = L"C:x" }, + Planted { .name = "object", .substitute = L"\\??\\C:\\x" } }) + { + auto const path = fixture.hostDirectory() / planted.name; + std::ofstream { path }.close(); + if (setReparsePoint( + path, core::fs::detail::relativeSymlinkReparseData(planted.substitute, planted.substitute)) + == Made::Yes) + names.emplace_back(planted.name); + } + if (names.empty()) + SKIP("this file system takes none of the links"); + + for (auto const& name: names) + { + CAPTURE(name); + CHECK(outcomeOf(fixture.run(root.statAt(SymlinkPolicy::Follow, name))) == FsErrorCode::NotPermitted); + CHECK(outcomeOf(fixture.run( + root.openAt(SymlinkPolicy::Follow, name, OpenFlags::None, DescriptorFlags::Read))) + == FsErrorCode::NotPermitted); + CHECK(outcomeOf(fixture.run(root.statAt(SymlinkPolicy::NoFollow, name + "/x"))) + == FsErrorCode::NotPermitted); + CHECK(typeAt(fixture, SymlinkPolicy::NoFollow, name) == DescriptorType::SymbolicLink); + } + CHECK(fixture.outsideUnchanged()); +} + +TEST_CASE("windows: symlinkAt writes no target the kernel would read as absolute, whatever the policy", + "[fs][windows]") +{ + // Under the POSIX policy `\` and `:` are a name's characters, so the policy lets these through. + auto fixture = DescriptorFixture::createNative({ .policy = &core::fs::posixPathPolicy() }); + auto& root = fixture.root(); + CHECK(outcomeOf(fixture.run(root.symlinkAt("\\x", "rooted"))) == FsErrorCode::NotPermitted); + CHECK(outcomeOf(fixture.run(root.symlinkAt("\\??\\C:\\x", "object"))) == FsErrorCode::NotPermitted); + CHECK(outcomeOf(fixture.run(root.symlinkAt("C:x", "drive"))) == FsErrorCode::NotPermitted); + CHECK(outcomeOf(fixture.run(root.symlinkAt("a/b:stream", "stream"))) == FsErrorCode::Invalid); + for (auto const* name: { "rooted", "object", "drive", "stream" }) + CHECK(outcomeOf(fixture.run(root.statAt(SymlinkPolicy::NoFollow, name))) == FsErrorCode::NoEntry); +} + +namespace +{ + +/// The system's NT calls, but for one name: it reads as a reparse point that names nothing else, +/// and opening it again through its filter meets a mount point, as when a writer swaps the one +/// for the other between the check and the reopen. +class SwappedPointFiles final: public core::fs::detail::INtFiles +{ + public: + core::fs::FsResult open( + HANDLE directory, + std::wstring const& name, + core::fs::detail::NtOpenRequest const& request) const override + { + if (request.reparse == core::fs::detail::ReparseHandling::ThroughFilters && isSwapped(directory)) + return std::unexpected { core::fs::fsErrorFromNtStatus( + std::int64_t { STATUS_REPARSE_POINT_ENCOUNTERED }, "scripted") }; + auto opened = core::fs::detail::systemNtFiles().open(directory, name, request); + if (opened && name == L"swapped") + _swapped = core::fs::detail::systemNtFiles().identity(opened->get()).value(); + return opened; + } + + core::fs::FsResult attributes(HANDLE handle) const override + { + if (isSwapped(handle)) + return core::fs::detail::EntryAttributes { .attributes = FILE_ATTRIBUTE_REPARSE_POINT, + .reparseTag = 0x0000'7F10U }; + return core::fs::detail::systemNtFiles().attributes(handle); + } + + core::fs::FsResult identity(HANDLE handle) const override + { + return core::fs::detail::systemNtFiles().identity(handle); + } + + core::fs::FsResult queryDirectory(HANDLE directory, std::span records) const override + { + return core::fs::detail::systemNtFiles().queryDirectory(directory, records); + } + + private: + /// By identity, not by handle value: a closed handle's value is reused. + [[nodiscard]] bool isSwapped(HANDLE handle) const + { + auto const identity = core::fs::detail::systemNtFiles().identity(handle); + return _swapped && identity && *identity == *_swapped; + } + + mutable std::optional _swapped; +}; + +/// Drives @p task to its end over the two executors, bounded. +template +T drive(core::async::testing::ManualExecutor& home, + core::async::testing::ManualExecutor& blocking, + core::async::Task task) +{ + task.handle().resume(); + for ([[maybe_unused]] auto const round: std::views::iota(0, 10'000)) + if (task.done() || home.drain() + blocking.drain() == 0) + break; + REQUIRE(task.done()); + return task.result(); +} + +} // namespace + +TEST_CASE("windows: a point swapped for a mount point before its filter opens it is refused", + "[fs][escape][windows]") +{ + auto home = core::async::testing::ManualExecutor {}; + auto blocking = core::async::testing::ManualExecutor {}; + auto const clock = core::platform::ManualWallClock {}; + auto random = FixedRandom { 1 }; + auto const files = SwappedPointFiles {}; + auto const directory = core::testing::ScopedTempDir { "core-cpp-fs-swapped" }; + std::ofstream { directory.path() / "swapped" } << "stub"; + std::ofstream { directory.path() / "plain" } << "plain"; + auto fileSystem = + core::fs::detail::makeWindowsDescriptorFileSystem(home, blocking, clock, random, {}, files); + REQUIRE(fileSystem.has_value()); + { + auto root = drive( + home, + blocking, + (*fileSystem) + ->openPreopen(directory.path(), DescriptorFlags::Read | DescriptorFlags::MutateDirectory)); + REQUIRE(root.has_value()); + auto const swapped = drive( + home, + blocking, + (*root)->openAt(SymlinkPolicy::NoFollow, "swapped", OpenFlags::None, DescriptorFlags::Read)); + CHECK(outcomeOf(swapped) == FsErrorCode::NotPermitted); + auto const plain = + drive(home, + blocking, + (*root)->openAt(SymlinkPolicy::NoFollow, "plain", OpenFlags::None, DescriptorFlags::Read)); + CHECK(plain.has_value()); + } + fileSystem->reset(); + std::ignore = home.drain() + blocking.drain(); +} + +namespace +{ + +/// The system's NT calls, but for one file: its append handle, opened again by its handle, lands on +/// another file outside, as following a symbolic link put on the file after its check would. +class RedirectedAppendFiles final: public core::fs::detail::INtFiles +{ + public: + explicit RedirectedAppendFiles(std::filesystem::path outside): _outside { std::move(outside) } {} + + core::fs::FsResult open( + HANDLE directory, + std::wstring const& name, + core::fs::detail::NtOpenRequest const& request) const override + { + auto const& system = core::fs::detail::systemNtFiles(); + if (name.empty() && (request.access & FILE_APPEND_DATA) != 0 && _victim + && system.identity(directory).value() == *_victim) + return core::fs::detail::UniqueHandle { ::CreateFileW(_outside.c_str(), + FILE_APPEND_DATA | FILE_READ_ATTRIBUTES, + FILE_SHARE_READ | FILE_SHARE_WRITE + | FILE_SHARE_DELETE, + nullptr, + OPEN_EXISTING, + 0, + nullptr) }; + auto opened = system.open(directory, name, request); + if (opened && name == L"victim") + _victim = system.identity(opened->get()).value(); + return opened; + } + + core::fs::FsResult attributes(HANDLE handle) const override + { + return core::fs::detail::systemNtFiles().attributes(handle); + } + + core::fs::FsResult identity(HANDLE handle) const override + { + return core::fs::detail::systemNtFiles().identity(handle); + } + + core::fs::FsResult queryDirectory(HANDLE directory, std::span records) const override + { + return core::fs::detail::systemNtFiles().queryDirectory(directory, records); + } + + private: + std::filesystem::path _outside; + mutable std::optional _victim; +}; + +} // namespace + +TEST_CASE("windows: an append handle that opens another object than the file is refused", + "[fs][escape][windows]") +{ + auto home = core::async::testing::ManualExecutor {}; + auto blocking = core::async::testing::ManualExecutor {}; + auto const clock = core::platform::ManualWallClock {}; + auto random = FixedRandom { 1 }; + auto const directory = core::testing::ScopedTempDir { "core-cpp-fs-append" }; + std::filesystem::create_directory(directory.path() / "root"); + std::ofstream { directory.path() / "root" / "victim" } << "inside"; + std::ofstream { directory.path() / "outside" } << "outside"; + auto const files = RedirectedAppendFiles { directory.path() / "outside" }; + auto fileSystem = + core::fs::detail::makeWindowsDescriptorFileSystem(home, blocking, clock, random, {}, files); + REQUIRE(fileSystem.has_value()); + { + auto root = drive(home, + blocking, + (*fileSystem) + ->openPreopen(directory.path() / "root", + DescriptorFlags::Read | DescriptorFlags::MutateDirectory)); + REQUIRE(root.has_value()); + auto const victim = drive( + home, + blocking, + (*root)->openAt(SymlinkPolicy::NoFollow, "victim", OpenFlags::None, DescriptorFlags::Write)); + CHECK(outcomeOf(victim) == FsErrorCode::NotPermitted); + } + fileSystem->reset(); + std::ignore = home.drain() + blocking.drain(); + CHECK(std::filesystem::file_size(directory.path() / "outside") == 7); +} diff --git a/src/core/fs/windows/DirectoryRecords.cpp b/src/core/fs/windows/DirectoryRecords.cpp new file mode 100644 index 00000000..b77edf76 --- /dev/null +++ b/src/core/fs/windows/DirectoryRecords.cpp @@ -0,0 +1,93 @@ +// SPDX-License-Identifier: Apache-2.0 +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace core::fs::detail +{ + +namespace +{ + + /// Where each field a stream reads is, in bytes from the start of its record. + constexpr std::size_t NextOffset = offsetof(FILE_ID_BOTH_DIR_INFO, NextEntryOffset); + constexpr std::size_t AttributesOffset = offsetof(FILE_ID_BOTH_DIR_INFO, FileAttributes); + constexpr std::size_t NameLengthOffset = offsetof(FILE_ID_BOTH_DIR_INFO, FileNameLength); + /// Holds the reparse tag where the attributes say the entry is a reparse point. + constexpr std::size_t ReparseTagOffset = offsetof(FILE_ID_BOTH_DIR_INFO, EaSize); + constexpr std::size_t NameOffset = offsetof(FILE_ID_BOTH_DIR_INFO, FileName); + + std::unexpected invalid(char const* what) + { + return std::unexpected { FsError { .code = FsErrorCode::Invalid, .systemCode = 0, .context = what } }; + } + + std::uint32_t readWord(std::span bytes, std::size_t offset) noexcept + { + auto value = std::uint32_t {}; + std::memcpy(&value, bytes.data() + offset, sizeof(value)); + return value; + } + + DescriptorType typeOf(EntryAttributes const& attributes) noexcept + { + if (attributes.isLink()) + return DescriptorType::SymbolicLink; + if (attributes.isDirectory()) + return DescriptorType::Directory; + return DescriptorType::RegularFile; + } + +} // namespace + +FsResult>> parseDirectoryRecords(std::span records) +{ + auto entries = std::vector> {}; + auto offset = std::size_t { 0 }; + while (true) + { + if (records.size() < NameOffset || offset > records.size() - NameOffset) + return invalid("FILE_ID_BOTH_DIR_INFO beyond its buffer"); + auto const record = records.subspan(offset); + auto const nameBytes = std::size_t { readWord(record, NameLengthOffset) }; + if (nameBytes % sizeof(wchar_t) != 0 || nameBytes > record.size() - NameOffset) + return invalid("FILE_ID_BOTH_DIR_INFO name beyond its buffer"); + auto name = std::wstring(nameBytes / sizeof(wchar_t), L'\0'); + std::memcpy(name.data(), record.data() + NameOffset, nameBytes); + // No file system hands out an empty name or one holding a separator; one that did would name + // another entry, or a path. + if (name.empty() || name.find_first_of(L"\\/") != std::wstring::npos) + entries.emplace_back(std::unexpected { FsError { + .code = FsErrorCode::Io, .systemCode = 0, .context = "FILE_ID_BOTH_DIR_INFO name" } }); + else if (name != L"." && name != L"..") + { + auto const attributes = EntryAttributes { + .attributes = readWord(record, AttributesOffset), + .reparseTag = readWord(record, ReparseTagOffset), + }; + entries.emplace_back(utf8Of(name).transform([&](std::string narrow) { + return DirectoryEntry { .type = typeOf(attributes), .name = std::move(narrow) }; + })); + } + auto const next = std::size_t { readWord(record, NextOffset) }; + if (next == 0) + return entries; + if (next < NameOffset) + return invalid("FILE_ID_BOTH_DIR_INFO chain does not move forward"); + offset += next; + } +} + +} // namespace core::fs::detail diff --git a/src/core/fs/windows/DirectoryRecords.hpp b/src/core/fs/windows/DirectoryRecords.hpp new file mode 100644 index 00000000..17ecd4cc --- /dev/null +++ b/src/core/fs/windows/DirectoryRecords.hpp @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// The records a Windows directory stream reads: `FILE_ID_BOTH_DIR_INFO`, as +/// `GetFileInformationByHandleEx(FileIdBothDirectoryInfo)` writes them into one fixed buffer per +/// batch, read field by field at their documented offsets and held to the buffer's bounds. Private +/// to the fs module. + +#include +#include +#include +#include + +#include +#include + +namespace core::fs::detail +{ + +/// Reads the chain of records @p records holds, from its first, skipping `.` and `..`. +/// @param records What one `FileIdBothDirectoryInfo` call wrote, at the start of its buffer. +/// @return The entries, in order: a name surrogate (a symbolic link, a junction, a mount point) is +/// a link, anything else the directory or the file it is; a name UTF-8 cannot spell (an +/// unpaired surrogate) is `IllegalByteSequence` for that entry, and an empty name or one +/// holding `\` or `/` is `Io` for that entry. `Invalid` where a record +/// or its name does not lie within @p records, or the chain does not move forward. +[[nodiscard]] CORE_FS_API FsResult>> parseDirectoryRecords( + std::span records); + +} // namespace core::fs::detail diff --git a/src/core/fs/windows/DirectoryRecords_test.cpp b/src/core/fs/windows/DirectoryRecords_test.cpp new file mode 100644 index 00000000..b44600cc --- /dev/null +++ b/src/core/fs/windows/DirectoryRecords_test.cpp @@ -0,0 +1,289 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The records a Windows directory stream reads, built by hand: what each entry is, `.` and `..` +// skipped, a name UTF-8 cannot spell refused for its entry alone, and a record that would read +// beyond its buffer refused as a whole. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using core::fs::DescriptorType; +using core::fs::FsErrorCode; +using core::fs::detail::parseDirectoryRecords; +using core::fs::test::outcomeOf; + +namespace +{ + +/// One record to write: its name in UTF-16, its attributes and, for a reparse point, its tag. +struct Record +{ + std::wstring name; + std::uint32_t attributes = FILE_ATTRIBUTE_NORMAL; + std::uint32_t reparseTag = 0; +}; + +void writeWord(std::vector& bytes, std::size_t offset, std::uint32_t value) +{ + std::memcpy(bytes.data() + offset, &value, sizeof(value)); +} + +/// @return @p records chained as the system writes them, each 8-byte aligned. +std::vector encode(std::vector const& records) +{ + auto bytes = std::vector {}; + auto previous = std::size_t { 0 }; + for (auto const& record: records) + { + auto const start = bytes.size(); + if (start > 0) + writeWord(bytes, + previous + offsetof(FILE_ID_BOTH_DIR_INFO, NextEntryOffset), + static_cast(start - previous)); + auto const nameBytes = record.name.size() * sizeof(wchar_t); + auto const size = offsetof(FILE_ID_BOTH_DIR_INFO, FileName) + nameBytes; + bytes.resize(start + ((size + 7) / 8 * 8)); + writeWord(bytes, start + offsetof(FILE_ID_BOTH_DIR_INFO, FileAttributes), record.attributes); + writeWord(bytes, + start + offsetof(FILE_ID_BOTH_DIR_INFO, FileNameLength), + static_cast(nameBytes)); + writeWord(bytes, start + offsetof(FILE_ID_BOTH_DIR_INFO, EaSize), record.reparseTag); + std::memcpy( + bytes.data() + start + offsetof(FILE_ID_BOTH_DIR_INFO, FileName), record.name.data(), nameBytes); + previous = start; + } + return bytes; +} + +} // namespace + +TEST_CASE("windows records: each entry is what its attributes say, without . and ..", "[fs][windows]") +{ + auto const bytes = encode({ + { .name = L".", .attributes = FILE_ATTRIBUTE_DIRECTORY }, + { .name = L"..", .attributes = FILE_ATTRIBUTE_DIRECTORY }, + { .name = L"file.txt" }, + { .name = L"dir", .attributes = FILE_ATTRIBUTE_DIRECTORY }, + { .name = L"link", .attributes = FILE_ATTRIBUTE_REPARSE_POINT, .reparseTag = IO_REPARSE_TAG_SYMLINK }, + { .name = L"junction", + .attributes = FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT, + .reparseTag = IO_REPARSE_TAG_MOUNT_POINT }, + // A placeholder names nothing else: it is the directory it is. + { .name = L"cloud", + .attributes = FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT, + .reparseTag = IO_REPARSE_TAG_CLOUD_6 }, + // The tag field is an EA size where the entry is no reparse point. + { .name = L"ea", .attributes = FILE_ATTRIBUTE_NORMAL, .reparseTag = IO_REPARSE_TAG_SYMLINK }, + { .name = L"café" }, + }); + auto const entries = parseDirectoryRecords(bytes); + REQUIRE(entries.has_value()); + auto seen = std::vector> {}; + for (auto const& entry: *entries) + { + REQUIRE(entry.has_value()); + seen.emplace_back(entry->name, entry->type); + } + CHECK(seen + == std::vector> { + { "file.txt", DescriptorType::RegularFile }, + { "dir", DescriptorType::Directory }, + { "link", DescriptorType::SymbolicLink }, + { "junction", DescriptorType::SymbolicLink }, + { "cloud", DescriptorType::Directory }, + { "ea", DescriptorType::RegularFile }, + { "caf\xc3\xa9", DescriptorType::RegularFile }, + }); +} + +TEST_CASE("windows records: an unpaired surrogate is refused for its entry alone", "[fs][windows]") +{ + auto const bytes = + encode({ { .name = L"a" }, { .name = std::wstring { L'b', wchar_t { 0xD800 } } }, { .name = L"c" } }); + auto const entries = parseDirectoryRecords(bytes); + REQUIRE(entries.has_value()); + REQUIRE(entries->size() == 3); + CHECK((*entries)[0]->name == "a"); + CHECK(outcomeOf((*entries)[1]) == FsErrorCode::IllegalByteSequence); + CHECK((*entries)[2]->name == "c"); +} + +TEST_CASE("windows records: a record beyond its buffer is Invalid", "[fs][windows]") +{ + auto const whole = encode({ { .name = L"first" }, { .name = L"second" } }); + + SECTION("a name longer than what is left") + { + auto bytes = whole; + bytes.resize(offsetof(FILE_ID_BOTH_DIR_INFO, FileName) + 2); + writeWord(bytes, offsetof(FILE_ID_BOTH_DIR_INFO, NextEntryOffset), 0); + CHECK(outcomeOf(parseDirectoryRecords(bytes)) == FsErrorCode::Invalid); + } + SECTION("a next record past the end") + { + auto bytes = whole; + writeWord(bytes, + offsetof(FILE_ID_BOTH_DIR_INFO, NextEntryOffset), + static_cast(bytes.size())); + CHECK(outcomeOf(parseDirectoryRecords(bytes)) == FsErrorCode::Invalid); + } + SECTION("a chain that does not move forward") + { + auto bytes = whole; + writeWord(bytes, offsetof(FILE_ID_BOTH_DIR_INFO, NextEntryOffset), 1); + CHECK(outcomeOf(parseDirectoryRecords(bytes)) == FsErrorCode::Invalid); + } + SECTION("an odd name length") + { + auto bytes = whole; + writeWord(bytes, offsetof(FILE_ID_BOTH_DIR_INFO, FileNameLength), 3); + CHECK(outcomeOf(parseDirectoryRecords(bytes)) == FsErrorCode::Invalid); + } + SECTION("a buffer too short for one record") + { + auto bytes = whole; + bytes.resize(8); + CHECK(outcomeOf(parseDirectoryRecords(bytes)) == FsErrorCode::Invalid); + } + CHECK(parseDirectoryRecords(whole).has_value()); +} + +TEST_CASE("windows records: a name no file system gives is refused for its entry alone", "[fs][windows]") +{ + auto const bytes = encode( + { { .name = L"a" }, { .name = L"" }, { .name = L"b\\c" }, { .name = L"d/e" }, { .name = L"f" } }); + auto const entries = parseDirectoryRecords(bytes); + REQUIRE(entries.has_value()); + REQUIRE(entries->size() == 5); + CHECK((*entries)[0]->name == "a"); + for (auto const index: { 1, 2, 3 }) + CHECK(outcomeOf((*entries)[static_cast(index)]) == FsErrorCode::Io); + CHECK((*entries)[4]->name == "f"); +} + +namespace +{ + +/// The system's NT calls, but for listing: each call takes the next scripted Win32 code, and a 0 +/// lists through the system. +class ScriptedListing final: public core::fs::detail::INtFiles +{ + public: + explicit ScriptedListing(std::deque codes): _codes { std::move(codes) } {} + + core::fs::FsResult open( + HANDLE directory, + std::wstring const& name, + core::fs::detail::NtOpenRequest const& request) const override + { + return core::fs::detail::systemNtFiles().open(directory, name, request); + } + + core::fs::FsResult attributes(HANDLE handle) const override + { + return core::fs::detail::systemNtFiles().attributes(handle); + } + + core::fs::FsResult identity(HANDLE handle) const override + { + return core::fs::detail::systemNtFiles().identity(handle); + } + + core::fs::FsResult queryDirectory(HANDLE directory, std::span records) const override + { + REQUIRE_FALSE(_codes.empty()); + auto const code = _codes.front(); + _codes.pop_front(); + if (code == 0) + return core::fs::detail::systemNtFiles().queryDirectory(directory, records); + return std::unexpected { core::fs::fsErrorFromSystemCode(std::int64_t { code }, "scripted") }; + } + + private: + mutable std::deque _codes; +}; + +/// Drives @p task to its end over the two executors, bounded. +template +T drive(core::async::testing::ManualExecutor& home, + core::async::testing::ManualExecutor& blocking, + core::async::Task task) +{ + task.handle().resume(); + for ([[maybe_unused]] auto const round: std::views::iota(0, 10'000)) + if (task.done() || home.drain() + blocking.drain() == 0) + break; + REQUIRE(task.done()); + return task.result(); +} + +/// What a stream over a directory holding `f` answers, call by call, when its listing calls answer +/// @p codes. +std::vector streamOver(std::deque codes) +{ + auto home = core::async::testing::ManualExecutor {}; + auto blocking = core::async::testing::ManualExecutor {}; + auto const clock = core::platform::ManualWallClock {}; + auto random = core::fs::test::FixedRandom { 1 }; + auto const files = ScriptedListing { std::move(codes) }; + auto const directory = core::testing::ScopedTempDir { "core-cpp-fs-listing" }; + std::ofstream { directory.path() / "f" } << "x"; + auto answers = std::vector {}; + auto fileSystem = + core::fs::detail::makeWindowsDescriptorFileSystem(home, blocking, clock, random, {}, files); + REQUIRE(fileSystem.has_value()); + { + auto root = drive( + home, blocking, (*fileSystem)->openPreopen(directory.path(), core::fs::DescriptorFlags::Read)); + REQUIRE(root.has_value()); + auto stream = drive(home, blocking, (*root)->readDirectory()); + REQUIRE(stream.has_value()); + for ([[maybe_unused]] auto const call: std::views::iota(0, 8)) + { + auto const next = drive(home, blocking, (*stream)->next()); + if (next && !*next) + break; + answers.push_back(outcomeOf(next)); + } + } + fileSystem->reset(); + std::ignore = home.drain() + blocking.drain(); + return answers; +} + +} // namespace + +TEST_CASE("windows listing: a directory with no entry at all ends at once", "[fs][windows]") +{ + using Outcomes = std::vector; + // An empty FAT or exFAT root: not even `.` and `..`, which the first call reports as no file. + CHECK(streamOver({ ERROR_FILE_NOT_FOUND }).empty()); + CHECK(streamOver({ ERROR_NO_MORE_FILES }).empty()); + // After a batch, the same code is a failure, answered once, and ends the stream. + CHECK(streamOver({ 0, ERROR_FILE_NOT_FOUND }) == Outcomes { std::nullopt, FsErrorCode::NoEntry }); + CHECK(streamOver({ 0, ERROR_NO_MORE_FILES }) == Outcomes { std::nullopt }); + CHECK(streamOver({ ERROR_ACCESS_DENIED }) == Outcomes { FsErrorCode::Access }); +} diff --git a/src/core/fs/windows/NativePathPolicy.cpp b/src/core/fs/windows/NativePathPolicy.cpp new file mode 100644 index 00000000..df4d0d45 --- /dev/null +++ b/src/core/fs/windows/NativePathPolicy.cpp @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The native name rules of a Windows system. +#include + +namespace core::fs +{ + +PathPolicy const& nativePathPolicy() noexcept +{ + return windowsPathPolicy(); +} + +} // namespace core::fs diff --git a/src/core/fs/windows/NtFile.hpp b/src/core/fs/windows/NtFile.hpp new file mode 100644 index 00000000..6a54293a --- /dev/null +++ b/src/core/fs/windows/NtFile.hpp @@ -0,0 +1,265 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// The native API the Windows descriptors open and name files through: `NtCreateFile` relative to a +/// held directory handle, which is the only way Windows resolves one name beneath a handle rather +/// than a whole path from a drive, and `NtSetInformationFile`, which renames and links an open file +/// to a name beneath another held handle. Private to the fs module, never included by a public +/// header, and the reason the module links `ntdll`. +/// +/// `` declares `NtCreateFile` but neither `NtSetInformationFile` nor the information +/// classes it takes beyond the first, which live in the driver kit's ``; the few used here +/// are spelled out below with their documented values, and `NtSetInformationFile` is resolved from +/// the `ntdll` every process has mapped, as `core::net`'s IOCP backend resolves it. + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// defines every STATUS_ code, and defines some of them again unless it is +// told not to: the documented order is this one. Every core-cpp target builds with +// WIN32_LEAN_AND_MEAN, under which no longer declares NTSTATUS; does, and +// NtCreateFile with it. +#define WIN32_NO_STATUS +#include +#undef WIN32_NO_STATUS +#include +#include + +namespace core::fs::detail +{ + +/// `OBJ_DONT_REPARSE` (Windows 10 1803): the object manager refuses any reparse point on the way to +/// the name, so a junction can never be crossed even if a name held a separator. Spelled here +/// because an SDK older than 10.0.17134 lacks the name; the value is the documented one. +#ifdef OBJ_DONT_REPARSE +inline constexpr ULONG DontReparse = OBJ_DONT_REPARSE; +#else +inline constexpr ULONG DontReparse = 0x0000'1000UL; +#endif + +/// How an open treats a reparse point it names. +enum class ReparseHandling : std::uint8_t +{ + /// It opens the point itself (`FILE_OPEN_REPARSE_POINT`) and refuses any met on the way to it + /// (`OBJ_DONT_REPARSE`), so the kernel follows no link: what every open by a name does. + OpenThePoint, + /// It lets the file system's filters act on the point, as an ordinary open does, but still + /// refuses any reparse the object manager would follow (`OBJ_DONT_REPARSE`): a filter serving its + /// own tag (a cloud placeholder, a deduplicated file) consumes the reparse itself, while a point + /// swapped for a mount point since it was checked answers `STATUS_REPARSE_POINT_ENCOUNTERED`, + /// which the callers refuse as `NotPermitted`, rather than being followed to wherever it names. Only for + /// opening again, by its handle and with no name, a point already known to name nothing else. + /// Before Windows 10 1803, which lacks the flag, such an open is refused. + ThroughFilters, +}; + +/// What `NtCreateFile` is asked for, besides the name. +struct NtOpenRequest +{ + ACCESS_MASK access = 0; ///< The access wanted; `SYNCHRONIZE` is always added. + ULONG disposition = 0; ///< `FILE_OPEN`, `FILE_CREATE`, ... + ULONG options = 0; ///< `FILE_DIRECTORY_FILE`, ...; synchronous I/O is always added. + ReparseHandling reparse = ReparseHandling::OpenThePoint; ///< What a reparse point it names is. +}; + +/// How every open identifies this process to a server it reaches (a named pipe, a share): never +/// beyond identification, so no peer can act as this process with its token. +inline constexpr auto IdentificationOnly = SECURITY_QUALITY_OF_SERVICE { + .Length = sizeof(SECURITY_QUALITY_OF_SERVICE), + .ImpersonationLevel = SecurityIdentification, + .ContextTrackingMode = SECURITY_STATIC_TRACKING, + .EffectiveOnly = TRUE, +}; + +/// Opens @p name beneath @p directory, with `OBJ_DONT_REPARSE` where the system knows it and +/// @c IdentificationOnly. Opening the point itself before Windows 10 1803, where that flag is +/// `STATUS_INVALID_PARAMETER`, the open is made again without it, as Rust's standard library does; +/// the name is one component either way, and the point itself is what is opened. Opening through +/// filters is never made without it. +/// @param directory A held handle the name is relative to: a directory, or the object itself for +/// an empty name. +/// @param name One component in UTF-16; empty opens @p directory itself again. +/// @param request What to ask for. +/// @return The handle, owned by the caller; the NTSTATUS, classified, where it failed. +[[nodiscard]] inline FsResult ntOpenRelative(HANDLE directory, + std::wstring const& name, + NtOpenRequest const& request) +{ + auto const openThePoint = request.reparse == ReparseHandling::OpenThePoint; + // Through filters only by a handle: a name could be anything by now. + if (!openThePoint && !name.empty()) + return std::unexpected { FsError { .code = FsErrorCode::Invalid, + .systemCode = 0, + .context = "NtCreateFile through filters by name" } }; + auto const bytes = name.size() * sizeof(wchar_t); + if (bytes > std::numeric_limits::max()) + return std::unexpected { FsError { + .code = FsErrorCode::NameTooLong, .systemCode = 0, .context = {} } }; + auto unicodeName = UNICODE_STRING { .Length = static_cast(bytes), + .MaximumLength = static_cast(bytes), + .Buffer = const_cast(name.c_str()) }; + auto qualityOfService = IdentificationOnly; + auto const open = [&](ULONG attributeFlags) { + auto attributes = OBJECT_ATTRIBUTES { .Length = sizeof(OBJECT_ATTRIBUTES), + .RootDirectory = directory, + .ObjectName = &unicodeName, + .Attributes = OBJ_CASE_INSENSITIVE | attributeFlags, + .SecurityDescriptor = nullptr, + .SecurityQualityOfService = &qualityOfService }; + auto status = IO_STATUS_BLOCK {}; + auto handle = HANDLE {}; + auto const result = + ::NtCreateFile(&handle, + request.access | SYNCHRONIZE, + &attributes, + &status, + nullptr, + FILE_ATTRIBUTE_NORMAL, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + request.disposition, + request.options | FILE_SYNCHRONOUS_IO_NONALERT + | (openThePoint ? ULONG { FILE_OPEN_REPARSE_POINT } : ULONG { 0 }), + nullptr, + 0); + return std::pair { result, handle }; + }; + auto [result, handle] = open(DontReparse); + if (result == STATUS_INVALID_PARAMETER && openThePoint) + std::tie(result, handle) = open(0); + if (result < 0) + return std::unexpected { fsErrorFromNtStatus(std::int64_t { result }, "NtCreateFile") }; + return UniqueHandle { handle }; +} + +/// The `NtSetInformationFile` classes that give an open file a name beneath a held directory. +inline constexpr ULONG FileRenameInformationClass = 10; ///< `FileRenameInformation`. +inline constexpr ULONG FileLinkInformationClass = 11; ///< `FileLinkInformation`. +inline constexpr ULONG FileRenameInformationExClass = 65; ///< `FileRenameInformationEx` (Windows 10 1709). + +/// The flags of `FileRenameInformationEx`; `FileRenameInformation` and `FileLinkInformation` read the +/// low byte as their `ReplaceIfExists`. +inline constexpr ULONG RenameReplaceIfExists = 0x01; +inline constexpr ULONG RenamePosixSemantics = 0x02; ///< The name goes at once, even while the target is open. +inline constexpr ULONG RenameIgnoreReadOnlyAttribute = 0x40; + +/// The head `FILE_RENAME_INFORMATION` and `FILE_LINK_INFORMATION` share: the flags (a `BOOLEAN` +/// `ReplaceIfExists` in their low byte before the `Ex` classes), the directory the new name is +/// relative to, and the name's length in bytes. The name follows the length, before the padding +/// that rounds the head up to a pointer's alignment. +struct NameInformationHead +{ + ULONG flags = 0; + HANDLE rootDirectory = nullptr; + ULONG fileNameLength = 0; +}; + +/// Where the name begins in a `FILE_RENAME_INFORMATION` or `FILE_LINK_INFORMATION`. +inline constexpr std::size_t NameInformationNameOffset = + offsetof(NameInformationHead, fileNameLength) + sizeof(ULONG); + +/// `NtSetInformationFile`, with the class taken as the `ULONG` it is passed as, since +/// ``'s `FILE_INFORMATION_CLASS` has none of the values used here. +using NtSetInformationFileFn = NTSTATUS(NTAPI*)(HANDLE, PIO_STATUS_BLOCK, PVOID, ULONG, ULONG); + +/// @return `NtSetInformationFile`, resolved once; null where `ntdll` lacks it, which no Windows does. +[[nodiscard]] inline NtSetInformationFileFn ntSetInformationFile() noexcept +{ + static auto const entry = []() noexcept -> NtSetInformationFileFn { + auto* const ntdll = ::GetModuleHandleW(L"ntdll.dll"); + if (ntdll == nullptr) + return nullptr; + // reinterpret_cast straight from FARPROC, never through `void*`: the documented way to use + // GetProcAddress (see core::net's WaitCompletionPacket.cpp). + return reinterpret_cast(::GetProcAddress(ntdll, "NtSetInformationFile")); + }(); + return entry; +} + +/// Gives @p handle's object the name @p name beneath @p directory: renames it, or links it there. +/// @param handle The object, open. +/// @param informationClass @c FileRenameInformationClass, @c FileRenameInformationExClass or +/// @c FileLinkInformationClass. +/// @param flags What the class takes as its flags. +/// @param directory A held directory handle on the same volume. +/// @param name One component in UTF-16. +/// @return Nothing; the NTSTATUS, classified, where it failed. +[[nodiscard]] inline FsResult ntSetName( + HANDLE handle, ULONG informationClass, ULONG flags, HANDLE directory, std::wstring const& name) +{ + auto const bytes = name.size() * sizeof(wchar_t); + if (bytes > std::numeric_limits::max() - NameInformationNameOffset) + return std::unexpected { FsError { + .code = FsErrorCode::NameTooLong, .systemCode = 0, .context = {} } }; + auto const head = NameInformationHead { .flags = flags, + .rootDirectory = directory, + .fileNameLength = static_cast(bytes) }; + // The head first, then the name over its padding. + auto buffer = std::vector(std::max(sizeof(head), NameInformationNameOffset + bytes)); + std::memcpy(buffer.data(), &head, sizeof(head)); + std::memcpy(buffer.data() + NameInformationNameOffset, name.data(), bytes); + auto const setInformation = ntSetInformationFile(); + if (setInformation == nullptr) + return std::unexpected { FsError { + .code = FsErrorCode::Unsupported, .systemCode = 0, .context = "NtSetInformationFile" } }; + auto status = IO_STATUS_BLOCK {}; + auto const result = + setInformation(handle, &status, buffer.data(), static_cast(buffer.size()), informationClass); + if (result < 0) + return std::unexpected { fsErrorFromNtStatus(std::int64_t { result }, "NtSetInformationFile") }; + return {}; +} + +/// @param text A name in UTF-8. +/// @return It in UTF-16; `IllegalByteSequence` where it is no UTF-8, `NameTooLong` past what the +/// conversion takes. +[[nodiscard]] inline FsResult utf16Of(std::string const& text) +{ + if (text.empty()) + return std::wstring {}; + if (text.size() > static_cast(std::numeric_limits::max())) + return std::unexpected { FsError { + .code = FsErrorCode::NameTooLong, .systemCode = 0, .context = {} } }; + auto const size = static_cast(text.size()); + auto const length = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, text.data(), size, nullptr, 0); + if (length <= 0) + return std::unexpected { FsError { + .code = FsErrorCode::IllegalByteSequence, .systemCode = 0, .context = {} } }; + auto wide = std::wstring(static_cast(length), L'\0'); + ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, text.data(), size, wide.data(), length); + return wide; +} + +/// @param text A name in UTF-16, as the file system holds it. +/// @return It in UTF-8; `IllegalByteSequence` for an unpaired surrogate, which UTF-8 cannot spell. +[[nodiscard]] inline FsResult utf8Of(std::wstring const& text) +{ + if (text.empty()) + return std::string {}; + if (text.size() > static_cast(std::numeric_limits::max())) + return std::unexpected { FsError { + .code = FsErrorCode::NameTooLong, .systemCode = 0, .context = {} } }; + auto const size = static_cast(text.size()); + auto const length = + ::WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, text.data(), size, nullptr, 0, nullptr, nullptr); + if (length <= 0) + return std::unexpected { FsError { + .code = FsErrorCode::IllegalByteSequence, .systemCode = 0, .context = {} } }; + auto narrow = std::string(static_cast(length), '\0'); + ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, text.data(), size, narrow.data(), length, nullptr, nullptr); + return narrow; +} + +} // namespace core::fs::detail diff --git a/src/core/fs/windows/NtStatusTable.cpp b/src/core/fs/windows/NtStatusTable.cpp new file mode 100644 index 00000000..9ca42aa5 --- /dev/null +++ b/src/core/fs/windows/NtStatusTable.cpp @@ -0,0 +1,81 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The NTSTATUS table: what NtCreateFile and NtSetInformationFile answer, mapped directly rather than +// through RtlNtStatusToDosError, whose Win32 codes lose distinctions the WASI codes keep. +#include + +#include +#include +#include + +// defines every STATUS_ code, and defines some of them again unless it is +// told not to: the documented order is this one. The codes are spelled `((NTSTATUS) ...)`, and every +// core-cpp target builds with WIN32_LEAN_AND_MEAN, under which no longer declares +// NTSTATUS; does. +#define WIN32_NO_STATUS +#include +#undef WIN32_NO_STATUS +#include +#include + +namespace core::fs +{ + +namespace +{ + + /// @return @p status as the signed 32-bit value the API returns, widened. + constexpr std::int64_t statusCode(NTSTATUS status) noexcept + { + return std::int64_t { status }; + } + + constexpr auto NtStatusRows = std::to_array({ + { .systemCode = statusCode(STATUS_ACCESS_DENIED), .code = FsErrorCode::Access }, + { .systemCode = statusCode(STATUS_DELETE_PENDING), .code = FsErrorCode::Access }, + { .systemCode = statusCode(STATUS_CANNOT_DELETE), .code = FsErrorCode::Access }, + { .systemCode = statusCode(STATUS_OBJECT_NAME_NOT_FOUND), .code = FsErrorCode::NoEntry }, + { .systemCode = statusCode(STATUS_OBJECT_PATH_NOT_FOUND), .code = FsErrorCode::NoEntry }, + { .systemCode = statusCode(STATUS_NO_SUCH_FILE), .code = FsErrorCode::NoEntry }, + { .systemCode = statusCode(STATUS_OBJECT_NAME_COLLISION), .code = FsErrorCode::Exist }, + { .systemCode = statusCode(STATUS_FILE_IS_A_DIRECTORY), .code = FsErrorCode::IsDirectory }, + { .systemCode = statusCode(STATUS_NOT_A_DIRECTORY), .code = FsErrorCode::NotDirectory }, + { .systemCode = statusCode(STATUS_DIRECTORY_NOT_EMPTY), .code = FsErrorCode::NotEmpty }, + { .systemCode = statusCode(STATUS_NOT_SAME_DEVICE), .code = FsErrorCode::CrossDevice }, + { .systemCode = statusCode(STATUS_DISK_FULL), .code = FsErrorCode::InsufficientSpace }, + { .systemCode = statusCode(STATUS_DISK_QUOTA_EXCEEDED), .code = FsErrorCode::Quota }, + { .systemCode = statusCode(STATUS_SHARING_VIOLATION), .code = FsErrorCode::Busy }, + { .systemCode = statusCode(STATUS_FILE_LOCK_CONFLICT), .code = FsErrorCode::Busy }, + { .systemCode = statusCode(STATUS_LOCK_NOT_GRANTED), .code = FsErrorCode::Busy }, + { .systemCode = statusCode(STATUS_OBJECT_NAME_INVALID), .code = FsErrorCode::Invalid }, + { .systemCode = statusCode(STATUS_OBJECT_PATH_SYNTAX_BAD), .code = FsErrorCode::Invalid }, + { .systemCode = statusCode(STATUS_INVALID_PARAMETER), .code = FsErrorCode::Invalid }, + { .systemCode = statusCode(STATUS_NOT_A_REPARSE_POINT), .code = FsErrorCode::Invalid }, + { .systemCode = statusCode(STATUS_STOPPED_ON_SYMLINK), .code = FsErrorCode::Loop }, + { .systemCode = statusCode(STATUS_REPARSE_POINT_NOT_RESOLVED), .code = FsErrorCode::Loop }, + // OBJ_DONT_REPARSE met a reparse point. Every open here names one component beneath a held + // handle, so the point is that component itself: a link that is not followed, which is + // Loop, as POSIX answers an O_NOFOLLOW open of one with ELOOP. + { .systemCode = statusCode(STATUS_REPARSE_POINT_ENCOUNTERED), .code = FsErrorCode::Loop }, + { .systemCode = statusCode(STATUS_IO_REPARSE_TAG_NOT_HANDLED), .code = FsErrorCode::Unsupported }, + { .systemCode = statusCode(STATUS_NOT_SUPPORTED), .code = FsErrorCode::Unsupported }, + { .systemCode = statusCode(STATUS_INVALID_DEVICE_REQUEST), .code = FsErrorCode::Unsupported }, + { .systemCode = statusCode(STATUS_INVALID_HANDLE), .code = FsErrorCode::BadDescriptor }, + { .systemCode = statusCode(STATUS_NAME_TOO_LONG), .code = FsErrorCode::NameTooLong }, + { .systemCode = statusCode(STATUS_NO_MEMORY), .code = FsErrorCode::InsufficientMemory }, + { .systemCode = statusCode(STATUS_INSUFFICIENT_RESOURCES), .code = FsErrorCode::InsufficientMemory }, + { .systemCode = statusCode(STATUS_MEDIA_WRITE_PROTECTED), .code = FsErrorCode::ReadOnly }, + { .systemCode = statusCode(STATUS_PRIVILEGE_NOT_HELD), .code = FsErrorCode::NotPermitted }, + { .systemCode = statusCode(STATUS_TOO_MANY_LINKS), .code = FsErrorCode::TooManyLinks }, + { .systemCode = statusCode(STATUS_FILE_TOO_LARGE), .code = FsErrorCode::FileTooLarge }, + { .systemCode = statusCode(STATUS_NO_SUCH_DEVICE), .code = FsErrorCode::NoSuchDevice }, + }); + +} // namespace + +std::span ntStatusTable() noexcept +{ + return NtStatusRows; +} + +} // namespace core::fs diff --git a/src/core/fs/windows/ReparsePoint.cpp b/src/core/fs/windows/ReparsePoint.cpp new file mode 100644 index 00000000..c54d2466 --- /dev/null +++ b/src/core/fs/windows/ReparsePoint.cpp @@ -0,0 +1,228 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The reparse data of symbolic links and mount points, field by field at the offsets of the driver +// kit's REPARSE_DATA_BUFFER: an 8-byte head (tag, length of what follows, reserved), then the +// offsets and lengths of the two names in bytes, a symbolic link's flags, and the names themselves, +// UTF-16, at those offsets from the start of the path buffer. +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace core::fs::detail +{ + +namespace +{ + + /// Where each field is, in bytes from the start of the data. + constexpr std::size_t TagOffset = 0; + constexpr std::size_t DataLengthOffset = 4; + constexpr std::size_t HeadSize = 8; ///< What `ReparseDataLength` does not count. + constexpr std::size_t SubstituteOffsetOffset = 8; + constexpr std::size_t SubstituteLengthOffset = 10; + constexpr std::size_t PrintOffsetOffset = 12; + constexpr std::size_t PrintLengthOffset = 14; + constexpr std::size_t SymlinkFlagsOffset = 16; + constexpr std::size_t SymlinkPathBufferOffset = 20; + constexpr std::size_t MountPointPathBufferOffset = 16; + + /// The layout of a point that names another object. + struct NamesLayout + { + std::uint32_t tag; + std::size_t pathBuffer; ///< Where its names begin. + }; + + constexpr auto NamesLayouts = std::to_array({ + { .tag = IO_REPARSE_TAG_SYMLINK, .pathBuffer = SymlinkPathBufferOffset }, + { .tag = IO_REPARSE_TAG_MOUNT_POINT, .pathBuffer = MountPointPathBufferOffset }, + }); + + std::unexpected refuseWith(FsErrorCode code) + { + return std::unexpected { FsError { .code = code, .systemCode = 0, .context = {} } }; + } + + template + T readAt(std::span bytes, std::size_t offset) noexcept + { + auto value = T {}; + std::memcpy(&value, bytes.data() + offset, sizeof(T)); + return value; + } + + template + void writeAt(std::vector& bytes, std::size_t offset, T value) noexcept + { + std::memcpy(bytes.data() + offset, &value, sizeof(T)); + } + + /// Encodes a point of @p tag whose names begin at @p pathBuffer: the substitute name, then the + /// print name, each followed by a NUL that the lengths do not count, as the system writes them. + std::vector encodeNames(std::uint32_t tag, + std::size_t pathBuffer, + std::uint32_t flags, + std::wstring_view substituteName, + std::wstring_view printName) + { + auto const substituteBytes = substituteName.size() * sizeof(wchar_t); + auto const printBytes = printName.size() * sizeof(wchar_t); + auto bytes = + std::vector(pathBuffer + substituteBytes + printBytes + (2 * sizeof(wchar_t))); + writeAt(bytes, TagOffset, tag); + writeAt(bytes, DataLengthOffset, static_cast(bytes.size() - HeadSize)); + writeAt(bytes, SubstituteOffsetOffset, std::uint16_t { 0 }); + writeAt(bytes, SubstituteLengthOffset, static_cast(substituteBytes)); + writeAt(bytes, PrintOffsetOffset, static_cast(substituteBytes + sizeof(wchar_t))); + writeAt(bytes, PrintLengthOffset, static_cast(printBytes)); + if (pathBuffer == SymlinkPathBufferOffset) + writeAt(bytes, SymlinkFlagsOffset, flags); + std::memcpy(bytes.data() + pathBuffer, substituteName.data(), substituteBytes); + std::memcpy( + bytes.data() + pathBuffer + substituteBytes + sizeof(wchar_t), printName.data(), printBytes); + return bytes; + } + + /// The name of @p bytes at @p offset and @p length from @p pathBuffer; `Invalid` outside them. + FsResult nameAt(std::span bytes, + std::size_t pathBuffer, + std::size_t offset, + std::size_t length) + { + if (length % sizeof(wchar_t) != 0 || pathBuffer + offset + length > bytes.size()) + return refuseWith(FsErrorCode::Invalid); + auto name = std::wstring(length / sizeof(wchar_t), L'\0'); + std::memcpy(name.data(), bytes.data() + pathBuffer + offset, length); + return name; + } + + /// What @c followedTarget and @c reportedTarget refuse: anything but a relative symbolic link. + FsResult requireRelativeLink(ReparseData const& data) + { + if (!isNameSurrogate(data.tag)) + return refuseWith(FsErrorCode::Invalid); + if (data.tag != IO_REPARSE_TAG_SYMLINK || data.target != LinkTarget::Relative) + return refuseWith(FsErrorCode::NotPermitted); + return {}; + } + +} // namespace + +std::vector relativeSymlinkReparseData(std::wstring_view substituteName, + std::wstring_view printName) +{ + return encodeNames( + IO_REPARSE_TAG_SYMLINK, SymlinkPathBufferOffset, SymlinkFlagRelative, substituteName, printName); +} + +std::vector mountPointReparseData(std::wstring_view substituteName, std::wstring_view printName) +{ + return encodeNames(IO_REPARSE_TAG_MOUNT_POINT, MountPointPathBufferOffset, 0, substituteName, printName); +} + +FsResult parseReparseData(std::span bytes) +{ + if (bytes.size() < HeadSize) + return refuseWith(FsErrorCode::Invalid); + auto data = ReparseData { .tag = readAt(bytes, TagOffset), + .substituteName = {}, + .printName = {}, + .target = LinkTarget::Absolute }; + auto const length = HeadSize + readAt(bytes, DataLengthOffset); + if (length > bytes.size()) + return refuseWith(FsErrorCode::Invalid); + auto const used = bytes.first(length); + auto const layout = std::ranges::find(NamesLayouts, data.tag, &NamesLayout::tag); + if (layout == NamesLayouts.end()) + return data; + if (used.size() < layout->pathBuffer) + return refuseWith(FsErrorCode::Invalid); + auto substitute = nameAt(used, + layout->pathBuffer, + readAt(used, SubstituteOffsetOffset), + readAt(used, SubstituteLengthOffset)); + auto print = nameAt(used, + layout->pathBuffer, + readAt(used, PrintOffsetOffset), + readAt(used, PrintLengthOffset)); + if (!substitute) + return std::unexpected { substitute.error() }; + if (!print) + return std::unexpected { print.error() }; + data.substituteName = std::move(*substitute); + data.printName = std::move(*print); + if (layout->pathBuffer == SymlinkPathBufferOffset + && (readAt(used, SymlinkFlagsOffset) & SymlinkFlagRelative) != 0) + data.target = LinkTarget::Relative; + return data; +} + +FsResult followedTarget(ReparseData const& data) +{ + return requireRelativeLink(data).and_then([&] { return utf8Of(data.substituteName); }); +} + +FsResult reportedTarget(ReparseData const& data) +{ + return requireRelativeLink(data).and_then([&] { + auto spelled = data.printName; + std::ranges::replace(spelled, L'/', L'\\'); + return utf8Of(!data.printName.empty() && spelled == data.substituteName ? data.printName + : data.substituteName); + }); +} + +FsResult readReparseData(HANDLE handle) +{ + auto bytes = std::vector(MAXIMUM_REPARSE_DATA_BUFFER_SIZE); + auto returned = DWORD { 0 }; + if (::DeviceIoControl(handle, + FSCTL_GET_REPARSE_POINT, + nullptr, + 0, + bytes.data(), + static_cast(bytes.size()), + &returned, + nullptr) + == FALSE) + return std::unexpected { fsErrorFromSystemCode(std::int64_t { ::GetLastError() }, + "DeviceIoControl(FSCTL_GET_REPARSE_POINT)") }; + return parseReparseData(std::span { bytes }.first(returned)); +} + +FsResult writeReparseData(HANDLE handle, std::span data) +{ + if (data.size() > MAXIMUM_REPARSE_DATA_BUFFER_SIZE) + return refuseWith(FsErrorCode::NameTooLong); + auto returned = DWORD { 0 }; + if (::DeviceIoControl(handle, + FSCTL_SET_REPARSE_POINT, + const_cast(data.data()), + static_cast(data.size()), + nullptr, + 0, + &returned, + nullptr) + == FALSE) + return std::unexpected { fsErrorFromSystemCode(std::int64_t { ::GetLastError() }, + "DeviceIoControl(FSCTL_SET_REPARSE_POINT)") }; + return {}; +} + +} // namespace core::fs::detail diff --git a/src/core/fs/windows/ReparsePoint.hpp b/src/core/fs/windows/ReparsePoint.hpp new file mode 100644 index 00000000..21d32118 --- /dev/null +++ b/src/core/fs/windows/ReparsePoint.hpp @@ -0,0 +1,102 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// What a reparse point holds, read and written through `FSCTL_GET_REPARSE_POINT` and +/// `FSCTL_SET_REPARSE_POINT`, and what a walk may do with it. The data's layout is the driver kit's +/// `REPARSE_DATA_BUFFER`, which `` does not declare: it is read and written here field by +/// field at its documented offsets, so no structure with a trailing array is cast over bytes. +/// +/// A symbolic link is followed only where it is relative; a junction, a mount point and every other +/// name surrogate name a place by an absolute path, and are never followed. Private to the fs module. + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace core::fs::detail +{ + +/// `SYMLINK_FLAG_RELATIVE` of the driver kit: the link's target is relative to the directory that +/// holds the link. +inline constexpr std::uint32_t SymlinkFlagRelative = 0x0000'0001U; + +/// Whether a link's target is resolved from the directory holding the link. +enum class LinkTarget : std::uint8_t +{ + Absolute, ///< From a volume or the object namespace (`\??\C:\...`): never followed. + Relative, ///< From the directory holding the link. +}; + +/// What a reparse point holds, as far as a walk needs it. +struct ReparseData +{ + std::uint32_t tag = 0; ///< The reparse tag. + std::wstring substituteName; ///< What the system follows (symbolic links and mount points). + std::wstring printName; ///< What a user is shown; may be empty. + LinkTarget target = LinkTarget::Absolute; ///< How @c substituteName is resolved. +}; + +/// @param tag A reparse tag. +/// @return Whether a point with @p tag names another object (a symbolic link, a junction, a mount +/// point), which is a link to a walk; any other point is a file of its own whose filter +/// supplies its data (a cloud placeholder, a deduplicated file). +[[nodiscard]] constexpr bool isNameSurrogate(std::uint32_t tag) noexcept +{ + return (tag & 0x2000'0000U) != 0; +} + +/// Encodes a relative symbolic link's reparse data. +/// @param substituteName The target as the system follows it, separated by `\`. +/// @param printName The target as it was given, read back by `readlinkAt`. +/// @return The data, for `FSCTL_SET_REPARSE_POINT`. +[[nodiscard]] CORE_FS_API std::vector relativeSymlinkReparseData(std::wstring_view substituteName, + std::wstring_view printName); + +/// Encodes a mount point's reparse data, as a junction is made: no flags, and the names after the +/// path offsets. +/// @param substituteName What the system follows (`\??\C:\dir\` or `\??\Volume{...}\`). +/// @param printName What a user is shown. +/// @return The data, for `FSCTL_SET_REPARSE_POINT`. +[[nodiscard]] CORE_FS_API std::vector mountPointReparseData(std::wstring_view substituteName, + std::wstring_view printName); + +/// Decodes reparse data. +/// @param bytes What `FSCTL_GET_REPARSE_POINT` returned. +/// @return The tag, with the names and the relative flag of a symbolic link or a mount point; +/// `Invalid` where the data is shorter than it says or its names lie outside it. +[[nodiscard]] CORE_FS_API FsResult parseReparseData(std::span bytes); + +/// What a walk follows: the target of a relative symbolic link. +/// @param data A decoded point. +/// @return The target in UTF-8; `NotPermitted` for an absolute link, a junction, a mount point or +/// any other name surrogate, whose target lies outside every directory a walk holds; +/// `Invalid` for a point that is no link at all. +[[nodiscard]] CORE_FS_API FsResult followedTarget(ReparseData const& data); + +/// What `readlinkAt` answers: the target of a relative symbolic link as it was given. That is the +/// print name, where it spells the substitute name with `/` for some of its `\`, and the substitute +/// name otherwise, so that what is read back is always what is followed. +/// @param data A decoded point. +/// @return The target in UTF-8; what @c followedTarget refuses, refused alike. +[[nodiscard]] CORE_FS_API FsResult reportedTarget(ReparseData const& data); + +/// Reads @p handle's reparse data. +/// @param handle A file opened as the point itself. +/// @return The data; `Invalid` where it is no reparse point. +[[nodiscard]] CORE_FS_API FsResult readReparseData(HANDLE handle); + +/// Writes @p data as @p handle's reparse point. +/// @param handle A file or directory opened with write access. +/// @param data Encoded reparse data. +/// @return Nothing; `NotPermitted` where a symbolic link needs a privilege the process lacks. +[[nodiscard]] CORE_FS_API FsResult writeReparseData(HANDLE handle, std::span data); + +} // namespace core::fs::detail diff --git a/src/core/fs/windows/Win32ErrorTable.cpp b/src/core/fs/windows/Win32ErrorTable.cpp new file mode 100644 index 00000000..2f56e05f --- /dev/null +++ b/src/core/fs/windows/Win32ErrorTable.cpp @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The Win32 error table, which the Win32 calls of the native descriptors answer in, and the empty +// O_NOFOLLOW list: Windows has no errno for an open to report. +#include + +#include +#include + +#include + +namespace core::fs +{ + +namespace +{ + + constexpr auto Win32ErrorRows = std::to_array({ + { .systemCode = ERROR_ACCESS_DENIED, .code = FsErrorCode::Access }, + { .systemCode = ERROR_DELETE_PENDING, .code = FsErrorCode::Access }, + { .systemCode = ERROR_FILE_NOT_FOUND, .code = FsErrorCode::NoEntry }, + { .systemCode = ERROR_PATH_NOT_FOUND, .code = FsErrorCode::NoEntry }, + { .systemCode = ERROR_ALREADY_EXISTS, .code = FsErrorCode::Exist }, + { .systemCode = ERROR_FILE_EXISTS, .code = FsErrorCode::Exist }, + { .systemCode = ERROR_DIR_NOT_EMPTY, .code = FsErrorCode::NotEmpty }, + { .systemCode = ERROR_DIRECTORY, .code = FsErrorCode::NotDirectory }, + { .systemCode = ERROR_NOT_SAME_DEVICE, .code = FsErrorCode::CrossDevice }, + { .systemCode = ERROR_DISK_FULL, .code = FsErrorCode::InsufficientSpace }, + { .systemCode = ERROR_HANDLE_DISK_FULL, .code = FsErrorCode::InsufficientSpace }, + { .systemCode = ERROR_DISK_QUOTA_EXCEEDED, .code = FsErrorCode::Quota }, + { .systemCode = ERROR_SHARING_VIOLATION, .code = FsErrorCode::Busy }, + { .systemCode = ERROR_LOCK_VIOLATION, .code = FsErrorCode::Busy }, + { .systemCode = ERROR_BUSY, .code = FsErrorCode::Busy }, + { .systemCode = ERROR_INVALID_NAME, .code = FsErrorCode::Invalid }, + { .systemCode = ERROR_INVALID_PARAMETER, .code = FsErrorCode::Invalid }, + { .systemCode = ERROR_NOT_A_REPARSE_POINT, .code = FsErrorCode::Invalid }, + { .systemCode = ERROR_CANT_RESOLVE_FILENAME, .code = FsErrorCode::Loop }, + { .systemCode = ERROR_STOPPED_ON_SYMLINK, .code = FsErrorCode::Loop }, + { .systemCode = ERROR_NO_UNICODE_TRANSLATION, .code = FsErrorCode::IllegalByteSequence }, + { .systemCode = ERROR_INVALID_HANDLE, .code = FsErrorCode::BadDescriptor }, + { .systemCode = ERROR_NOT_ENOUGH_MEMORY, .code = FsErrorCode::InsufficientMemory }, + { .systemCode = ERROR_OUTOFMEMORY, .code = FsErrorCode::InsufficientMemory }, + { .systemCode = ERROR_FILENAME_EXCED_RANGE, .code = FsErrorCode::NameTooLong }, + { .systemCode = ERROR_NOT_SUPPORTED, .code = FsErrorCode::Unsupported }, + { .systemCode = ERROR_WRITE_PROTECT, .code = FsErrorCode::ReadOnly }, + { .systemCode = ERROR_PRIVILEGE_NOT_HELD, .code = FsErrorCode::NotPermitted }, + { .systemCode = ERROR_TOO_MANY_LINKS, .code = FsErrorCode::TooManyLinks }, + { .systemCode = ERROR_FILE_TOO_LARGE, .code = FsErrorCode::FileTooLarge }, + { .systemCode = ERROR_BROKEN_PIPE, .code = FsErrorCode::Pipe }, + { .systemCode = ERROR_NEGATIVE_SEEK, .code = FsErrorCode::InvalidSeek }, + }); + +} // namespace + +std::span systemErrorTable() noexcept +{ + return Win32ErrorRows; +} + +std::span noFollowSymlinkErrnos() noexcept +{ + return {}; +} + +} // namespace core::fs diff --git a/src/core/fs/windows/WindowsDescriptor.cpp b/src/core/fs/windows/WindowsDescriptor.cpp new file mode 100644 index 00000000..9d8d125a --- /dev/null +++ b/src/core/fs/windows/WindowsDescriptor.cpp @@ -0,0 +1,1312 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The native descriptors of Windows. Every system call is made inside async::offload, on the +// blocking executor, by a job that holds the descriptor's handle by shared ownership (decision C2), +// and the caller resumes on its home executor. Rights are checked from rightsTable() before +// anything else, inside the job. +// +// A path is resolved beneath the descriptor by detail::resolveBeneath, one component at a time over +// held directory handles (windows/WindowsPathWalk.cpp), and the final name is acted on without +// following, in the directory the walk holds: opened with NtCreateFile relative to that handle, as +// the reparse point itself, then read, written, renamed or linked by handle. A link is made and read +// through FSCTL_SET_REPARSE_POINT and FSCTL_GET_REPARSE_POINT, renamed and linked through +// NtSetInformationFile with the new directory's handle as RootDirectory; no call takes a path. +// +// A directory stream opens the directory again by its handle (detail::openAgain), so its position +// is its own, and reads it with GetFileInformationByHandleEx(FileIdBothDirectoryInfo) into one +// 64 KiB buffer per batch, one offload each; each record carries what its entry is. +#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 +#include +#include +#include + +namespace core::fs +{ + +void detail::closeNativeHandle(platform::NativeHandle handle) noexcept +{ + ::CloseHandle(handle); +} + +namespace +{ + + using detail::NativeContext; + using detail::refuse; + using detail::SharedContext; + using detail::SharedHandle; + using detail::UniqueHandle; + + /// What the kernel splits a name on (and `:`, which names a stream): never part of a name handed + /// to it, whatever the policy. + constexpr std::string_view KernelSeparators = "\\/:"; + + /// The largest offset a positioned read or write takes. + constexpr auto OffsetMax = static_cast(std::numeric_limits::max()); + + /// 100-nanosecond intervals from 1601-01-01 to 1970-01-01, and per second. + constexpr std::int64_t UnixEpochTicks = 116'444'736'000'000'000; + constexpr std::int64_t TicksPerSecond = 10'000'000; + constexpr std::int64_t NanosecondsPerTick = 100; + + std::unexpected lastError(char const* call) + { + return std::unexpected { fsErrorFromSystemCode(std::int64_t { ::GetLastError() }, call) }; + } + + FsResult succeededOr(BOOL result, char const* call) + { + if (result == FALSE) + return lastError(call); + return {}; + } + + FileTime fileTimeOf(LARGE_INTEGER ticks) noexcept + { + auto const sinceEpoch = ticks.QuadPart - UnixEpochTicks; + auto seconds = sinceEpoch / TicksPerSecond; + auto remainder = sinceEpoch % TicksPerSecond; + if (remainder < 0) + { + --seconds; + remainder += TicksPerSecond; + } + return FileTime { .seconds = seconds, + .nanoseconds = static_cast(remainder * NanosecondsPerTick) }; + } + + /// @return @p time in FILETIME ticks; `Invalid` past what 64 bits hold, and at or before + /// 1601-01-01T00:00:00Z: `FILE_BASIC_INFO` reads a time of 0 as "leave it" and -1 as + /// "stop updating it", so neither instant can be set, and refusing says so rather than + /// doing something else silently. + FsResult ticksOf(FileTime time) + { + constexpr auto Max = std::numeric_limits::max(); + if (time.nanoseconds >= 1'000'000'000) + return refuse(FsErrorCode::Invalid); + if (time.seconds < -UnixEpochTicks / TicksPerSecond + || time.seconds > ((Max - UnixEpochTicks) / TicksPerSecond) - 1) + return refuse(FsErrorCode::Invalid); + auto const ticks = + UnixEpochTicks + (time.seconds * TicksPerSecond) + (time.nanoseconds / NanosecondsPerTick); + if (ticks <= 0) + return refuse(FsErrorCode::Invalid); + return ticks; + } + + /// Replaces `SetToNow` with the wall clock's instant, read on the caller's thread before the hop, + /// so the clock is never read from the blocking executor. + NewTimestamp resolveNow(NewTimestamp change, platform::IWallClock const& clock) + { + if (std::holds_alternative(change)) + return detail::fileTimeOf(clock.now()); + return change; + } + + /// The `FILE_BASIC_INFO` time for @p change, `SetToNow` already resolved: 0 leaves the time. + FsResult basicTimeOf(NewTimestamp const& change) + { + if (auto const* time = std::get_if(&change)) + return ticksOf(*time); + if (std::holds_alternative(change)) + return std::int64_t { 0 }; + return refuse(FsErrorCode::Invalid); + } + + /// What one handle tells about its object. + struct Information + { + FILE_BASIC_INFO basic {}; + FILE_STANDARD_INFO standard {}; + FILE_ATTRIBUTE_TAG_INFO tag {}; + }; + + FsResult informationOf(HANDLE handle) + { + auto information = Information {}; + if (::GetFileInformationByHandleEx( + handle, FileBasicInfo, &information.basic, sizeof(information.basic)) + == FALSE + || ::GetFileInformationByHandleEx( + handle, FileStandardInfo, &information.standard, sizeof(information.standard)) + == FALSE) + return lastError("GetFileInformationByHandleEx"); + if (::GetFileInformationByHandleEx( + handle, FileAttributeTagInfo, &information.tag, sizeof(information.tag)) + == FALSE) + { + // FAT and exFAT keep no reparse point and answer no FileAttributeTagInfo: their + // attributes are the basic ones, and no tag. + if (::GetLastError() != ERROR_INVALID_PARAMETER) + return lastError("GetFileInformationByHandleEx"); + information.tag = FILE_ATTRIBUTE_TAG_INFO { .FileAttributes = information.basic.FileAttributes, + .ReparseTag = 0 }; + } + return information; + } + + /// A reparse point that names another object (a symbolic link, a junction, a mount point) is a + /// link; one that names nothing else is the file or directory it is. + DescriptorType typeOf(Information const& information) noexcept + { + auto const attributes = detail::EntryAttributes { .attributes = information.tag.FileAttributes, + .reparseTag = information.tag.ReparseTag }; + if (attributes.isLink()) + return DescriptorType::SymbolicLink; + if (information.standard.Directory != FALSE) + return DescriptorType::Directory; + return DescriptorType::RegularFile; + } + + DescriptorStat statOf(Information const& information) noexcept + { + return DescriptorStat { .type = typeOf(information), + .linkCount = information.standard.NumberOfLinks, + .size = static_cast(information.standard.EndOfFile.QuadPart), + .accessed = fileTimeOf(information.basic.LastAccessTime), + .modified = fileTimeOf(information.basic.LastWriteTime), + .statusChanged = fileTimeOf(information.basic.ChangeTime) }; + } + + FsResult hashOf(NativeContext const& context, HANDLE handle) + { + auto const identity = context.ntFiles->identity(handle); + if (!identity) + return std::unexpected { identity.error() }; + return informationOf(handle).transform([&](Information const& information) { + return detail::hashMetadata( + context.secret, + detail::MetadataFields { + .device = identity->volume, + .fileIdLow = identity->idLow, + .fileIdHigh = identity->idHigh, + .size = static_cast(information.standard.EndOfFile.QuadPart), + .modified = fileTimeOf(information.basic.LastWriteTime), + .statusChanged = fileTimeOf(information.basic.ChangeTime) }); + }); + } + + /// How far a directory stream has read its directory. + enum class ListingProgress : std::uint8_t + { + AtStart, ///< No batch has been read. + Started, ///< At least one has. + }; + + /// A Win32 code the listing call answers that is the end of the directory rather than a failure. + struct ListingEndRow + { + DWORD code; + /// The code ends the directory only on the first batch, or on any. + std::optional onlyAt; + }; + + constexpr auto ListingEndRows = std::to_array({ + { .code = ERROR_NO_MORE_FILES, .onlyAt = std::nullopt }, + // A directory with no entry at all, not even `.` and `..`, as a FAT or exFAT volume's root + // is (STATUS_NO_SUCH_FILE); later, the same code would be a failure. + { .code = ERROR_FILE_NOT_FOUND, .onlyAt = ListingProgress::AtStart }, + }); + + /// A directory stream's own handle on its directory, the NT calls it lists through and the + /// buffer its batches are read into, shared by the stream and the batch read in flight. The + /// handle keeps a position, so a batch holds @c lock while it reads. + struct DirectoryReader + { + SharedHandle handle; ///< Opened for the stream alone. + detail::INtFiles const* files; ///< What it lists through. + std::mutex lock; ///< Held by the batch that reads. + std::vector records; ///< @c detail::DirectoryBufferBytes, 8-byte aligned. + ListingProgress progress = ListingProgress::AtStart; ///< Under @c lock. + + DirectoryReader(SharedHandle directory, detail::INtFiles const& ntFiles): + handle { std::move(directory) }, + files { &ntFiles }, + records(detail::DirectoryBufferBytes / sizeof(std::uint64_t)) + { + } + }; + + /// @return Whether @p error, met at @p progress, is the end of the directory. + bool endsListing(FsError const& error, ListingProgress progress) noexcept + { + return std::ranges::any_of(ListingEndRows, [&](ListingEndRow const& row) { + return error.systemCode == std::int64_t { row.code } && (!row.onlyAt || *row.onlyAt == progress); + }); + } + + /// Reads the records that fit in @p reader's buffer, from where its handle stands. + FsResult readBatch(DirectoryReader& reader) + { + auto const held = std::scoped_lock { reader.lock }; + auto const buffer = std::as_writable_bytes(std::span { reader.records }); + auto const progress = std::exchange(reader.progress, ListingProgress::Started); + if (auto listed = reader.files->queryDirectory(reader.handle->get(), buffer); !listed) + { + if (endsListing(listed.error(), progress)) + return detail::DirectoryBatch { .entries = {}, .end = StreamEnd::Reached }; + return std::unexpected { std::move(listed.error()) }; + } + return detail::parseDirectoryRecords(buffer).transform( + [](std::vector> entries) { + return detail::DirectoryBatch { .entries = std::move(entries), .end = StreamEnd::More }; + }); + } + + class WindowsDirectoryStream final: public detail::BatchedDirectoryStream + { + public: + WindowsDirectoryStream(SharedContext context, std::shared_ptr reader): + _context { std::move(context) }, _reader { std::move(reader) } + { + } + + protected: + async::Task> fetch() override + { + return async::offload( + _context->home, _context->blocking, [reader = _reader]() { return readBatch(*reader); }); + } + + private: + SharedContext _context; + std::shared_ptr _reader; + }; + + /// What a directory stream opens its directory again with. + constexpr auto ListRequest = detail::NtOpenRequest { .access = FILE_LIST_DIRECTORY, + .disposition = FILE_OPEN, + .options = FILE_DIRECTORY_FILE }; + + using detail::EntryKind; + using detail::FinalComponent; + using detail::Resolved; + using detail::TrailingSlashOnLink; + + /// Resolves @p path beneath @p root, following a final link where @p finalPolicy, or a trailing + /// `/` under @p onLink, says so. + FsResult resolve(HANDLE root, + std::string_view path, + NativeContext const& context, + SymlinkPolicy finalPolicy, + TrailingSlashOnLink onLink) + { + return detail::planRelativePath(path, *context.policy).and_then([&](detail::PathPlan plan) { + return detail::resolveBeneathWith( + *context.ntFiles, root, std::move(plan), detail::walkRulesOf(context, finalPolicy, onLink)); + }); + } + + /// @return @p resolved, where it names a place an entry of @p creating can be made; `Exist` + /// where something is there already (the directory itself included), `NotDirectory` + /// where the path ends in `/` and @p creating is not a directory. + FsResult vacant(Resolved resolved, DescriptorType creating) + { + if (resolved.name.empty() || resolved.kind != EntryKind::Missing) + return refuse(FsErrorCode::Exist); + if (creating != DescriptorType::Directory && resolved.finalComponent == FinalComponent::Directory) + return refuse(FsErrorCode::NotDirectory); + return resolved; + } + + /// Opens the final name of @p resolved, not following it: the directory itself again where the + /// path names it. + FsResult openFinal(NativeContext const& context, + Resolved const& resolved, + detail::NtOpenRequest const& request) + { + return detail::utf16Of(resolved.name).and_then([&](std::wstring const& name) { + return context.ntFiles->open(resolved.directory(), name, request); + }); + } + + /// @return The request that opens an entry to read its attributes and, with @p access, more. + detail::NtOpenRequest attributesRequest(ACCESS_MASK access) noexcept + { + return detail::NtOpenRequest { .access = access | FILE_READ_ATTRIBUTES, + .disposition = FILE_OPEN, + .options = 0, + .reparse = detail::ReparseHandling::OpenThePoint }; + } + + struct SyncFlagRow + { + DescriptorFlags flag; + ULONG createOption; ///< 0 where Windows has no such mode. + }; + + constexpr auto SyncFlagRows = std::to_array({ + { .flag = DescriptorFlags::FileIntegritySync, .createOption = FILE_WRITE_THROUGH }, + { .flag = DescriptorFlags::DataIntegritySync, .createOption = FILE_WRITE_THROUGH }, + { .flag = DescriptorFlags::RequestedWriteSync, .createOption = 0 }, + }); + + /// The `NtCreateFile` request for @p open and @p flags. + FsResult openRequestOf(OpenFlags open, DescriptorFlags flags) + { + auto request = + detail::NtOpenRequest { .access = FILE_READ_ATTRIBUTES, .disposition = FILE_OPEN, .options = 0 }; + if (hasFlag(flags, DescriptorFlags::Read)) + request.access |= FILE_GENERIC_READ; + if (hasFlag(flags, DescriptorFlags::Write)) + request.access |= FILE_GENERIC_WRITE; + if (hasFlag(flags, DescriptorFlags::MutateDirectory)) + request.access |= FILE_WRITE_ATTRIBUTES; + auto const create = hasFlag(open, OpenFlags::Create); + auto const truncate = hasFlag(open, OpenFlags::Truncate); + // Never an overwrite disposition: it would truncate whatever the name opens before the + // caller sees what that is, a symbolic link included. openAt truncates by handle, after. + if (create && hasFlag(open, OpenFlags::Exclusive)) + request.disposition = FILE_CREATE; + else if (create) + request.disposition = FILE_OPEN_IF; + if (truncate) + request.access |= FILE_WRITE_DATA; + if (hasFlag(open, OpenFlags::Directory)) + request.options |= FILE_DIRECTORY_FILE; + // A directory never carries Write, and is never created or truncated by openAt. + if (hasFlag(flags, DescriptorFlags::Write) || create || truncate) + request.options |= FILE_NON_DIRECTORY_FILE; + for (auto const& row: SyncFlagRows) + { + if (!hasFlag(flags, row.flag)) + continue; + if (row.createOption == 0) + return refuse(FsErrorCode::Unsupported); + request.options |= row.createOption; + } + return request; + } + + /// Marks @p handle's object for deletion with POSIX semantics (its name goes at once, even while + /// another handle is open on it), or the classic way where the file system has no such mode. + FsResult deleteOpened(HANDLE handle) + { + auto posix = FILE_DISPOSITION_INFO_EX { .Flags = FILE_DISPOSITION_FLAG_DELETE + | FILE_DISPOSITION_FLAG_POSIX_SEMANTICS + | FILE_DISPOSITION_FLAG_IGNORE_READONLY_ATTRIBUTE }; + if (::SetFileInformationByHandle(handle, FileDispositionInfoEx, &posix, sizeof(posix)) != FALSE) + return {}; + auto const error = ::GetLastError(); + if (error != ERROR_INVALID_PARAMETER && error != ERROR_NOT_SUPPORTED + && error != ERROR_INVALID_FUNCTION) + return std::unexpected { fsErrorFromSystemCode(std::int64_t { error }, + "SetFileInformationByHandle") }; + auto classic = FILE_DISPOSITION_INFO { .DeleteFile = TRUE }; + return succeededOr( + ::SetFileInformationByHandle(handle, FileDispositionInfo, &classic, sizeof(classic)), + "SetFileInformationByHandle"); + } + + FsResult truncateOpened(HANDLE handle) + { + auto end = FILE_END_OF_FILE_INFO {}; + end.EndOfFile.QuadPart = 0; + return succeededOr(::SetFileInformationByHandle(handle, FileEndOfFileInfo, &end, sizeof(end)), + "SetFileInformationByHandle"); + } + + /// @return Whether @p resolved's final name is a directory link, which is a directory to the + /// system: no file replaces it, as none replaces a directory. + bool isDirectoryLink(NativeContext const& context, Resolved const& resolved) + { + if (resolved.kind != EntryKind::SymbolicLink) + return false; + auto const link = openFinal(context, resolved, attributesRequest(0)); + if (!link) + return false; + auto const attributes = context.ntFiles->attributes(link->get()); + return attributes && attributes->isDirectory(); + } + + /// Whether a symbolic link is made as a directory link, which is what the system, and every + /// program on it, can follow to a directory; to this file system both are links alike. + enum class LinkFlavour : std::uint8_t + { + File, + Directory, + }; + + /// @return The flavour of a link to @p target made at @p newPath beneath @p root: a directory + /// link where the target says so by its spelling (it ends in a separator, `.` or `..`), + /// or where it names a directory beneath @p root when followed from where the link will + /// be; a file link otherwise, a target that cannot be resolved beneath @p root included. + LinkFlavour flavourOf(HANDLE root, + std::string_view newPath, + std::string_view target, + NativeContext const& context) + { + auto const& policy = *context.policy; + auto const last = target.substr(target.find_last_of(policy.targetSeparators) + 1); + if (last.empty() || last == "." || last == "..") + return LinkFlavour::Directory; + auto plan = detail::planRelativePath(newPath, policy); + if (!plan || !detail::spliceSymlink(*plan, plan->components.size() - 1, target, policy)) + return LinkFlavour::File; + auto const followed = detail::resolveBeneathWith( + *context.ntFiles, + root, + std::move(*plan), + detail::walkRulesOf(context, SymlinkPolicy::Follow, TrailingSlashOnLink::Follow)); + if (followed && (followed->name.empty() || followed->kind == EntryKind::Directory)) + return LinkFlavour::Directory; + return LinkFlavour::File; + } + + /// Checks a link's substitute name against what the kernel itself reads in a relative link's + /// target, whatever the policy let through: a leading `\` resolves from the volume's root and + /// `\??\` from the object namespace, so either is `NotPermitted`; a `:` names a drive in the + /// first component (`NotPermitted`) and a stream anywhere else (`Invalid`). + FsResult checkKernelTarget(std::wstring const& substituteName) + { + if (substituteName.starts_with(L'\\')) + return refuse(FsErrorCode::NotPermitted); + auto const colon = substituteName.find(L':'); + if (colon == std::wstring::npos) + return {}; + if (colon < substituteName.find(L'\\')) + return refuse(FsErrorCode::NotPermitted); + return refuse(FsErrorCode::Invalid); + } + + /// Makes @p resolved's name a symbolic link to @p target: a new file or directory, given the + /// link's reparse data, and removed again where that is refused. Where the removal fails too, the + /// refusal is still the write's, which says why the link was not made, and its context names the + /// empty entry left behind. + FsResult createSymlink(NativeContext const& context, + Resolved const& resolved, + std::string const& target, + LinkFlavour flavour) + { + auto const printName = detail::utf16Of(target); + if (!printName) + return std::unexpected { printName.error() }; + auto substituteName = *printName; + std::ranges::replace(substituteName, L'/', L'\\'); + if (auto checked = checkKernelTarget(substituteName); !checked) + return checked; + auto const link = + openFinal(context, + resolved, + detail::NtOpenRequest { + .access = FILE_WRITE_DATA | FILE_WRITE_ATTRIBUTES | FILE_READ_ATTRIBUTES | DELETE, + .disposition = FILE_CREATE, + .options = flavour == LinkFlavour::Directory ? ULONG { FILE_DIRECTORY_FILE } + : ULONG { FILE_NON_DIRECTORY_FILE }, + .reparse = detail::ReparseHandling::OpenThePoint }); + if (!link) + return std::unexpected { link.error() }; + auto written = detail::writeReparseData( + link->get(), detail::relativeSymlinkReparseData(substituteName, *printName)); + if (written) + return written; + auto failure = written.error(); + if (auto removed = deleteOpened(link->get()); !removed) + failure.context += + "; the empty entry made for the link was not removed: " + removed.error().toString(); + return std::unexpected { std::move(failure) }; + } + + /// The statuses with which a file system refuses `FileRenameInformationEx` it does not know. + constexpr auto RenameExUnknownStatuses = std::to_array({ STATUS_INVALID_INFO_CLASS, + STATUS_NOT_IMPLEMENTED, + STATUS_NOT_SUPPORTED, + STATUS_INVALID_PARAMETER }); + + /// Renames @p handle's object to @p name beneath @p directory, replacing what is there: with POSIX + /// semantics, so an open target's name goes at once, where the file system knows them. + FsResult renameOpened(HANDLE handle, HANDLE directory, std::wstring const& name) + { + auto renamed = detail::ntSetName(handle, + detail::FileRenameInformationExClass, + detail::RenameReplaceIfExists | detail::RenamePosixSemantics + | detail::RenameIgnoreReadOnlyAttribute, + directory, + name); + if (renamed + || std::ranges::find(RenameExUnknownStatuses, renamed.error().systemCode) + == RenameExUnknownStatuses.end()) + return renamed; + return detail::ntSetName( + handle, detail::FileRenameInformationClass, detail::RenameReplaceIfExists, directory, name); + } + + FsResult setTimesOf(HANDLE handle, NewTimestamp const& accessed, NewTimestamp const& modified) + { + auto const accessTicks = basicTimeOf(accessed); + if (!accessTicks) + return std::unexpected { accessTicks.error() }; + auto const writeTicks = basicTimeOf(modified); + if (!writeTicks) + return std::unexpected { writeTicks.error() }; + auto basic = FILE_BASIC_INFO {}; + basic.LastAccessTime.QuadPart = *accessTicks; + basic.LastWriteTime.QuadPart = *writeTicks; + return succeededOr(::SetFileInformationByHandle(handle, FileBasicInfo, &basic, sizeof(basic)), + "SetFileInformationByHandle"); + } + + OVERLAPPED overlappedAt(std::uint64_t offset) noexcept + { + auto overlapped = OVERLAPPED {}; + overlapped.Offset = static_cast(offset & 0xFFFF'FFFFU); + overlapped.OffsetHigh = static_cast(offset >> 32U); + return overlapped; + } + + /// Writes all of @p bytes through @p handle, each chunk placed by @p offsetOf. + template + FsResult writeAll(HANDLE handle, std::span bytes, OffsetOf offsetOf) + { + auto written = std::size_t { 0 }; + while (written < bytes.size()) + { + auto const chunk = static_cast( + std::min(bytes.size() - written, std::numeric_limits::max())); + auto overlapped = offsetOf(written); + auto count = DWORD { 0 }; + if (::WriteFile(handle, bytes.data() + written, chunk, &count, &overlapped) == FALSE) + { + if (written > 0) + break; + return lastError("WriteFile"); + } + if (count == 0) + break; + written += count; + } + return written; + } + + class WindowsDescriptor final: public detail::NativeDescriptorBase + { + public: + WindowsDescriptor(SharedContext context, + SharedHandle handle, + SharedHandle appendHandle, + DescriptorFlags flags, + DescriptorType type): + NativeDescriptorBase { std::move(context), std::move(handle), flags, type }, + _appendHandle { std::move(appendHandle) } + { + } + + async::Task> read(std::size_t maxBytes, std::uint64_t offset) override + { + return submit([handle = handle(), + flags = flags(), + type = objectType(), + want = std::min({ maxBytes, + context()->options.maxReadChunk, + std::size_t { std::numeric_limits::max() } }), + offset]() -> FsResult { + return checkRights(flags, Operation::Read).and_then([&]() -> FsResult { + if (offset > OffsetMax) + return ReadChunk { .bytes = {}, .end = StreamEnd::Reached }; + auto bytes = std::vector(want); + auto overlapped = overlappedAt(offset); + auto count = DWORD { 0 }; + if (::ReadFile(handle->get(), bytes.data(), static_cast(want), &count, &overlapped) + == FALSE + && ::GetLastError() != ERROR_HANDLE_EOF) + { + // A directory's handle reads nothing: POSIX's EISDIR, said in Windows' words. + if (::GetLastError() == ERROR_INVALID_FUNCTION && type == DescriptorType::Directory) + return refuse(FsErrorCode::IsDirectory); + return lastError("ReadFile"); + } + bytes.resize(count); + auto const end = bytes.size() < want ? StreamEnd::Reached : StreamEnd::More; + return ReadChunk { .bytes = std::move(bytes), .end = end }; + }); + }); + } + + async::Task> write(std::vector bytes, std::uint64_t offset) override + { + return submit([handle = handle(), flags = flags(), bytes = std::move(bytes), offset]() { + return checkRights(flags, Operation::Write).and_then([&]() -> FsResult { + if (offset > OffsetMax || bytes.size() > OffsetMax - offset) + return refuse(FsErrorCode::FileTooLarge); + return writeAll(handle->get(), bytes, [offset](std::size_t written) { + return overlappedAt(offset + written); + }); + }); + }); + } + + async::Task> append(std::vector bytes) override + { + return submit([appendHandle = _appendHandle, flags = flags(), bytes = std::move(bytes)]() { + return checkRights(flags, Operation::Append).and_then([&]() -> FsResult { + if (!appendHandle) + return refuse(FsErrorCode::BadDescriptor); + // An offset of all ones writes at the end of the file. + return writeAll(appendHandle->get(), bytes, [](std::size_t) { + auto overlapped = OVERLAPPED {}; + overlapped.Offset = 0xFFFF'FFFFU; + overlapped.OffsetHigh = 0xFFFF'FFFFU; + return overlapped; + }); + }); + }); + } + + async::Task> advise(std::uint64_t, std::uint64_t, Advice) override + { + // Windows takes no advice on a range of an open file; it succeeds, as advice may. + return submit([flags = flags()]() { return checkRights(flags, Operation::Advise); }); + } + + async::Task> syncData() override { return sync(); } + + async::Task> sync() override + { + return submit([handle = handle(), flags = flags()]() { + return checkRights(flags, Operation::Sync).and_then([&]() -> FsResult { + // FlushFileBuffers needs write access, which a read-only or directory handle + // lacks; such a descriptor wrote nothing to flush, and succeeds as fsync does. + if (!hasFlag(flags, DescriptorFlags::Write)) + return {}; + return succeededOr(::FlushFileBuffers(handle->get()), "FlushFileBuffers"); + }); + }); + } + + async::Task> type() override + { + return submit([handle = handle(), flags = flags()]() { + return checkRights(flags, Operation::Stat) + .and_then([&] { return informationOf(handle->get()); }) + .transform([](Information const& information) { return typeOf(information); }); + }); + } + + async::Task> setSize(std::uint64_t size) override + { + return submit([handle = handle(), flags = flags(), size]() { + return checkRights(flags, Operation::SetSize).and_then([&]() -> FsResult { + if (size > OffsetMax) + return refuse(FsErrorCode::FileTooLarge); + auto end = FILE_END_OF_FILE_INFO {}; + end.EndOfFile.QuadPart = static_cast(size); + return succeededOr( + ::SetFileInformationByHandle(handle->get(), FileEndOfFileInfo, &end, sizeof(end)), + "SetFileInformationByHandle"); + }); + }); + } + + async::Task> setTimes(NewTimestamp accessed, NewTimestamp modified) override + { + auto const& clock = *context()->wallClock; + return submit([handle = handle(), + flags = flags(), + accessed = resolveNow(accessed, clock), + modified = resolveNow(modified, clock)]() { + return checkRights(flags, Operation::SetTimes).and_then([&] { + return setTimesOf(handle->get(), accessed, modified); + }); + }); + } + + async::Task> stat() override + { + return submit([handle = handle(), flags = flags()]() { + return checkRights(flags, Operation::Stat) + .and_then([&] { return informationOf(handle->get()); }) + .transform([](Information const& information) { return statOf(information); }); + }); + } + + async::Task> metadataHash() override + { + return submit([context = context(), handle = handle(), flags = flags()]() { + return checkRights(flags, Operation::MetadataHash).and_then([&] { + return hashOf(*context, handle->get()); + }); + }); + } + + async::Task>> readDirectory() override + { + return submit([context = context(), handle = handle(), flags = flags(), type = objectType()]() { + auto const& files = *context->ntFiles; + return checkRights(flags, Operation::ReadDirectory) + .and_then([&] { return detail::requireDirectory(type); }) + .and_then([&] { return files.attributes(handle->get()); }) + .and_then([&](detail::EntryAttributes const& attributes) { + return detail::openAgain(files, handle->get(), attributes, ListRequest); + }) + .transform([&](UniqueHandle opened) -> std::unique_ptr { + return std::make_unique( + context, + std::make_shared( + detail::shareHandle(std::move(opened), *context->blocking), files)); + }); + }); + } + + async::Task>> openAt(SymlinkPolicy policy, + std::string path, + OpenFlags open, + DescriptorFlags childFlags) override + { + return submit([context = context(), + handle = handle(), + flags = flags(), + type = objectType(), + policy, + path = std::move(path), + open, + childFlags]() -> FsResult> { + // Create | Exclusive never follows a final link: a dangling one is Exist rather than + // created through. + auto const exclusive = + hasFlag(open, OpenFlags::Create) && hasFlag(open, OpenFlags::Exclusive); + auto const resolved = checkRights(flags, Operation::OpenAt) + .and_then([&] { return checkOpenRights(flags, open, childFlags); }) + .and_then([&] { return detail::requireDirectory(type); }) + .and_then([&] { + return resolve(handle->get(), + path, + *context, + exclusive ? SymlinkPolicy::NoFollow : policy, + TrailingSlashOnLink::Follow); + }); + if (!resolved) + return std::unexpected { resolved.error() }; + auto request = openRequestOf(open, childFlags); + if (!request) + return std::unexpected { request.error() }; + // A link not followed is Loop, as `O_NOFOLLOW` answers, before the request's + // FILE_NON_DIRECTORY_FILE could call a directory link IsDirectory. + if (!exclusive && resolved->kind == EntryKind::SymbolicLink) + return refuse(FsErrorCode::Loop); + if (resolved->finalComponent == FinalComponent::Directory && !resolved->name.empty()) + { + // `name/` opens nothing but a directory, and creates none. + if (resolved->kind == EntryKind::Missing && hasFlag(open, OpenFlags::Create)) + return refuse(FsErrorCode::NotDirectory); + request->options |= FILE_DIRECTORY_FILE; + } + auto const name = detail::utf16Of(resolved->name); + if (!name) + return std::unexpected { name.error() }; + auto child = detail::openEntry(*context->ntFiles, resolved->directory(), *name, *request); + if (!child) + return std::unexpected { child.error() }; + auto const opened = child->handle.get(); + auto const information = informationOf(opened); + if (!information) + return std::unexpected { information.error() }; + auto const childType = typeOf(*information); + // The name became a link since the walk looked: the kernel opened the link itself, + // and changed nothing. + if (childType == DescriptorType::SymbolicLink) + return refuse(FsErrorCode::Loop); + // Truncated by handle only now that the handle is known to be a file's. + if (hasFlag(open, OpenFlags::Truncate) && childType == DescriptorType::RegularFile) + if (auto truncated = truncateOpened(opened); !truncated) + return std::unexpected { truncated.error() }; + auto appendHandle = SharedHandle {}; + if (hasFlag(childFlags, DescriptorFlags::Write) && childType == DescriptorType::RegularFile) + { + // The append handle is the same object opened again by its handle, never by + // ReOpenFile, which would follow a reparse point put on the file since; it writes + // through as the first does, where a sync mode asks. + auto second = detail::openAgain( + *context->ntFiles, + *child, + detail::NtOpenRequest { .access = FILE_APPEND_DATA, + .disposition = FILE_OPEN, + .options = FILE_NON_DIRECTORY_FILE + | (request->options & FILE_WRITE_THROUGH), + .reparse = detail::ReparseHandling::OpenThePoint }); + if (!second) + return std::unexpected { second.error() }; + appendHandle = detail::shareHandle(std::move(*second), *context->blocking); + } + return std::make_unique( + context, + detail::shareHandle(std::move(child->handle), *context->blocking), + std::move(appendHandle), + grantedFlags(childType, childFlags), + childType); + }); + } + + async::Task> createDirectoryAt(std::string path) override + { + return submit([context = context(), + handle = handle(), + flags = flags(), + type = objectType(), + path = std::move(path)]() { + return checkRights(flags, Operation::CreateDirectoryAt) + .and_then([&] { return detail::requireDirectory(type); }) + .and_then([&] { + return resolve(handle->get(), + path, + *context, + SymlinkPolicy::NoFollow, + TrailingSlashOnLink::Follow); + }) + .and_then([](Resolved resolved) { + return vacant(std::move(resolved), DescriptorType::Directory); + }) + .and_then([&](Resolved const& resolved) { + return openFinal( + *context, + resolved, + detail::NtOpenRequest { .access = FILE_LIST_DIRECTORY, + .disposition = FILE_CREATE, + .options = FILE_DIRECTORY_FILE, + .reparse = detail::ReparseHandling::OpenThePoint }) + .transform([](UniqueHandle const&) {}); + }); + }); + } + + async::Task> statAt(SymlinkPolicy policy, std::string path) override + { + return submit([context = context(), + handle = handle(), + flags = flags(), + type = objectType(), + policy, + path = std::move(path)]() { + return checkRights(flags, Operation::StatAt) + .and_then([&] { return detail::requireDirectory(type); }) + .and_then([&] { + return resolve(handle->get(), path, *context, policy, TrailingSlashOnLink::Follow); + }) + .and_then([&](Resolved const& resolved) { + return openFinal(*context, resolved, attributesRequest(0)); + }) + .and_then([](UniqueHandle const& opened) { return informationOf(opened.get()); }) + .transform([](Information const& information) { return statOf(information); }); + }); + } + + async::Task> setTimesAt(SymlinkPolicy policy, + std::string path, + NewTimestamp accessed, + NewTimestamp modified) override + { + auto const& clock = *context()->wallClock; + return submit([context = context(), + handle = handle(), + flags = flags(), + type = objectType(), + policy, + path = std::move(path), + accessed = resolveNow(accessed, clock), + modified = resolveNow(modified, clock)]() { + return checkRights(flags, Operation::SetTimesAt) + .and_then([&] { return detail::requireDirectory(type); }) + .and_then([&] { + return resolve(handle->get(), path, *context, policy, TrailingSlashOnLink::Follow); + }) + .and_then([&](Resolved const& resolved) { + return openFinal(*context, resolved, attributesRequest(FILE_WRITE_ATTRIBUTES)); + }) + .and_then([&](UniqueHandle const& opened) { + return setTimesOf(opened.get(), accessed, modified); + }); + }); + } + + async::Task> linkAt(SymlinkPolicy policy, + std::string oldPath, + IDescriptor* newDirectory, + std::string newPath) override + { + auto const target = sameSystemTarget(newDirectory); + return submit([context = context(), + handle = handle(), + flags = flags(), + type = objectType(), + policy, + oldPath = std::move(oldPath), + target, + newPath = std::move(newPath)]() -> FsResult { + if (auto checked = checkRights(flags, Operation::LinkAt); !checked) + return checked; + if (policy == SymlinkPolicy::Follow) + return refuse(FsErrorCode::Invalid); + if (!target) + return std::unexpected { target.error() }; + if (auto checked = checkRights(target->flags, Operation::LinkAt); !checked) + return checked; + if (auto checked = detail::requireDirectory(type).and_then( + [&] { return detail::requireDirectory(target->type); }); + !checked) + return checked; + auto const from = resolve( + handle->get(), oldPath, *context, SymlinkPolicy::NoFollow, TrailingSlashOnLink::Follow); + if (!from) + return std::unexpected { from.error() }; + // A directory is never hard linked, as POSIX refuses it with EPERM. + if (from->name.empty() || from->kind == EntryKind::Directory) + return refuse(FsErrorCode::NotPermitted); + if (from->kind == EntryKind::Missing) + return refuse(FsErrorCode::NoEntry); + auto const to = resolve(target->handle->get(), + newPath, + *context, + SymlinkPolicy::NoFollow, + TrailingSlashOnLink::Follow) + .and_then([](Resolved resolved) { + return vacant(std::move(resolved), DescriptorType::RegularFile); + }); + if (!to) + return std::unexpected { to.error() }; + auto const name = detail::utf16Of(to->name); + if (!name) + return std::unexpected { name.error() }; + return openFinal(*context, *from, attributesRequest(FILE_WRITE_ATTRIBUTES)) + .and_then([&](UniqueHandle const& opened) { + return detail::ntSetName( + opened.get(), detail::FileLinkInformationClass, 0, to->directory(), *name); + }); + }); + } + + async::Task> readlinkAt(std::string path) override + { + return submit([context = context(), + handle = handle(), + flags = flags(), + type = objectType(), + path = std::move(path)]() { + return checkRights(flags, Operation::ReadlinkAt) + .and_then([&] { return detail::requireDirectory(type); }) + .and_then([&] { + return resolve(handle->get(), + path, + *context, + SymlinkPolicy::NoFollow, + TrailingSlashOnLink::Follow); + }) + .and_then([&](Resolved const& resolved) -> FsResult { + if (resolved.name.empty()) + return refuse(FsErrorCode::Invalid); + return openFinal(*context, resolved, attributesRequest(0)); + }) + .and_then([](UniqueHandle const& link) { return detail::readReparseData(link.get()); }) + .and_then([](detail::ReparseData const& data) { return detail::reportedTarget(data); }); + }); + } + + async::Task> removeDirectoryAt(std::string path) override + { + return submit([context = context(), + handle = handle(), + flags = flags(), + type = objectType(), + path = std::move(path)]() { + return checkRights(flags, Operation::RemoveDirectoryAt) + .and_then([&] { return detail::requireDirectory(type); }) + .and_then([&] { + return resolve(handle->get(), + path, + *context, + SymlinkPolicy::NoFollow, + TrailingSlashOnLink::Refuse); + }) + .and_then([&](Resolved const& resolved) -> FsResult { + if (resolved.name.empty()) + return refuse(FsErrorCode::Invalid); + auto const opened = openFinal( + *context, + resolved, + detail::NtOpenRequest { .access = DELETE | FILE_READ_ATTRIBUTES, + .disposition = FILE_OPEN, + .options = FILE_DIRECTORY_FILE, + .reparse = detail::ReparseHandling::OpenThePoint }); + if (!opened) + return std::unexpected { opened.error() }; + // A link to a directory carries the directory attribute, but rmdir does not + // remove a link. + auto const information = informationOf(opened->get()); + if (!information) + return std::unexpected { information.error() }; + if (typeOf(*information) != DescriptorType::Directory) + return refuse(FsErrorCode::NotDirectory); + return deleteOpened(opened->get()); + }); + }); + } + + async::Task> renameAt(std::string oldPath, + IDescriptor* newDirectory, + std::string newPath) override + { + auto const target = sameSystemTarget(newDirectory); + return submit([context = context(), + handle = handle(), + flags = flags(), + type = objectType(), + oldPath = std::move(oldPath), + target, + newPath = std::move(newPath)]() -> FsResult { + if (auto checked = checkRights(flags, Operation::RenameAt); !checked) + return checked; + if (!target) + return std::unexpected { target.error() }; + if (auto checked = checkRights(target->flags, Operation::RenameAt); !checked) + return checked; + if (auto checked = detail::requireDirectory(type).and_then( + [&] { return detail::requireDirectory(target->type); }); + !checked) + return checked; + auto const from = resolve( + handle->get(), oldPath, *context, SymlinkPolicy::NoFollow, TrailingSlashOnLink::Refuse); + if (!from) + return std::unexpected { from.error() }; + auto const to = resolve(target->handle->get(), + newPath, + *context, + SymlinkPolicy::NoFollow, + TrailingSlashOnLink::Refuse); + if (!to) + return std::unexpected { to.error() }; + if (from->kind == EntryKind::Missing && !from->name.empty()) + return refuse(FsErrorCode::NoEntry); + if (from->name.empty() || to->name.empty()) + return refuse(FsErrorCode::Invalid); + // What POSIX's rename answers for a type that cannot replace another, which Windows + // would answer as Access, or not at all. + auto const fromDirectory = from->kind == EntryKind::Directory; + if (!fromDirectory && to->finalComponent == FinalComponent::Directory) + return refuse(FsErrorCode::NotDirectory); + if (fromDirectory && (to->kind == EntryKind::Other || to->kind == EntryKind::SymbolicLink)) + return refuse(FsErrorCode::NotDirectory); + if (!fromDirectory && (to->kind == EntryKind::Directory || isDirectoryLink(*context, *to))) + return refuse(FsErrorCode::IsDirectory); + auto const name = detail::utf16Of(to->name); + if (!name) + return std::unexpected { name.error() }; + return openFinal(*context, *from, attributesRequest(DELETE)) + .and_then([&](UniqueHandle const& opened) { + return renameOpened(opened.get(), to->directory(), *name); + }); + }); + } + + async::Task> symlinkAt(std::string target, std::string newPath) override + { + return submit([context = context(), + handle = handle(), + flags = flags(), + type = objectType(), + target = std::move(target), + newPath = std::move(newPath)]() { + return checkRights(flags, Operation::SymlinkAt) + .and_then([&] { return detail::requireDirectory(type); }) + .and_then([&] { return detail::checkSymlinkTarget(target, *context->policy); }) + .and_then([&] { + return resolve(handle->get(), + newPath, + *context, + SymlinkPolicy::NoFollow, + TrailingSlashOnLink::Follow); + }) + .and_then([](Resolved resolved) { + return vacant(std::move(resolved), DescriptorType::SymbolicLink); + }) + .and_then([&](Resolved const& resolved) { + return createSymlink( + *context, resolved, target, flavourOf(handle->get(), newPath, target, *context)); + }); + }); + } + + async::Task> unlinkFileAt(std::string path) override + { + return submit([context = context(), + handle = handle(), + flags = flags(), + type = objectType(), + path = std::move(path)]() { + return checkRights(flags, Operation::UnlinkFileAt) + .and_then([&] { return detail::requireDirectory(type); }) + .and_then([&] { + return resolve(handle->get(), + path, + *context, + SymlinkPolicy::NoFollow, + TrailingSlashOnLink::Refuse); + }) + .and_then([&](Resolved const& resolved) -> FsResult { + if (resolved.name.empty() || resolved.kind == EntryKind::Directory) + return refuse(FsErrorCode::IsDirectory); + // Not FILE_NON_DIRECTORY_FILE: a directory link is a directory to the + // system, and a link to anything is unlinked. + auto const opened = openFinal(*context, resolved, attributesRequest(DELETE)); + if (!opened) + return std::unexpected { opened.error() }; + auto const information = informationOf(opened->get()); + if (!information) + return std::unexpected { information.error() }; + if (typeOf(*information) == DescriptorType::Directory) + return refuse(FsErrorCode::IsDirectory); + return deleteOpened(opened->get()); + }); + }); + } + + async::Task> metadataHashAt(SymlinkPolicy policy, std::string path) override + { + return submit([context = context(), + handle = handle(), + flags = flags(), + type = objectType(), + policy, + path = std::move(path)]() { + return checkRights(flags, Operation::MetadataHashAt) + .and_then([&] { return detail::requireDirectory(type); }) + .and_then([&] { + return resolve(handle->get(), path, *context, policy, TrailingSlashOnLink::Follow); + }) + .and_then([&](Resolved const& resolved) { + return openFinal(*context, resolved, attributesRequest(0)); + }) + .and_then([&](UniqueHandle const& opened) { return hashOf(*context, opened.get()); }); + }); + } + + async::Task> isSameObject(IDescriptor* other) override + { + return submit([context = context(), + handle = handle(), + candidate = sameObjectCandidate(other)]() -> FsResult { + if (!candidate) + return std::unexpected { candidate.error() }; + if (!*candidate) + return false; + auto const& files = *context->ntFiles; + return files.identity(handle->get()).and_then([&](detail::FileIdentity const& mine) { + return files.identity((*candidate)->handle->get()) + .transform([&](detail::FileIdentity const& theirs) { return mine == theirs; }); + }); + }); + } + + private: + SharedHandle _appendHandle; ///< The `FILE_APPEND_DATA` handle `append` writes through. + }; + + class WindowsFileSystem final: public IDescriptorFileSystem + { + public: + explicit WindowsFileSystem(SharedContext context): _context { std::move(context) } {} + + async::Task>> openPreopen(std::filesystem::path hostDirectory, + DescriptorFlags flags) override + { + return async::offload( + _context->home, + _context->blocking, + [context = _context, + path = std::move(hostDirectory), + flags]() -> FsResult> { + if (hasFlag(flags, DescriptorFlags::Write)) + return refuse(FsErrorCode::IsDirectory); + auto access = + DWORD { FILE_LIST_DIRECTORY | FILE_TRAVERSE | FILE_READ_ATTRIBUTES | SYNCHRONIZE }; + if (hasFlag(flags, DescriptorFlags::MutateDirectory)) + access |= FILE_WRITE_ATTRIBUTES; + // The host chose this directory, so the system resolves its path. + auto const opened = ::CreateFileW(path.c_str(), + access, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + nullptr, + OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS | SECURITY_SQOS_PRESENT + | SECURITY_IDENTIFICATION, + nullptr); + if (opened == INVALID_HANDLE_VALUE) + return lastError("CreateFileW"); + auto handle = UniqueHandle { opened }; + auto const information = informationOf(opened); + if (!information) + return std::unexpected { information.error() }; + if (typeOf(*information) != DescriptorType::Directory) + return refuse(FsErrorCode::NotDirectory); + return std::make_unique( + context, + detail::shareHandle(std::move(handle), *context->blocking), + SharedHandle {}, + grantedFlags(DescriptorType::Directory, flags), + DescriptorType::Directory); + }); + } + + private: + SharedContext _context; + }; + +} // namespace + +FsResult> makeNativeDescriptorFileSystem( + async::IExecutor& home, + async::IExecutor& blocking, + platform::IWallClock const& wallClock, + IRandom& random, + NativeFileSystemOptions options) +{ + return detail::checkOptions(options).transform([&] -> std::unique_ptr { + return std::make_unique(std::make_shared( + home, blocking, wallClock, random, options, KernelSeparators, &detail::systemNtFiles())); + }); +} + +FsResult> detail::makeWindowsDescriptorFileSystem( + async::IExecutor& home, + async::IExecutor& blocking, + platform::IWallClock const& wallClock, + IRandom& random, + NativeFileSystemOptions options, + INtFiles const& files) +{ + return detail::checkOptions(options).transform([&] -> std::unique_ptr { + return std::make_unique(std::make_shared( + home, blocking, wallClock, random, options, KernelSeparators, &files)); + }); +} + +} // namespace core::fs diff --git a/src/core/fs/windows/WindowsPathWalk.cpp b/src/core/fs/windows/WindowsPathWalk.cpp new file mode 100644 index 00000000..cfb13284 --- /dev/null +++ b/src/core/fs/windows/WindowsPathWalk.cpp @@ -0,0 +1,311 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The component walker of Windows: each directory is opened beneath the one before it with +// NtCreateFile, RootDirectory set to the held handle, as the reparse point itself and with +// OBJ_DONT_REPARSE, and held by its handle, so the walk never names a directory by a path again. +// A name surrogate met on the way is a link: a relative symbolic link is read with +// FSCTL_GET_REPARSE_POINT and spliced by the shared walk, which also owns the hop limit and `..` at +// the root; anything else that names another object is NotPermitted. +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace core::fs::detail +{ + +namespace +{ + + std::uint64_t littleEndianAt(std::span bytes, std::size_t offset) noexcept + { + auto value = std::uint64_t { 0 }; + for (auto const index: std::views::iota(std::size_t { 0 }, std::size_t { 8 })) + value |= std::uint64_t { bytes[offset + index] } << (index * 8U); + return value; + } + + class SystemNtFiles final: public INtFiles + { + public: + FsResult open(HANDLE directory, + std::wstring const& name, + NtOpenRequest const& request) const override + { + return ntOpenRelative(directory, name, request); + } + + FsResult attributes(HANDLE handle) const override + { + auto tag = FILE_ATTRIBUTE_TAG_INFO {}; + if (::GetFileInformationByHandleEx(handle, FileAttributeTagInfo, &tag, sizeof(tag)) != FALSE) + return EntryAttributes { .attributes = tag.FileAttributes, .reparseTag = tag.ReparseTag }; + // FAT and exFAT keep no reparse point and answer no FileAttributeTagInfo: their + // attributes are the basic ones, and no tag. + auto basic = FILE_BASIC_INFO {}; + if (::GetLastError() != ERROR_INVALID_PARAMETER + || ::GetFileInformationByHandleEx(handle, FileBasicInfo, &basic, sizeof(basic)) == FALSE) + return std::unexpected { fsErrorFromSystemCode(std::int64_t { ::GetLastError() }, + "GetFileInformationByHandleEx") }; + return EntryAttributes { .attributes = basic.FileAttributes, .reparseTag = 0 }; + } + + /// The 128-bit `FILE_ID_INFO` where the file system has it, the 64-bit index of + /// `BY_HANDLE_FILE_INFORMATION` where it does not (FAT). + FsResult identity(HANDLE handle) const override + { + auto id = FILE_ID_INFO {}; + if (::GetFileInformationByHandleEx(handle, FileIdInfo, &id, sizeof(id)) != FALSE) + { + auto const bytes = std::span { id.FileId.Identifier }; + return FileIdentity { .volume = id.VolumeSerialNumber, + .idLow = littleEndianAt(bytes, 0), + .idHigh = littleEndianAt(bytes, 8) }; + } + auto legacy = BY_HANDLE_FILE_INFORMATION {}; + if (::GetFileInformationByHandle(handle, &legacy) == FALSE) + return std::unexpected { fsErrorFromSystemCode(std::int64_t { ::GetLastError() }, + "GetFileInformationByHandle") }; + return FileIdentity { .volume = legacy.dwVolumeSerialNumber, + .idLow = + (std::uint64_t { legacy.nFileIndexHigh } << 32U) | legacy.nFileIndexLow, + .idHigh = 0 }; + } + + FsResult queryDirectory(HANDLE directory, std::span records) const override + { + if (::GetFileInformationByHandleEx( + directory, FileIdBothDirectoryInfo, records.data(), static_cast(records.size())) + == FALSE) + return std::unexpected { fsErrorFromSystemCode(std::int64_t { ::GetLastError() }, + "GetFileInformationByHandleEx") }; + return {}; + } + }; + + std::unexpected refuseWith(FsErrorCode code) + { + return std::unexpected { FsError { .code = code, .systemCode = 0, .context = {} } }; + } + + /// What every name the walk looks at is opened with: enough to read its attributes and its + /// reparse data, and nothing that a share mode or a missing right could refuse. + constexpr auto LookRequest = NtOpenRequest { .access = FILE_READ_ATTRIBUTES, + .disposition = FILE_OPEN, + .options = 0, + .reparse = ReparseHandling::OpenThePoint }; + +} // namespace + +INtFiles const& systemNtFiles() noexcept +{ + static auto const files = SystemNtFiles {}; + return files; +} + +FsResult openEntry(INtFiles const& files, + HANDLE directory, + std::wstring const& name, + NtOpenRequest request) +{ + request.access |= FILE_READ_ATTRIBUTES; + request.reparse = ReparseHandling::OpenThePoint; + auto point = files.open(directory, name, request); + if (!point) + return std::unexpected { point.error() }; + auto const attributes = files.attributes(point->get()); + if (!attributes) + return std::unexpected { attributes.error() }; + if (!attributes->isFilteredPoint()) + return OpenedEntry { .handle = std::move(*point), .attributes = *attributes }; + + auto entry = OpenedEntry { .handle = std::move(*point), .attributes = *attributes }; + auto filtered = openAgain(files, entry, request); + if (!filtered) + { + if (filtered.error().systemCode == std::int64_t { STATUS_IO_REPARSE_TAG_NOT_HANDLED }) + return entry; + return std::unexpected { filtered.error() }; + } + return OpenedEntry { .handle = std::move(*filtered), .attributes = entry.attributes }; +} + +FsResult openAgain(INtFiles const& files, OpenedEntry const& entry, NtOpenRequest request) +{ + return openAgain(files, entry.handle.get(), entry.attributes, request); +} + +FsResult openAgain(INtFiles const& files, + HANDLE handle, + EntryAttributes const& attributes, + NtOpenRequest request) +{ + // By the handle, so whatever the name names by now it is this object that is opened; never + // created again, nor truncated by the disposition. + request.access |= FILE_READ_ATTRIBUTES; + request.disposition = FILE_OPEN; + request.reparse = + attributes.isFilteredPoint() ? ReparseHandling::ThroughFilters : ReparseHandling::OpenThePoint; + auto again = files.open(handle, std::wstring {}, request); + if (!again) + { + // The object became a point the object manager would follow (a mount point) since it was + // checked: that is a link, never crossed. + if (again.error().systemCode == std::int64_t { STATUS_REPARSE_POINT_ENCOUNTERED }) + return refuseWith(FsErrorCode::NotPermitted); + return std::unexpected { again.error() }; + } + auto const checked = files.identity(handle); + auto const opened = files.identity(again->get()); + if (!checked) + return std::unexpected { checked.error() }; + if (!opened) + return std::unexpected { opened.error() }; + if (*checked != *opened) + return refuseWith(FsErrorCode::NotPermitted); + return std::move(*again); +} + +WindowsCursor::WindowsCursor(HANDLE root, INtFiles const& files) noexcept: _root { root }, _files { &files } +{ +} + +bool WindowsCursor::atRoot() const noexcept +{ + return _entered.empty(); +} + +HANDLE WindowsCursor::current() const noexcept +{ + return _entered.empty() ? _root : _entered.back().get(); +} + +FsResult WindowsCursor::enter(std::string const& name) +{ + auto const wide = utf16Of(name); + if (!wide) + return std::unexpected { wide.error() }; + auto opened = openEntry(*_files, + current(), + *wide, + NtOpenRequest { .access = FILE_READ_ATTRIBUTES, + .disposition = FILE_OPEN, + .options = FILE_DIRECTORY_FILE, + .reparse = ReparseHandling::OpenThePoint }); + if (opened) + { + // A directory link or a junction carries the directory attribute and opens as one. + if (opened->attributes.isLink()) + return EntryKind::SymbolicLink; + _entered.push_back(std::move(opened->handle)); + return EntryKind::Directory; + } + // A link to a file has no directory attribute, so FILE_DIRECTORY_FILE refuses it as it refuses + // a file; and a point OBJ_DONT_REPARSE met is Loop. Which it is, the name itself tells. + auto const failure = opened.error(); + if (failure.code != FsErrorCode::NotDirectory && failure.code != FsErrorCode::Loop) + return std::unexpected { failure }; + return inspect(name).and_then([&failure](EntryKind kind) -> FsResult { + switch (kind) + { + case EntryKind::Missing: return refuseWith(FsErrorCode::NoEntry); + // A directory here changed under the walk since the open refused it: reported as a + // link, whose read answers Invalid, so the walk looks at the name again. + case EntryKind::Directory: + case EntryKind::SymbolicLink: return EntryKind::SymbolicLink; + case EntryKind::Other: break; + } + return std::unexpected { failure }; + }); +} + +void WindowsCursor::leave() +{ + _entered.pop_back(); +} + +FsResult WindowsCursor::inspect(std::string const& name) +{ + auto const wide = utf16Of(name); + if (!wide) + return std::unexpected { wide.error() }; + auto const opened = _files->open(current(), *wide, LookRequest); + if (!opened) + { + if (opened.error().code == FsErrorCode::NoEntry) + return EntryKind::Missing; + return std::unexpected { opened.error() }; + } + return _files->attributes(opened->get()).transform([](EntryAttributes const& attributes) { + if (attributes.isLink()) + return EntryKind::SymbolicLink; + if (attributes.isDirectory()) + return EntryKind::Directory; + return EntryKind::Other; + }); +} + +FsResult WindowsCursor::readLink(std::string const& name) +{ + return utf16Of(name) + .and_then([this](std::wstring const& wide) { return _files->open(current(), wide, LookRequest); }) + .and_then([](UniqueHandle const& link) { return readReparseData(link.get()); }) + .and_then([](ReparseData const& data) { return followedTarget(data); }); +} + +FsResult WindowsCursor::shortcut(std::span) +{ + return Shortcut::Declined; +} + +void WindowsCursor::restart() +{ + _entered.clear(); +} + +UniqueHandle WindowsCursor::release() noexcept +{ + if (_entered.empty()) + return UniqueHandle { platform::InvalidHandle }; + auto top = std::move(_entered.back()); + _entered.clear(); + return top; +} + +FsResult resolveBeneath(platform::NativeHandle root, + PathPlan plan, + WalkRules const& rules, + IBeneathOpener const* /*opener: Windows has none*/) +{ + return resolveBeneathWith(systemNtFiles(), root, std::move(plan), rules); +} + +FsResult resolveBeneathWith(INtFiles const& files, + HANDLE root, + PathPlan plan, + WalkRules const& rules) +{ + auto cursor = WindowsCursor { root, files }; + return walkBeneath(cursor, std::move(plan), rules).transform([&cursor, root](WalkEnd end) { + return Resolved { .held = cursor.release(), + .root = root, + .name = std::move(end.name), + .kind = end.kind, + .finalComponent = end.finalComponent }; + }); +} + +} // namespace core::fs::detail diff --git a/src/core/fs/windows/WindowsPathWalk.hpp b/src/core/fs/windows/WindowsPathWalk.hpp new file mode 100644 index 00000000..14a26ed5 --- /dev/null +++ b/src/core/fs/windows/WindowsPathWalk.hpp @@ -0,0 +1,234 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// The Windows side of @c walkBeneath: a cursor over directory handles, each opened with +/// `NtCreateFile` relative to the one before it, as the reparse point itself, so a directory swapped +/// for a link or a junction between two components is met as a link, never crossed. A symbolic link +/// is followed by the walk only where its target is relative; a junction, a mount point and every +/// other name surrogate is refused (`NotPermitted`). A reparse point that names nothing else (a +/// cloud placeholder, a deduplicated file) is opened again through its filter, by the handle that +/// was checked, so its data is what its filter supplies. Private to the fs module. +/// +/// The NT calls that decide all of this are behind @c INtFiles, so the decision is tested with +/// scripted answers as well as against the file system. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace core::fs::detail +{ + +/// What `FileAttributeTagInfo` tells about an open object. +struct EntryAttributes +{ + std::uint32_t attributes = 0; ///< `FILE_ATTRIBUTE_*`. + std::uint32_t reparseTag = 0; ///< The reparse tag, where `FILE_ATTRIBUTE_REPARSE_POINT` is set. + + /// @return Whether the object is a reparse point that names another object: a link to a walk. + [[nodiscard]] constexpr bool isLink() const noexcept + { + return isReparsePoint() && isNameSurrogate(reparseTag); + } + + /// @return Whether the object is a reparse point that names nothing else. + [[nodiscard]] constexpr bool isFilteredPoint() const noexcept + { + return isReparsePoint() && !isNameSurrogate(reparseTag); + } + + /// @return Whether the object is a directory (a directory link is one, too). + [[nodiscard]] constexpr bool isDirectory() const noexcept + { + return (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0; + } + + /// @return Whether the object is a reparse point. + [[nodiscard]] constexpr bool isReparsePoint() const noexcept + { + return (attributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0; + } +}; + +/// Which object an open handle is: its volume and its file id there. +struct FileIdentity +{ + std::uint64_t volume = 0; ///< The volume's serial number. + std::uint64_t idLow = 0; ///< The file id, low 64 bits. + std::uint64_t idHigh = 0; ///< The file id, high 64 bits (0 where the file system has 64-bit ids). + + bool operator==(FileIdentity const&) const = default; +}; + +/// The NT calls whose answers decide how a name is opened. Implemented by the system, and by tests +/// with scripted answers. +class INtFiles +{ + public: + INtFiles() = default; + INtFiles(INtFiles const&) = delete; + INtFiles(INtFiles&&) = delete; + INtFiles& operator=(INtFiles const&) = delete; + INtFiles& operator=(INtFiles&&) = delete; + virtual ~INtFiles() = default; + + /// @param directory A held handle @p name is relative to. + /// @param name One component; empty for @p directory itself. + /// @param request What to ask for. + /// @return The handle; what refused it. + [[nodiscard]] virtual FsResult open(HANDLE directory, + std::wstring const& name, + NtOpenRequest const& request) const = 0; + + /// @param handle An open object, with `FILE_READ_ATTRIBUTES`. + /// @return Its attributes and reparse tag. + [[nodiscard]] virtual FsResult attributes(HANDLE handle) const = 0; + + /// @param handle An open object. + /// @return Which object it is. + [[nodiscard]] virtual FsResult identity(HANDLE handle) const = 0; + + /// Reads the next records of @p directory's listing, from where its handle stands + /// (`GetFileInformationByHandleEx(FileIdBothDirectoryInfo)`). + /// @param directory A directory, open with `FILE_LIST_DIRECTORY`. + /// @param records Where the `FILE_ID_BOTH_DIR_INFO` records are written, from its start. + /// @return Nothing once records are written; what refused it, with its Win32 code kept: + /// `ERROR_NO_MORE_FILES` past the last record. + [[nodiscard]] virtual FsResult queryDirectory(HANDLE directory, + std::span records) const = 0; +}; + +/// @return The system's NT calls. +[[nodiscard]] CORE_FS_API INtFiles const& systemNtFiles() noexcept; + +/// An entry opened by @c openEntry. +struct OpenedEntry +{ + UniqueHandle handle; ///< The handle. + EntryAttributes attributes; ///< What the first open found under the name. +}; + +/// Opens @p name beneath @p directory as the reparse point itself, never following a link. Where the +/// name is a reparse point that names nothing else, the object is opened again by the handle just +/// checked, through its filter, which then supplies its data; where no filter takes the point's tag +/// (`STATUS_IO_REPARSE_TAG_NOT_HANDLED`), the point is the file and the first handle is kept. +/// @param files The NT calls. +/// @param directory A held directory handle. +/// @param name One component in UTF-16; empty for @p directory itself. +/// @param request What to ask for; `FILE_READ_ATTRIBUTES` is added. +/// @return The entry; `NotPermitted` where the object opened again is another than the one checked, +/// and what else refused it. +[[nodiscard]] CORE_FS_API FsResult openEntry(INtFiles const& files, + HANDLE directory, + std::wstring const& name, + NtOpenRequest request); + +/// Opens @p entry's object again by its handle, with no name: the point itself, or through its +/// filter where @p entry is a reparse point that names nothing else (@c openEntry), and refusing, +/// either way, any reparse the object manager would follow. A second handle on an object is made +/// this way, never by `ReOpenFile`, which follows whatever reparse point the object holds by then. +/// @param files The NT calls. +/// @param entry What @c openEntry opened. +/// @param request What to ask for; the disposition is always `FILE_OPEN`, `FILE_READ_ATTRIBUTES` is +/// added. +/// @return The handle; `NotPermitted` where the object became a point that names another object, or +/// the handle opened is another object; what else refused it. +[[nodiscard]] CORE_FS_API FsResult openAgain(INtFiles const& files, + OpenedEntry const& entry, + NtOpenRequest request); + +/// @c openAgain for an object held by a handle the caller keeps. +/// @param files The NT calls. +/// @param handle The object, open; borrowed for the call. +/// @param attributes What @p handle's object is, read from it. +/// @param request What to ask for, as for @c openAgain. +/// @return The handle, as @c openAgain answers. +[[nodiscard]] CORE_FS_API FsResult openAgain(INtFiles const& files, + HANDLE handle, + EntryAttributes const& attributes, + NtOpenRequest request); + +/// Resolves @p plan beneath @p root over @p files: @c resolveBeneath with the NT calls a file system +/// was built with, rather than the system's. +/// @param files The NT calls. +/// @param root The descriptor's directory handle; borrowed for the call. +/// @param plan The planned path. +/// @param rules How links, `..` and the kernel's separators are treated. +/// @return Where it resolved to, or what @c walkBeneath answers. +[[nodiscard]] CORE_FS_API FsResult resolveBeneathWith(INtFiles const& files, + HANDLE root, + PathPlan plan, + WalkRules const& rules); + +/// Builds the Windows file system over @p files instead of the system's NT calls, so a test can +/// script what the system answers; @c makeNativeDescriptorFileSystem otherwise. +/// @param home Where every operation resumes. +/// @param blocking Where every system call runs. +/// @param wallClock What `SetToNow` reads. +/// @param random Where the metadata secret is drawn from. +/// @param options What the file system is built with. +/// @param files The NT calls; must outlive the file system and its descriptors. +/// @return The file system; `Invalid` for a `maxReadChunk` of 0. +[[nodiscard]] CORE_FS_API FsResult> makeWindowsDescriptorFileSystem( + async::IExecutor& home, + async::IExecutor& blocking, + platform::IWallClock const& wallClock, + IRandom& random, + NativeFileSystemOptions options, + INtFiles const& files); + +/// A cursor over directory handles: the root, borrowed, and a stack of the directories entered +/// beneath it, each held open by this cursor and closed where it is left. It takes no shortcut: +/// `NtCreateFile` has no mode that resolves several components beneath a handle. +class CORE_FS_API WindowsCursor final: public IBeneathCursor +{ + public: + /// @param root The directory the walk starts on; borrowed, and must outlive the cursor. + /// @param files The NT calls; must outlive the cursor. + WindowsCursor(HANDLE root, INtFiles const& files) noexcept; + + WindowsCursor(WindowsCursor const&) = delete; + WindowsCursor(WindowsCursor&&) = delete; + WindowsCursor& operator=(WindowsCursor const&) = delete; + WindowsCursor& operator=(WindowsCursor&&) = delete; + ~WindowsCursor() override = default; + + [[nodiscard]] bool atRoot() const noexcept override; + [[nodiscard]] FsResult enter(std::string const& name) override; + void leave() override; + [[nodiscard]] FsResult inspect(std::string const& name) override; + [[nodiscard]] FsResult readLink(std::string const& name) override; + [[nodiscard]] FsResult shortcut(std::span components) override; + void restart() override; + + /// @return The directory the cursor stands on, borrowed. + [[nodiscard]] HANDLE current() const noexcept; + + /// Hands over the directory the cursor stands on, where it is not the root. + /// @return It; one holding no handle where the cursor stands on the root. + [[nodiscard]] UniqueHandle release() noexcept; + + private: + HANDLE _root; + INtFiles const* _files; + std::vector _entered; +}; + +} // namespace core::fs::detail diff --git a/src/core/fs/windows/WindowsPathWalk_test.cpp b/src/core/fs/windows/WindowsPathWalk_test.cpp new file mode 100644 index 00000000..986df9ff --- /dev/null +++ b/src/core/fs/windows/WindowsPathWalk_test.cpp @@ -0,0 +1,343 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// How a name is opened when it is a reparse point, decided over scripted NT answers: a point that +// names another object is a link and is never opened through; one that names nothing else (a cloud +// placeholder, a deduplicated file) is opened again, by the handle that was checked, through its +// filter, so a read sees the data the filter supplies rather than the stub. Then the reparse data a +// link is made and read with. +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using core::fs::FsErrorCode; +using core::fs::FsResult; +using core::fs::detail::EntryAttributes; +using core::fs::detail::FileIdentity; +using core::fs::detail::INtFiles; +using core::fs::detail::LinkTarget; +using core::fs::detail::NtOpenRequest; +using core::fs::detail::ReparseHandling; +using core::fs::detail::UniqueHandle; +using core::fs::test::outcomeOf; + +namespace +{ + +/// One open the code under test made. +struct OpenCall +{ + HANDLE directory = nullptr; + std::wstring name; + NtOpenRequest request; +}; + +/// NT answers from a script: each open takes the next answer, and each handle it hands out is a +/// real event handle, so the code under test closes what it was given, with the attributes and the +/// identity the script gave it. +class ScriptedNtFiles final: public INtFiles +{ + public: + /// What one open answers. + struct Answer + { + NTSTATUS status = 0; ///< A failure, or 0 for a handle. + EntryAttributes attributes; + FileIdentity identity; + }; + + explicit ScriptedNtFiles(std::deque answers): _answers { std::move(answers) } {} + + FsResult open(HANDLE directory, + std::wstring const& name, + NtOpenRequest const& request) const override + { + _calls.push_back(OpenCall { .directory = directory, .name = name, .request = request }); + REQUIRE_FALSE(_answers.empty()); + auto const answer = _answers.front(); + _answers.pop_front(); + if (answer.status < 0) + return std::unexpected { core::fs::fsErrorFromNtStatus(std::int64_t { answer.status }, + "scripted") }; + auto handle = UniqueHandle { ::CreateEventW(nullptr, TRUE, FALSE, nullptr) }; + _objects[handle.get()] = answer; + _handed.push_back(handle.get()); + return handle; + } + + FsResult attributes(HANDLE handle) const override + { + return _objects.at(handle).attributes; + } + + FsResult identity(HANDLE handle) const override { return _objects.at(handle).identity; } + + /// No case here lists a directory. + FsResult queryDirectory(HANDLE, std::span) const override + { + return std::unexpected { core::fs::FsError { + .code = FsErrorCode::Unsupported, .systemCode = 0, .context = "scripted" } }; + } + + /// @return Every open made, in order. + [[nodiscard]] std::vector const& calls() const noexcept { return _calls; } + + /// @return The handles handed out, in order. + [[nodiscard]] std::vector const& handed() const noexcept { return _handed; } + + private: + mutable std::deque _answers; + mutable std::vector _calls; + mutable std::map _objects; + mutable std::vector _handed; +}; + +constexpr auto Placeholder = + EntryAttributes { .attributes = FILE_ATTRIBUTE_REPARSE_POINT, + .reparseTag = static_cast(IO_REPARSE_TAG_CLOUD_6) }; +constexpr auto Symlink = EntryAttributes { .attributes = FILE_ATTRIBUTE_REPARSE_POINT, + .reparseTag = static_cast(IO_REPARSE_TAG_SYMLINK) }; +constexpr auto Junction = + EntryAttributes { .attributes = FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY, + .reparseTag = static_cast(IO_REPARSE_TAG_MOUNT_POINT) }; +constexpr auto PlainFile = EntryAttributes { .attributes = FILE_ATTRIBUTE_NORMAL, .reparseTag = 0 }; +constexpr auto SameFile = FileIdentity { .volume = 7, .idLow = 42, .idHigh = 0 }; +constexpr auto OtherFile = FileIdentity { .volume = 7, .idLow = 43, .idHigh = 0 }; + +constexpr auto ReadRequest = NtOpenRequest { .access = FILE_GENERIC_READ, + .disposition = FILE_OPEN_IF, + .options = FILE_NON_DIRECTORY_FILE, + .reparse = ReparseHandling::OpenThePoint }; + +/// A directory handle the opens are relative to; never dereferenced by the script. +HANDLE directory() noexcept +{ + return ::GetCurrentProcess(); +} + +} // namespace + +TEST_CASE("a reparse point that names nothing else is opened again through its filter", + "[fs][native][windows]") +{ + auto const files = ScriptedNtFiles { { { .status = 0, .attributes = Placeholder, .identity = SameFile }, + { .status = 0, .attributes = PlainFile, .identity = SameFile } } }; + auto const opened = openEntry(files, directory(), L"placeholder", ReadRequest); + REQUIRE(opened.has_value()); + REQUIRE(files.calls().size() == 2); + + auto const& first = files.calls()[0]; + CHECK(first.directory == directory()); + CHECK(first.name == L"placeholder"); + CHECK(first.request.reparse == ReparseHandling::OpenThePoint); + CHECK((first.request.access & FILE_READ_ATTRIBUTES) != 0); + + // Again by the handle checked, with no name: the same object, whatever the name names by now; + // never created again. + auto const& again = files.calls()[1]; + REQUIRE_FALSE(files.handed().empty()); + CHECK(again.directory == files.handed().front()); + CHECK(again.name.empty()); + CHECK(again.request.reparse == ReparseHandling::ThroughFilters); + CHECK(again.request.disposition == ULONG { FILE_OPEN }); + CHECK(again.request.access == first.request.access); + CHECK(again.request.options == first.request.options); + CHECK(opened->attributes.reparseTag == Placeholder.reparseTag); +} + +TEST_CASE("a name surrogate is never opened through", "[fs][native][windows]") +{ + for (auto const& link: { Symlink, Junction }) + { + CAPTURE(link.reparseTag); + auto const files = ScriptedNtFiles { { { .status = 0, .attributes = link, .identity = SameFile } } }; + auto const opened = openEntry(files, directory(), L"link", ReadRequest); + REQUIRE(opened.has_value()); + CHECK(files.calls().size() == 1); + CHECK(opened->attributes.isLink()); + } +} + +TEST_CASE("a file that is no reparse point is opened once", "[fs][native][windows]") +{ + auto const files = ScriptedNtFiles { { { .status = 0, .attributes = PlainFile, .identity = SameFile } } }; + auto const opened = openEntry(files, directory(), L"f", ReadRequest); + REQUIRE(opened.has_value()); + CHECK(files.calls().size() == 1); + CHECK_FALSE(opened->attributes.isLink()); +} + +TEST_CASE("a reparse point no filter takes is the file itself", "[fs][native][windows]") +{ + auto const files = ScriptedNtFiles { + { { .status = 0, .attributes = Placeholder, .identity = SameFile }, + { .status = STATUS_IO_REPARSE_TAG_NOT_HANDLED, .attributes = {}, .identity = {} } } + }; + auto const opened = openEntry(files, directory(), L"private", ReadRequest); + REQUIRE(opened.has_value()); + CHECK(files.calls().size() == 2); + CHECK(opened->handle.get() != nullptr); +} + +TEST_CASE("a filter that opens another object than the one checked is refused", "[fs][native][windows]") +{ + auto const files = + ScriptedNtFiles { { { .status = 0, .attributes = Placeholder, .identity = SameFile }, + { .status = 0, .attributes = PlainFile, .identity = OtherFile } } }; + auto const opened = openEntry(files, directory(), L"placeholder", ReadRequest); + REQUIRE_FALSE(opened.has_value()); + CHECK(opened.error().code == FsErrorCode::NotPermitted); +} + +TEST_CASE("a filter's refusal is the open's", "[fs][native][windows]") +{ + auto const files = + ScriptedNtFiles { { { .status = 0, .attributes = Placeholder, .identity = SameFile }, + { .status = STATUS_ACCESS_DENIED, .attributes = {}, .identity = {} } } }; + auto const opened = openEntry(files, directory(), L"placeholder", ReadRequest); + REQUIRE_FALSE(opened.has_value()); + CHECK(opened.error().code == FsErrorCode::Access); +} + +TEST_CASE("a relative symbolic link's reparse data reads back as it was written", "[fs][native][windows]") +{ + auto const bytes = core::fs::detail::relativeSymlinkReparseData(L"..\\x\\y", L"../x\\y"); + auto const data = core::fs::detail::parseReparseData(bytes); + REQUIRE(data.has_value()); + CHECK(data->tag == static_cast(IO_REPARSE_TAG_SYMLINK)); + CHECK(data->target == LinkTarget::Relative); + CHECK(data->substituteName == L"..\\x\\y"); + CHECK(data->printName == L"../x\\y"); + CHECK(core::fs::detail::followedTarget(*data).value() == "..\\x\\y"); + CHECK(core::fs::detail::reportedTarget(*data).value() == "../x\\y"); + + SECTION("a print name that spells another target is not what is reported") + { + auto const lying = core::fs::detail::parseReparseData( + core::fs::detail::relativeSymlinkReparseData(L"..\\..\\outside", L"inside")); + REQUIRE(lying.has_value()); + CHECK(core::fs::detail::reportedTarget(*lying).value() == "..\\..\\outside"); + } +} + +TEST_CASE("an absolute link, a junction and a mount point are never followed", "[fs][native][windows]") +{ + auto absolute = core::fs::detail::relativeSymlinkReparseData(L"\\??\\C:\\outside", L"C:\\outside"); + absolute[16] = std::byte { 0 }; // the flags: not relative + auto const junction = core::fs::detail::mountPointReparseData(L"\\??\\C:\\outside\\", L"C:\\outside\\"); + auto const volume = + core::fs::detail::mountPointReparseData(L"\\??\\Volume{01234567-89ab-cdef-0123-456789abcdef}\\", L""); + for (auto const& bytes: { absolute, junction, volume }) + { + auto const data = core::fs::detail::parseReparseData(bytes); + REQUIRE(data.has_value()); + CHECK(outcomeOf(core::fs::detail::followedTarget(*data)) == FsErrorCode::NotPermitted); + CHECK(outcomeOf(core::fs::detail::reportedTarget(*data)) == FsErrorCode::NotPermitted); + } +} + +TEST_CASE("reparse data that claims more than it holds is Invalid", "[fs][native][windows]") +{ + auto const bytes = core::fs::detail::relativeSymlinkReparseData(L"target", L"target"); + for (auto const length: { std::size_t { 0 }, std::size_t { 7 }, std::size_t { 19 }, bytes.size() - 1 }) + { + CAPTURE(length); + auto const data = core::fs::detail::parseReparseData(std::span { bytes }.first(length)); + REQUIRE_FALSE(data.has_value()); + CHECK(data.error().code == FsErrorCode::Invalid); + } + auto pastTheEnd = bytes; + pastTheEnd[8] = std::byte { 0x40 }; // the substitute name's offset, beyond the data + CHECK(outcomeOf(core::fs::detail::parseReparseData(pastTheEnd)) == FsErrorCode::Invalid); +} + +TEST_CASE("a point swapped for a mount point before its filter opens it is refused", "[fs][native][windows]") +{ + // OBJ_DONT_REPARSE makes the reopen meet the mount point rather than follow it. + auto const files = ScriptedNtFiles { + { { .status = 0, .attributes = Placeholder, .identity = SameFile }, + { .status = STATUS_REPARSE_POINT_ENCOUNTERED, .attributes = {}, .identity = {} } } + }; + auto const opened = openEntry(files, directory(), L"placeholder", ReadRequest); + REQUIRE_FALSE(opened.has_value()); + CHECK(opened.error().code == FsErrorCode::NotPermitted); + REQUIRE(files.calls().size() == 2); + CHECK(files.calls()[1].request.reparse == ReparseHandling::ThroughFilters); +} + +TEST_CASE("a second handle is the same object, opened again by its handle", "[fs][native][windows]") +{ + constexpr auto AppendRequest = NtOpenRequest { .access = FILE_APPEND_DATA, + .disposition = FILE_OPEN, + .options = FILE_NON_DIRECTORY_FILE | FILE_WRITE_THROUGH, + .reparse = ReparseHandling::OpenThePoint }; + SECTION("a plain file: the point itself, never following one put on it since") + { + auto const files = + ScriptedNtFiles { { { .status = 0, .attributes = PlainFile, .identity = SameFile }, + { .status = 0, .attributes = PlainFile, .identity = SameFile } } }; + auto const entry = openEntry(files, directory(), L"f", ReadRequest); + REQUIRE(entry.has_value()); + auto const second = core::fs::detail::openAgain(files, *entry, AppendRequest); + REQUIRE(second.has_value()); + REQUIRE(files.calls().size() == 2); + auto const& again = files.calls()[1]; + CHECK(again.directory == files.handed().front()); + CHECK(again.name.empty()); + CHECK(again.request.reparse == ReparseHandling::OpenThePoint); + CHECK(again.request.disposition == ULONG { FILE_OPEN }); + CHECK((again.request.access & FILE_APPEND_DATA) != 0); + CHECK((again.request.options & FILE_WRITE_THROUGH) != 0); + } + SECTION("the handle opens another object: a symbolic link put on the file was followed") + { + auto const files = + ScriptedNtFiles { { { .status = 0, .attributes = PlainFile, .identity = SameFile }, + { .status = 0, .attributes = PlainFile, .identity = OtherFile } } }; + auto const entry = openEntry(files, directory(), L"f", ReadRequest); + REQUIRE(entry.has_value()); + CHECK(outcomeOf(core::fs::detail::openAgain(files, *entry, AppendRequest)) + == FsErrorCode::NotPermitted); + } + SECTION("a filtered point: through its filter, and a mount point swapped in is refused") + { + auto const files = ScriptedNtFiles { + { { .status = 0, .attributes = Placeholder, .identity = SameFile }, + { .status = 0, .attributes = PlainFile, .identity = SameFile }, + { .status = STATUS_REPARSE_POINT_ENCOUNTERED, .attributes = {}, .identity = {} } } + }; + auto const entry = openEntry(files, directory(), L"placeholder", ReadRequest); + REQUIRE(entry.has_value()); + CHECK(outcomeOf(core::fs::detail::openAgain(files, *entry, AppendRequest)) + == FsErrorCode::NotPermitted); + REQUIRE(files.calls().size() == 3); + CHECK(files.calls()[2].request.reparse == ReparseHandling::ThroughFilters); + } +} + +TEST_CASE("an open through filters takes no name", "[fs][native][windows]") +{ + auto const opened = + core::fs::detail::ntOpenRelative(directory(), + L"name", + NtOpenRequest { .access = FILE_READ_ATTRIBUTES, + .disposition = FILE_OPEN, + .options = 0, + .reparse = ReparseHandling::ThroughFilters }); + REQUIRE_FALSE(opened.has_value()); + CHECK(opened.error().code == FsErrorCode::Invalid); +} diff --git a/tests/cmake/check-layering.cmake b/tests/cmake/check-layering.cmake index 332f2f16..dee8dae0 100644 --- a/tests/cmake/check-layering.cmake +++ b/tests/cmake/check-layering.cmake @@ -18,9 +18,11 @@ # The table is read from the real cmake/CoreCppModules.cmake -- by configuring it, not by a regex # that imitates it -- and a module may include itself and whatever its DEPS reach, transitively, # because that is exactly what its target links. Tests (`*_test.cpp`) and canaries (`*Canary.cpp`) -# are separate executables with links of their own, and are not scanned. The scan is watched -# refusing a planted violation, and accepting a planted compliant tree, before it is run over this -# one -- a scan that found nothing in a tree it could not read would read exactly like a clean one. +# are separate executables with links of their own, and are not scanned; nor is a test-only support +# header (`*TestSupport.hpp`), which is in no FILE_SET and is compiled only into those executables. +# The scan is watched refusing a planted violation, and accepting a planted compliant tree, before +# it is run over this one -- a scan that found nothing in a tree it could not read would read +# exactly like a clean one. # # What the include scan does not see: a module's SUB-target (`tui_output`, `net_types`) is held to # its module's row rather than its own, because the files a sub-target owns are named in its @@ -74,6 +76,11 @@ function(core_cpp_layering_add module name) endfunction() ]=]) +# A source root holding an empty CMakeLists.txt for every module of the real table but fs, for the +# two scenarios that enter the module directories. `\$` keeps the variables for the scenario's own +# configure; it has no `;`, which would split the scenario list. +set(missingModuleRoot "set(fakeRoot \"\${CMAKE_CURRENT_BINARY_DIR}/fake-root\")\nforeach(module IN LISTS CORE_CPP_MODULES)\n if(NOT module STREQUAL fs)\n file(WRITE \"\${fakeRoot}/src/core/\${CORE_CPP_MODULE_\${module}_DIR}/CMakeLists.txt\" \"\")\n endif()\nendforeach()\nset(CORE_CPP_SOURCE_DIR \"\${fakeRoot}\")") + # "||". # The real net row lists DEPS async platform; net_x is a row a scenario adds to the net module. set(scenarios @@ -117,6 +124,12 @@ set(scenarios # A module's own target follows the module's row: its DEPS, and the module's targets. "module-links-its-targets|configures|core_cpp_module(NAME demo KIND INTERFACE DEPS base PLATFORMS any)\ncore_cpp_module_target(NAME demo_types MODULE demo KIND INTERFACE PLATFORMS any)\ncore_cpp_layering_stand_in(base demo_types)\ncore_cpp_layering_add(demo demo core::base core::demo_types)" "module-links-undeclared-module|core-cpp-demo links core::log|core_cpp_module(NAME demo KIND INTERFACE DEPS base PLATFORMS any)\ncore_cpp_layering_stand_in(log)\ncore_cpp_layering_add(demo demo core::log)" + + # An enabled module whose directory a vendored copy left out is refused naming the option that + # would switch it off, not by add_subdirectory() naming a path. The real table, over a root that + # has an empty directory for every module but fs; with the option off, the same root configures. + "enabled-module-without-its-directory|module fs is enabled but its directory src/core/fs is missing.*Set CORE_CPP_WITH_FS=OFF|${missingModuleRoot}\ncore_cpp_add_modules()" + "disabled-module-without-its-directory|configures|${missingModuleRoot}\nset(CORE_CPP_WITH_FS OFF)\ncore_cpp_add_modules()" ) set(generatorArguments "") @@ -282,7 +295,7 @@ function(core_cpp_layering_scan_includes root outViolations outFiles outEdges) else() file(GLOB_RECURSE sources LIST_DIRECTORIES false "${root}/src/core/${dir}/*.hpp" "${root}/src/core/${dir}/*.cpp") endif() - list(FILTER sources EXCLUDE REGEX "(_test|Canary)\\.cpp$") + list(FILTER sources EXCLUDE REGEX "((_test|Canary)\\.cpp|TestSupport\\.hpp)$") foreach(source IN LISTS sources) math(EXPR files "${files} + 1") file(STRINGS "${source}" includes REGEX "^[ \t]*#[ \t]*include[ \t]*[<\"]core/") @@ -317,24 +330,25 @@ function(core_cpp_layering_scan_includes root outViolations outFiles outEdges) endfunction() # Watched refusing first, and accepting, on a planted tree: `log` reaching `net`, which its row does -# not; `net` reaching `platform` and -- through it -- `base`, which its row does; and a test file -# reaching `tui`, which is not scanned. +# not; `net` reaching `platform` and -- through it -- `base`, which its row does; and a test file and +# a test-only support header reaching `tui`, which are not scanned. set(fixture "${WORK_DIR}/include-edges-fixture") file(REMOVE_RECURSE "${fixture}") file(WRITE "${fixture}/src/core/log/Bad.hpp" "#pragma once\n#include \n") file(WRITE "${fixture}/src/core/net/Good.hpp" "#pragma once\n#include \n#include \n#include \n") file(WRITE "${fixture}/src/core/net/Good_test.cpp" "#include \n") +file(WRITE "${fixture}/src/core/net/NetTestSupport.hpp" "#pragma once\n#include \n") core_cpp_layering_scan_includes("${fixture}" planted plantedFiles plantedEdges) list(LENGTH planted plantedCount) if(NOT plantedCount EQUAL 1 OR NOT planted MATCHES "src/core/log/Bad.hpp includes , and log's row does not reach net") message(STATUS "FAIL include-edges-fixture: wanted exactly the planted violation, got ${plantedCount}: ${planted}") list(APPEND failures include-edges-fixture) elseif(NOT plantedEdges EQUAL 4) - message(STATUS "FAIL include-edges-fixture: counted ${plantedEdges} cross-module include(s), not 4 -- the test file was scanned, or an allowed edge was missed") + message(STATUS "FAIL include-edges-fixture: counted ${plantedEdges} cross-module include(s), not 4 -- the test file or the support header was scanned, or an allowed edge was missed") list(APPEND failures include-edges-fixture) else() - message(STATUS "ok include-edges-fixture: refuses log -> net by name, allows net -> platform -> base, skips tests") + message(STATUS "ok include-edges-fixture: refuses log -> net by name, allows net -> platform -> base, skips tests and their support headers") endif() core_cpp_layering_scan_includes("${ROOT}" violations scannedFiles scannedEdges) diff --git a/tests/consumer-vendored/CMakeLists.txt b/tests/consumer-vendored/CMakeLists.txt index e7dcd550..8eeed18a 100644 --- a/tests/consumer-vendored/CMakeLists.txt +++ b/tests/consumer-vendored/CMakeLists.txt @@ -6,7 +6,7 @@ # this project's own suite. # # cmake -DMODE=sync -DREF= -DDEST=/vendor/core-cpp \ -# "-DMODULES=base;log;cli;codec;platform;async;net;testing" -P /cmake/CoreCppVendor.cmake +# "-DMODULES=base;log;cli;codec;platform;async;net;fs;testing" -P /cmake/CoreCppVendor.cmake # cmake -S tests/consumer-vendored -B -DCORE_CPP_VENDOR_DIR=/vendor/core-cpp # cmake --build && ctest --test-dir --output-on-failure # @@ -76,6 +76,8 @@ add_test(NAME core-cpp-vendored-copy -P "${CORE_CPP_VENDOR_DIR}/cmake/CoreCppVendor.cmake") add_executable(consumer-vendored main.cpp) -target_link_libraries(consumer-vendored PRIVATE core::async core::log core::net core::net_tls) +# core::fs is linked although main.cpp names nothing of it: it is EXCLUDE_FROM_ALL like every target +# of the copy, so a link is what makes this build compile it. +target_link_libraries(consumer-vendored PRIVATE core::async core::log core::net core::net_tls core::fs) add_test(NAME consumer-vendored COMMAND consumer-vendored) set_tests_properties(consumer-vendored PROPERTIES TIMEOUT 120) From a97b90c36ee5a060bd914789c1f44935cada01ce Mon Sep 17 00:00:00 2001 From: Christian Parpart Date: Thu, 26 Nov 2026 19:33:50 +0100 Subject: [PATCH 05/19] feat(net)!: classified resolver failures and a resolver that runs on an injected executor Classify name-not-found and temporary resolver failures. NetErrorCode gains NameNotFound and ResolverTemporaryFailure, before Last, for wasi:sockets' name-unresolvable and temporary-resolver-failure; AddressError stays the permanent and unclassified resolver failure. IAddressResolver gains a defaulted resolveClassified, which wraps resolve()'s message into AddressError. SystemAddressResolver overrides it through resolverErrorTable(), one table per OS: every EAI_* code the POSIX libc defines (asserted complete against gai_strerror), and every WSA* code Winsock's getaddrinfo returns (asserted against the documented list). A code no row names is AddressError; a refused family or socket type is AddressError too, since the hints are this library's own. FreeBSD keeps rows for the two codes its headers retired but gai_strerror still describes. ThreadedAddressResolver and InlineAddressResolver call resolveClassified, so the code survives the hop, and the TCP listeners classify their own getaddrinfo failures through the same table instead of storing a raw EAI code as the system code. detail::endpointOfLiteral parses a strict literal into a dial-able endpoint (no port, no brackets, no embedded NUL; "127.1" is a name); it is now what isNumericHost asks. testing::ScriptedAddressResolver answers literals by parsing and names from a script, fails with words or a code, and can hold a lookup for a resolver that offloads it. AcceptErrorTable classifies both new codes as Unclassified. BREAKING CHANGE: an exhaustive switch over NetErrorCode must handle the two new codes (-Wswitch). ExecutorAddressResolver runs lookups on an injected executor. A resolver that owns no thread: each lookup is a detached flow that hops onto the blocking executor it was given, calls resolveClassified there and hands the waiting flow back to its loop. A literal is parsed in place, a null loop resolves inline, and a full maxInFlight budget is refused with WouldBlock. A stop ends the wait, not the lookup: the lookup keeps its slot until the blocking call returns. A lookup its executor drops unrun answers its waiter Cancelled and frees its slot through a guard in the detached frame. ThreadedAddressResolver's slot, stop callback and stop-aware awaiter move to net/detail/ParkedCall.hpp as ParkedCall, with one SlotState replacing the two flags. Its tests run over testing::ScriptedAddressResolver, which gains callers(). Also in this commit: - a scoped IPv6 literal is a name on every platform - ExecutorAddressResolver settles without throwing and stops before it offloads - the async resolvers refuse a host that names no host Signed-off-by: Christian Parpart --- .agent/reference/provenance.md | 27 +- src/core/net/AcceptPolicy.hpp | 4 + src/core/net/AcceptPolicy_test.cpp | 3 + src/core/net/CMakeLists.txt | 9 + src/core/net/ExecutorAddressResolver.cpp | 217 ++++++++ src/core/net/ExecutorAddressResolver.hpp | 115 ++++ src/core/net/ExecutorAddressResolver_test.cpp | 496 ++++++++++++++++++ src/core/net/IAsyncAddressResolver.hpp | 32 +- src/core/net/NetError.hpp | 61 ++- src/core/net/NetError_test.cpp | 16 + src/core/net/SocketAddress.cpp | 91 +++- src/core/net/SocketAddress.hpp | 103 +++- src/core/net/SocketAddress_test.cpp | 106 +++- src/core/net/Sockets.cpp | 4 +- src/core/net/Sockets.hpp | 4 +- src/core/net/ThreadedAddressResolver.cpp | 201 +------ src/core/net/ThreadedAddressResolver.hpp | 12 +- src/core/net/ThreadedAddressResolver_test.cpp | 207 +++++--- src/core/net/detail/ParkedCall.hpp | 222 ++++++++ src/core/net/detail/ParkedCall_test.cpp | 121 +++++ src/core/net/posix/PosixListener.cpp | 10 +- src/core/net/posix/ResolverErrors_test.cpp | 138 +++++ src/core/net/posix/SocketsPosix.cpp | 93 ++++ .../net/testing/ScriptedAddressResolver.hpp | 199 +++++++ .../testing/ScriptedAddressResolver_test.cpp | 192 +++++++ src/core/net/windows/IocpSocket.cpp | 7 +- src/core/net/windows/ResolverErrors_test.cpp | 79 +++ src/core/net/windows/SocketsWin32.cpp | 46 ++ 28 files changed, 2474 insertions(+), 341 deletions(-) create mode 100644 src/core/net/ExecutorAddressResolver.cpp create mode 100644 src/core/net/ExecutorAddressResolver.hpp create mode 100644 src/core/net/ExecutorAddressResolver_test.cpp create mode 100644 src/core/net/detail/ParkedCall.hpp create mode 100644 src/core/net/detail/ParkedCall_test.cpp create mode 100644 src/core/net/posix/ResolverErrors_test.cpp create mode 100644 src/core/net/testing/ScriptedAddressResolver.hpp create mode 100644 src/core/net/testing/ScriptedAddressResolver_test.cpp create mode 100644 src/core/net/windows/ResolverErrors_test.cpp diff --git a/.agent/reference/provenance.md b/.agent/reference/provenance.md index bb1969b8..c391d921 100644 --- a/.agent/reference/provenance.md +++ b/.agent/reference/provenance.md @@ -252,7 +252,7 @@ others in notes. | `src/core/net/BackendParity_test.cpp` | contour-terminal/contour | `src/net/EventSourceParity_test.cpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | Task B3: `EventSourceParity_test` renamed, and its direct-registration cases rewritten over `ReadinessHandler` -- a case now asserts which callback ran and how often, because that is what a dispatching backend gives it. The end-to-end cases (the `[closehang]` family above all) are unchanged but for the matrix they run over. New here: Rule 1 asserted from a resumed flow's own frame on every backend, the batch withdrawal on a real kernel (fastcached#475), `setInterest` reporting the kernel's refusal under descriptor pressure (fastcached#1054, #1057), `wake()` from another thread, a dead handle not blinding the backend to a live one, and `makeBackend` answering null for a kind this platform does not build Task B8: `localPort` is `boundPort` Task B7b: every backend without a completion port refuses a `HandleKind::Completion` registration by name, the host-driven one included. | | `src/core/net/CMakeLists.txt` | origin: core-cpp | - | - | replaces contour's `src/net/CMakeLists.txt`: the targets `core::net_types`, `core::net` and `core::net_tls`, and three test binaries; keeps its comment on the PUBLIC `Threads::Threads` Task B8: the dial, the connector and the two resolvers join `core::net`, with `DialPrimitives.cpp` per platform; five new test sources join the `net` binary. Task B9: the datagram, blocking-transport and in-memory-fake sources and their tests join `core::net` and the `net` binary, with `BlockingPrimitives.cpp`, `SocketErrors.cpp` and `UdpSocket.cpp` per platform | | `src/core/net/AcceptedHalfClose_test.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/AcceptedHalfClose_test.cpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B6: `shutdownWrite` from the ACCEPTED side, which no other case here drives. Upstream's two assertions are kept verbatim in meaning -- the peer sees EOF, AND the shutting-down socket's own next write fails -- because an implementation that gets only the first right passes a half-written port. Upstream's reactor thread plus blocking connector becomes one sequential flow on one loop: a loopback dial completes out of the backlog before anything accepts, so no step waits on a sibling that may have bailed, and the accepted end provably has not closed when the peer reads -- a close would send a FIN of its own and pass for the half-close's. Portable on purpose: the defect it pins was one platform's Task B8: `localPort` is `boundPort` | -| `src/core/net/AcceptPolicy.hpp` | origin: core-cpp | - | - | graduated from LASTRADA-Software/fastcached `src/FastCache/Transport/AcceptPolicy.hpp` at `a11f0c1a37ab317bd1dd7e9c82f2c4a78a5a4b55`, a commit not yet on its master: the row moves to that upstream once it is, [core-cpp#60](https://github.com/contour-terminal/core-cpp/issues/60); 0.6.0: camelBack; the table is a `std::array` sized by `NetErrorCode::Last` with a position check, where upstream used its `EnumTable`; `Stop` is split into `Closed` and `Dead`, and the verdict is an `AcceptAction` (accept again, stop, give up) where upstream had a `stop` bool; `SystemError` is `Unclassified`, backed off on without end and reported degraded after `UnclassifiedBeforeDegraded` (`AcceptConditionChange`), exhaustion is keyed on the new `ResourceExhausted`, and a poll tick counts toward the yield; the warning is a count the caller words (`describeAcceptFailure`), and `onError` takes the code alone; `WaitOutBackoff` not taken, since a loop here waits on its `EventLoop` timer | +| `src/core/net/AcceptPolicy.hpp` | origin: core-cpp | - | - | graduated from LASTRADA-Software/fastcached `src/FastCache/Transport/AcceptPolicy.hpp` at `a11f0c1a37ab317bd1dd7e9c82f2c4a78a5a4b55`, a commit not yet on its master: the row moves to that upstream once it is, [core-cpp#60](https://github.com/contour-terminal/core-cpp/issues/60); 0.6.0: camelBack; the table is a `std::array` sized by `NetErrorCode::Last` with a position check, where upstream used its `EnumTable`; `Stop` is split into `Closed` and `Dead`, and the verdict is an `AcceptAction` (accept again, stop, give up) where upstream had a `stop` bool; `SystemError` is `Unclassified`, backed off on without end and reported degraded after `UnclassifiedBeforeDegraded` (`AcceptConditionChange`), exhaustion is keyed on the new `ResourceExhausted`, and a poll tick counts toward the yield; the warning is a count the caller words (`describeAcceptFailure`), and `onError` takes the code alone; `WaitOutBackoff` not taken, since a loop here waits on its `EventLoop` timer; 0.24.0 (P13): rows for `NameNotFound` and `ResolverTemporaryFailure`, both `Unclassified` | | `src/core/net/AcceptPolicy.cpp` | origin: core-cpp | - | - | graduated from LASTRADA-Software/fastcached `src/FastCache/Transport/AcceptPolicy.cpp` at `a11f0c1a37ab317bd1dd7e9c82f2c4a78a5a4b55`, a commit not yet on its master: the row moves to that upstream once it is, [core-cpp#60](https://github.com/contour-terminal/core-cpp/issues/60); 0.6.0: as the header; the decision is one `switch` over the disposition | | `src/core/net/AcceptPolicy_test.cpp` | origin: core-cpp | - | - | graduated from LASTRADA-Software/fastcached `src/FastCache/Transport/AcceptPolicy_test.cpp` at `a11f0c1a37ab317bd1dd7e9c82f2c4a78a5a4b55`, a commit not yet on its master: the row moves to that upstream once it is, [core-cpp#60](https://github.com/contour-terminal/core-cpp/issues/60); 0.6.0: over `platform::ManualClock`; new: the unclassified give-up and the run that resets it, and exhaustion that never gives up | | `src/core/net/AcceptLoopHealth.hpp` | origin: core-cpp | - | - | graduated from LASTRADA-Software/fastcached `src/FastCache/Transport/AcceptLoopHealth.hpp` at `a11f0c1a37ab317bd1dd7e9c82f2c4a78a5a4b55`, a commit not yet on its master: the row moves to that upstream once it is, [core-cpp#60](https://github.com/contour-terminal/core-cpp/issues/60); 0.6.0: camelBack; it records degraded loops as well as ones that gave up, removes a degraded one on recovery, and takes the accept loop's reports whole (`record`) where upstream had `Stopped(surface, reason)` | @@ -270,6 +270,9 @@ others in notes. | `src/core/net/EventLoop.cpp` | contour-terminal/contour | `src/net/EventLoop.cpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | namespaces and includes; `IClock`, `SystemPipe` and `createSystemPipe()` are `core::platform`'s; the two iterator `for` loops over `_fdToTokens` are a `std::ranges::find_if` and a range-`for` over a `std::ranges::subrange`; post-import addition (core-cpp): `pumpOnce()` calls `IClock::refresh()` before it computes a wait's timeout and after the wait, as the merged `IClock` asks of a loop | Task B3: the loop drives an `IoBackend`, so readiness arrives as a callback per park rather than as two token lists to route, and the post self-pipe is gone -- `post()` calls `IoBackend::wake()`, which every backend owns. `drainReadyQueue` asserts no backend dispatch is in flight, which is where Rule 1 is caught Task B4: the five-step turn, the six-step teardown and the park table; `IExecutor` is implemented here, so `submit`, `schedule` and `cancelPending` are the loop's; `pumpOnce` is `runOnce`, and what it resumes is drained in step 2 alone Perf lane (v0.2.0): `RegistrationLifetime::UntilClosed` -- one `detail::HandleWatch` per handle, attached on its first park and detached by `notifyHandleClosing`, narrowed after the wait -- and a turn is idle only if it leaves the ready queue empty. A re-sync must keep both: `SocketRegistration_test` and `ClosedParkIdle_test` fail without them. | | `src/core/net/EventLoop.hpp` | contour-terminal/contour | `src/net/EventLoop.hpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | namespaces and includes; `IClock`, `defaultSteadyClock()`, `SteadyTimePoint`, `NativeHandle`, `InvalidHandle` and `SystemPipe` are `core::platform`'s; no `NOLINT`; the provenance pointer names contour's `src/coro/README.md`; the constructor's comment says when the loop refreshes the clock (core-cpp) | Task B3: `EventSource&` becomes `IoBackend&`, `FdToken` becomes the loop's own `ParkId` (Task B4 widens it), each park owns the `ReadinessHandler` the backend holds, and `parkedWaiterCount()` joins `pendingTimerCount()` as the leak assertion for the other kind of park Task B4: `EventLoop` is an `async::IExecutor`, `ParkId` and `ParkEntry` move to `detail/ParkTable.hpp`, `WaitFdAwaiter` becomes `WaitHandleAwaiter` and takes a `HandleKind`, and `IdlePolicy`, `EventLoopOptions`, `RunOnceResult`, `run`, `runOnce`, `runUntilIdle`, `stop`, `resumeSoon`, `registerPark`, `unregisterPark`, `wakeReasonOf`, `requestCancel`, `running`, `isOnWorkerThread` and `teardownIsSerialisedWithDispatch` arrive Task B7b: `completionPort()`, lending the backend's port (never the backend) to the socket factories that choose by it. | | `src/core/net/EventLoop_test.cpp` | contour-terminal/contour | `src/net/EventLoop_test.cpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | namespaces and includes; `ManualClock`, `SystemPipe`, `createSystemPipe()`, `NativeHandle` and `InvalidHandle` are `core::platform`'s; a pipe read tests `ChannelResult::bytesRead()` where it compared a count; post-import addition (core-cpp): the case over a `CachedClock` that the loop refreshes before each timeout and after each wait | Task B3: over `ScriptedBackend` and `makeDefaultBackend()`; the registration cases are stated in handlers and `HandlerId`s, and the leak assertions read `EventLoop::parkedWaiterCount()` where they read the source's `attachedCount()` Task B4: the clock cases move to `ClockRefresh_test.cpp`, one per refresh; the turn's order and bound, guarantees G2 and G3, and `spawn`'s O(1) unlink are asserted here | +| `src/core/net/ExecutorAddressResolver.hpp` | origin: core-cpp | - | - | P13 Task 7: the resolver that owns no thread | +| `src/core/net/ExecutorAddressResolver.cpp` | origin: core-cpp | - | - | P13 Task 7 | +| `src/core/net/ExecutorAddressResolver_test.cpp` | origin: core-cpp | - | - | P13 Task 7 | | `src/core/net/HostDrivenBackend.cpp` | origin: core-cpp | - | - | its body: the coalescing (several wakes before the host gets a turn are one pump), the clamp of a deadline already past to a zero delay, and the schedule cleared BEFORE a pump runs so the turn it drives can arm the next one | | `src/core/net/HostDrivenBackend.hpp` | origin: core-cpp | - | - | Task B3: the IoBackend for a loop that is PUMPED rather than one that blocks. Portable, and tested on every platform over testing::ManualHostScheduler -- the browser is one of its hosts, not its definition | | `src/core/net/HostDrivenBackend_test.cpp` | origin: core-cpp | - | - | Task B3: the host-driven backend over testing::ManualHostScheduler, on every platform including Emscripten -- the alternative leaves its behaviour observable only in a node run | @@ -336,7 +339,7 @@ others in notes. | `src/core/net/LoopAffinityCanary.cpp` | origin: core-cpp | - | - | Task B13: fastcached's `reactor-teardown-gate` (`scripts/reactor-teardown-gate.cmake` at 0708dd54) in this tree's shape -- one process per loop-thread-only member of `EventLoop`, each calling it from a second thread while the loop runs, judged by the ASSERTION'S OWN TEXT naming that member rather than by a marker, so a death on the way there is not read as the guard firing | | `src/core/net/LoopExecutorContext_test.cpp` | origin: core-cpp | - | - | 0.4.0: an `EventLoop` turn states the loop as the current executor, a strand it drives nests beneath it, and a flow that awaits a queue built over another executor comes back to the loop. In `net_backend`, so it runs under Emscripten too | | `src/core/net/LoopTeardown_test.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Async/ParkedWork_test.cpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B4. The six #1025 proofs, carried over the `BackendMatrix` and the `TestLoop` rather than over one platform reactor. Two of upstream's cases stayed where the type lives (`src/core/async/ParkedWork_test.cpp`), and one is new here: the READINESS park, which fastcached's reactors had and its test did not reach, and which is the only kind that also holds a registration the backend knows by address | -| `src/core/net/NetError.hpp` | contour-terminal/contour | `src/net/IoResult.hpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | `NetErrorCode`, `toString()`, `NetError` and `makeNetError()`, split out of `IoResult.hpp`, with a file comment of its own; the `core::net_types` target. Task B2 merged LASTRADA-Software/fastcached `src/FastCache/Net/NetError.hpp` (`0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21`) into it: `NetErrorCode` is the union of the two (fastcached's `AddressNotAvail`, `HostUnreach` and `PermissionDenied` join contour's, `BadFileHandle` is `BadHandle` and contour's `Other` is fastcached's `SystemError`), `IsDeadlineExpiry` is `isDeadlineExpiry` with its #824 reasoning rewritten against core-cpp's callers, and a `Last` enumerator states the count. Not taken: fastcached's `ToString()` (`NetError(code=6 …)`, a numeric code) and `ToStringView()` (the enumerator's name); `toString()` keeps contour's wording, and `` stays out of this header; 0.6.0: `ResourceExhausted`, after `SystemError` | +| `src/core/net/NetError.hpp` | contour-terminal/contour | `src/net/IoResult.hpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | `NetErrorCode`, `toString()`, `NetError` and `makeNetError()`, split out of `IoResult.hpp`, with a file comment of its own; the `core::net_types` target. Task B2 merged LASTRADA-Software/fastcached `src/FastCache/Net/NetError.hpp` (`0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21`) into it: `NetErrorCode` is the union of the two (fastcached's `AddressNotAvail`, `HostUnreach` and `PermissionDenied` join contour's, `BadFileHandle` is `BadHandle` and contour's `Other` is fastcached's `SystemError`), `IsDeadlineExpiry` is `isDeadlineExpiry` with its #824 reasoning rewritten against core-cpp's callers, and a `Last` enumerator states the count. Not taken: fastcached's `ToString()` (`NetError(code=6 …)`, a numeric code) and `ToStringView()` (the enumerator's name); `toString()` keeps contour's wording, and `` stays out of this header; 0.6.0: `ResourceExhausted`, after `SystemError`; 0.24.0 (P13): `NameNotFound` and `ResolverTemporaryFailure`, before `Last` | | `src/core/net/NetError_test.cpp` | origin: core-cpp | - | - | the `core-cpp.net_types` test, which the Emscripten build runs too; the upstream file has no test | | `src/core/net/PlatformLoop.hpp` | LASTRADA-Software/fastcached | `src/FastCache/Async/PlatformReactor.hpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B4. Upstream is an `#if` ladder aliasing one of three concrete reactors; here there is one loop type and the choice is `makeDefaultBackend()`'s, so this is a class that OWNS the backend and is-a `EventLoop`. The private base is what gets the order right: a member would be initialised after every base, and `EventLoop` is one | | `src/core/net/ParkReuse_test.cpp` | origin: core-cpp | - | - | 0.4.3, core-cpp#52: what a socket's park must still answer once the loop keeps it across operations -- a late cancel from another thread, a ready entry queued for a retired operation, idle narrowing and the count, and a reused descriptor number -- at the loop interface on every backend | @@ -368,6 +371,8 @@ others in notes. | `src/core/net/bsd/DefaultBackend.cpp` | contour-terminal/contour | `src/net/DefaultEventSource.cpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | its macOS/BSD arm: kqueue by preference, poll(2) beside it | | `src/core/net/bsd/KqueueBackend.cpp` | contour-terminal/contour | `src/net/KqueueEventSource.cpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | Task B3 rewrote it behind `IoBackend`: readiness is DISPATCHED to the callbacks on the `ReadinessHandler` a caller registers, instead of being collected into a `WaitOutcome` of tokens for the caller to route. The `EV_RECEIPT` handling is unchanged and still load-bearing; what changed is where its verdict goes -- a refused filter is now a `NetError` carrying the kernel's errno rather than an invalid token (fastcached#1054) Task B7b: refuses `HandleKind::Completion` by name with `Unsupported`.; 0.6.0: a refused registration is classified by the one socket-error table | | `src/core/net/bsd/KqueueBackend.hpp` | contour-terminal/contour | `src/net/KqueueEventSource.hpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | Task B3: `KqueueEventSource` renamed `KqueueBackend`. Task B3 rewrote it behind `IoBackend`: readiness is DISPATCHED to the callbacks on the `ReadinessHandler` a caller registers, instead of being collected into a `WaitOutcome` of tokens for the caller to route; `attach` here registers NOTHING with the kernel, and says so -- kqueue has no 'add with no filters' operation, so only `setInterest` can answer whether the kernel accepted the descriptor (fastcached#1057) | +| `src/core/net/detail/ParkedCall.hpp` | origin: core-cpp | - | - | P13 Task 7: `ParkedCall`, extracted from `ThreadedAddressResolver.cpp` and shared with `ExecutorAddressResolver` | +| `src/core/net/detail/ParkedCall_test.cpp` | origin: core-cpp | - | - | P13 Task 7 fix round 1: first answer wins, the late answer kept and taken once | | `src/core/net/detail/ParkId.hpp` | origin: core-cpp | - | - | Task B13: `ParkId` and its hash, moved out of `detail/ParkTable.hpp` so that `IoAwaitable.hpp` -- and so `ISocket.hpp` -- no longer includes the park table for one strong integer (core-cpp#43) | | `src/core/net/detail/ParkTable.hpp` | origin: core-cpp | - | - | Task B4: `ParkId`, `ParkEntry` and the table. fastcached had no unified one -- a submission queue, a timer heap and each reactor's own descriptor map -- and cancellation therefore meant something slightly different in each. One table, one id space that never wraps, and the id IS the generation check: a cancel for a park that has gone resolves to nothing Task B13: `ParkId` moves out to `detail/ParkId.hpp` Parity lane (v0.2.0): the parks are keyed in `ParkMap`, an open-addressing table with backward-shift deletion, instead of `std::unordered_map`; taken parks are recycled; a park on a handle's lifetime registration points at its `HandleWatch` rather than being filed by handle, and `fileByHandle` files one displaced from its slot | | `src/core/net/detail/ParkTable_test.cpp` | origin: core-cpp | - | - | Parity lane (v0.2.0): `ParkMap` against `std::unordered_map`, the zero id it must refuse, and park recycling; 0.4.3 (core-cpp#52): resident parks -- ids per operation, idle parks uncounted, slots freed with their watch or their last operation | @@ -400,7 +405,7 @@ others in notes. | `src/core/net/posix/PosixListener.hpp` | contour-terminal/contour | `src/net/posix/PosixListener.hpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | namespaces and includes; no file-wide `#ifndef _WIN32` guard: `SOURCES_POSIX` selects the file (Ruling R42) Task B8: `localPort` is `boundPort`, and `adopt` joins `bind` for a descriptor this process did not create; 0.6.0: `doClose()`, and `close(FdWakePolicy)` is `closeWith` | | `src/core/net/posix/PosixSocket.cpp` | contour-terminal/contour | `src/net/posix/PosixSocket.cpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | Task B6 rewrote it frame-free over fastcached's `src/FastCache/Net/EpollSocket.cpp` and `src/FastCache/Net/KqueueSocket.cpp` (`0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21`): the retry loop runs in a frameless readiness callback rather than in the awaiting coroutine. contour's `recvmsg` SCM_RIGHTS walk, its `ENOTSOCK`/`EIO` PTY handling, the stale-`errno` zero-write fix and the `SO_NOSIGPIPE` option are kept unchanged; the `MSG_PEEK` probe, the vectored cursor and the detach-then-complete ordering are fastcached's. No file-wide `#ifndef _WIN32` guard: `SOURCES_POSIX` selects the file (Ruling R42) Perf lane (v0.2.0): its parks ask for `RegistrationLifetime::UntilClosed`, one registration for the socket's life, and `armWrite` arms both write verbs. Upstream registers per operation; a re-sync from it would bring that back, which `SocketRegistration_test` catches. | | `src/core/net/posix/PosixSocket.hpp` | contour-terminal/contour | `src/net/posix/PosixSocket.hpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | Task B6 rewrote it as ONE socket replacing fastcached's `src/FastCache/Net/EpollSocket.hpp` and `src/FastCache/Net/KqueueSocket.hpp` (`0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21`), which differed from each other only in the reactor type they named. The per-direction operation structs are theirs; there is no `Impl` pimpl, because the multiplexer is `IoBackend`'s and nothing platform-shaped is left to hide. No file-wide `#ifndef _WIN32` guard: `SOURCES_POSIX` selects the file (Ruling R42) | -| `src/core/net/posix/SocketsPosix.cpp` | contour-terminal/contour | `src/net/posix/SocketsPosix.cpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | namespaces and includes; `ensureWinsockInitialized()` is `core::platform`'s; the `addrinfo` walk is a `while` that steps to the next candidate first; no file-wide `#ifndef _WIN32` guard: `SOURCES_POSIX` selects the file (Ruling R42) Task B8: `connect` is gone from here -- it is portable now, over `makeConnector`, in `Sockets.cpp` -- and `listen(loop, ListenOptions)` plus `adoptListener` arrive. `connectUnix` is untouched: an AF_UNIX dial resolves no name; 0.6.0: the AF_UNIX dial classifies its errors by the one socket-error table | +| `src/core/net/posix/SocketsPosix.cpp` | contour-terminal/contour | `src/net/posix/SocketsPosix.cpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | namespaces and includes; `ensureWinsockInitialized()` is `core::platform`'s; the `addrinfo` walk is a `while` that steps to the next candidate first; no file-wide `#ifndef _WIN32` guard: `SOURCES_POSIX` selects the file (Ruling R42) Task B8: `connect` is gone from here -- it is portable now, over `makeConnector`, in `Sockets.cpp` -- and `listen(loop, ListenOptions)` plus `adoptListener` arrive. `connectUnix` is untouched: an AF_UNIX dial resolves no name; 0.6.0: the AF_UNIX dial classifies its errors by the one socket-error table; 0.24.0 (P13): the `EAI_*` half of `resolverErrorTable()` and `detail::resolverSystemCode` | | `src/core/net/TlsCancelRead_test.cpp` | origin: core-cpp | - | - | Task B11 fix round 1: `cancelRead` during a handshake a read drives. POSIX-only until Task B13 gave `WindowsSocket` its `cancelRead`; it runs on every platform since | | `src/core/net/posix/UnixListener.cpp` | contour-terminal/contour | `src/net/posix/UnixListener.cpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | namespaces and includes; no file-wide `#ifndef _WIN32` guard: `SOURCES_POSIX` selects the file (Ruling R42); 0.6.0: `doClose()`; `socket`, `bind` and `listen` failures are classified by the one socket-error table | | `src/core/net/posix/UnixListener.hpp` | contour-terminal/contour | `src/net/posix/UnixListener.hpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | namespaces and includes; no file-wide `#ifndef _WIN32` guard: `SOURCES_POSIX` selects the file (Ruling R42); 0.6.0: `doClose()`, and `close(FdWakePolicy)` is `closeWith` | @@ -414,6 +419,8 @@ others in notes. | `src/core/net/testing/StrictTlsPeer.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/TlsSocket_test.cpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B11: upstream's test-local `TlsPeer`, made a public double of `core::net_tls`: a server role, a strict end-of-stream reading, and peer-certificate queries | | `src/core/net/testing/StrictTlsPeer.hpp` | origin: core-cpp | - | - | Task B11: the interface of the double above, with its OpenSSL state behind an incomplete type | | `src/core/net/testing/ScriptedBackend.hpp` | contour-terminal/contour | `src/net/testing/ScriptedEventSource.hpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | Task B3: `ScriptedEventSource` renamed `ScriptedBackend`, and a real backend rather than a stub -- it dispatches through the same `detail::ReadyBatch` the native ones do. Readiness is scripted against a `HandlerId` handed out in attach order, because a case cannot name a `ReadinessHandler` the loop created inside itself. The live-registration SET (not a count) that A12 added is kept, and so is the throw on an exhausted script; new here are `pushFailure`, `refuseNextAttach`/`refuseNextSetInterest`, and a `wake()` that makes the next wait return without consuming a scripted step Perf lane (v0.2.0): `pushReadiness`, a step reporting several conditions at once.; 0.6.0: `refuseNextAttach(NetError)`, a refusal with a chosen reason | +| `src/core/net/testing/ScriptedAddressResolver.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): a scripted, thread-free `IAddressResolver`; literals parsed, names answered or failed, a hold for offloading resolvers | +| `src/core/net/testing/ScriptedAddressResolver_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the scripted resolver, and the default `resolveClassified` it exercises | | `src/core/net/testing/ScriptedBackend_test.cpp` | origin: core-cpp | - | - | Task B3 fix round 2 (F5): cases over the double itself, in the portable binary because the double is portable. A double that is not faithful about a rule every real backend keeps is worse than none -- a case written against it passes here and fails on four kernels, and its author reads the green as evidence | | `src/core/net/testing/TestLoop.hpp` | LASTRADA-Software/fastcached | `src/FastCache/Async/TestReactor.hpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B4. Upstream is a SECOND reactor, so every rule the platform reactors held had to be written twice and could differ; this is the real `EventLoop` over `NullBackend` with `IdlePolicy::Return`, so a case that passes here and fails on a `PlatformLoop` is a backend difference and nothing else. `Tick`/`Drain` become `tick`/`drain` over `runOnce`/`runUntilIdle`; the mutex, the sequence counter and `AbandonParkedWork` are the loop's | | `src/core/net/testing/TestLoop_test.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Async/TestReactor_test.cpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B4. The thread-safety case asserts that nothing is LOST rather than the size of one container, because where cross-thread work waits between the producer's call and the loop's turn is the loop's business. New here: `cancelPending`'s ownership transfer, on a submission, a deadline park and a readiness park, over every backend -- 'cancelPending means the same on every backend' was a rule of the design that nothing checked | @@ -436,7 +443,7 @@ others in notes. | `src/core/net/windows/NetworkEvents.cpp` | origin: core-cpp | - | - | the one place this module takes a Winsock readiness indication off an event; extracted from `WindowsSocket::latchNetworkEvents` so `WindowsListener::accept` stops reaching for `WSAResetEvent`, which loses a recorded indication (Task A12, gate pass 4, finding 2) | | `src/core/net/windows/NetworkEvents.hpp` | origin: core-cpp | - | - | declares `consumeNetworkEvents` and states why `WSAResetEvent` is never a substitute | | `src/core/net/windows/NetworkEvents_test.cpp` | origin: core-cpp | - | - | drives a listening socket into the state the accept race ends in, and pins both arms: the consume reports the pending connection, the bare reset leaves the event dark for good | -| `src/core/net/windows/SocketsWin32.cpp` | contour-terminal/contour | `src/net/windows/SocketsWin32.cpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | namespaces and includes; `ensureWinsockInitialized()` is `core::platform`'s; the `addrinfo` walk is a `while` that steps to the next candidate first; no file-wide `#ifdef _WIN32` guards, around its body or its `` block: `SOURCES_WINDOWS` selects the file (Ruling R42) Task B8: as `posix/SocketsPosix.cpp` -- `connect` and its `discardEvent` helper move to the portable `Sockets.cpp` over `makeConnector`, and `listen(loop, ListenOptions)` plus `adoptListener` arrive Task B7b: `listen` and `adoptListener` build an `IocpListener` when the loop lends a completion port.; post-import fix: `listenUnix()` makes the parent directory by the path's UTF-8 name (`core::pathFromUtf8()`), as AF_UNIX reads `sun_path`; `listenUnix()` refuses a path that is not UTF-8 (`detail::unixSocketFile()`) before making its parent directory | +| `src/core/net/windows/SocketsWin32.cpp` | contour-terminal/contour | `src/net/windows/SocketsWin32.cpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | namespaces and includes; `ensureWinsockInitialized()` is `core::platform`'s; the `addrinfo` walk is a `while` that steps to the next candidate first; no file-wide `#ifdef _WIN32` guards, around its body or its `` block: `SOURCES_WINDOWS` selects the file (Ruling R42) Task B8: as `posix/SocketsPosix.cpp` -- `connect` and its `discardEvent` helper move to the portable `Sockets.cpp` over `makeConnector`, and `listen(loop, ListenOptions)` plus `adoptListener` arrive Task B7b: `listen` and `adoptListener` build an `IocpListener` when the loop lends a completion port.; post-import fix: `listenUnix()` makes the parent directory by the path's UTF-8 name (`core::pathFromUtf8()`), as AF_UNIX reads `sun_path`; `listenUnix()` refuses a path that is not UTF-8 (`detail::unixSocketFile()`) before making its parent directory; 0.24.0 (P13): the `WSA*` half of `resolverErrorTable()` and `detail::resolverSystemCode` | | `src/core/net/windows/WaitCompletionPacket.cpp` | origin: core-cpp | - | - | Task B7a: `NtCreateWaitCompletionPacket` and friends behind a `GetProcAddress` probe, never a link against `ntdll` -- core-cpp is a library inside other people's builds and may not add an undocumented import to their executables. The kernel's own bridge from a waitable HANDLE to a completion port, taken when the probe answers and an ordinary fallback to the thread-pool wait when it does not | | `src/core/net/windows/WaitCompletionPacket.hpp` | origin: core-cpp | - | - | Task B7a: the reusable packet object and the probe, with `cancel()` documented as an OWNERSHIP answer rather than a status -- `true` means no packet will be delivered and none is sitting in the port, so the caller still holds the arm's share; read the other way round it is a use-after-free on one side and a leak on the other | | `src/core/net/windows/UnixListener_test.cpp` | origin: core-cpp | - | - | v0.2.1: `listenUnix`/`connectUnix` belong to the loop's transport family, over `BackendMatrix`; a socket path beyond ASCII: bound into a directory `listenUnix()` makes, refused to a second listener, deleted on close, reclaimed when stale, and a non-socket file left alone; paths are passed in UTF-8 and probed with `GetFileAttributesW()`; the not-UTF-8 path case; the helpers go through `core::pathFromTrustedUtf8()` | @@ -453,13 +460,13 @@ others in notes. | `src/core/net/Connector_test.cpp` | origin: core-cpp | - | - | Task B8: the case this task exists for -- an injected resolver records the thread it was called on, and a dial asserts that thread is not the loop's. It could not be written against contour's `connect()` at all, which called `getaddrinfo` inline with no seam to inject through. Also the R101 refusal through the public `connect()` on every backend, and `boundPort` reporting the port a bind to 0 actually got | | `src/core/net/IAdmissionControl.hpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/IAdmissionControl.hpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B8. camelBack: `AllowAccept`, `OnConnectionStarted`, `OnConnectionEnded`, `InFlight` and `SetMax` become `allowAccept`, `onConnectionStarted`, `onConnectionEnded`, `inFlight` and `setMax`; the `_in` member is `_inFlight`, since `inFlight()` is what reads it. Reshaped in B8's fix round rather than renamed: `allowAccept` + `onConnectionStarted` are one atomic `tryAdmit()` returning an `AdmissionLease` whose destructor is what `onConnectionEnded` was, and `setMax` is gone -- a check-then-act across two calls let two loops exceed the cap, and `setMax` wrote a plain field other threads read | | `src/core/net/IAdmissionControl_test.cpp` | origin: core-cpp | - | - | Task B8 fix round: upstream had no test. Two threads released together from a barrier race for the last slot, round after round, and exactly one may win each | -| `src/core/net/IAsyncAddressResolver.hpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/IAsyncAddressResolver.hpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B8. camelBack; `IReactor*` is `EventLoop*`, keeping the nullable convention (null means resolve inline and never suspend). `ResolveFailure` is `resolveFailure` and builds its error through `makeNetError` | +| `src/core/net/IAsyncAddressResolver.hpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/IAsyncAddressResolver.hpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B8. camelBack; `IReactor*` is `EventLoop*`, keeping the nullable convention (null means resolve inline and never suspend). `ResolveFailure` is `resolveFailure` and builds its error through `makeNetError`; 0.24.0 (P13): `InlineAddressResolver` calls `resolveClassified`; a `resolveFailure` overload keeps a classified code | | `src/core/net/IConnector.hpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/IConnector.hpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B8. `Connect` is `connect`; `DialOptions` is declared here, which is where upstream keeps it too -- `Net/DialOptions.*` does not exist at the pin. `makeConnector(EventLoop&, IAsyncAddressResolver&)` is new and replaces `Net/PlatformConnector.hpp` | | `src/core/net/KeepAlive.hpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/KeepAlive.hpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B8. The namespace, and the upstream issue links restated as the facts they carried rather than as URLs into another project's tracker | | `src/core/net/ReadinessDial.hpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/ReactorDial.hpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B8. **De-templatised.** Upstream's `DialReadiness` was templated on a `{Reactor, Handler, Socket}` triple PLUS a `Traits::Settle` callback -- four facts, not the three its own comment names -- because `EpollReactor` and `KqueueReactor` had no common base. `EventLoop` is that base, so what is left is one free function, and the platform difference moves to `detail/DialPrimitives.hpp`. The file-wide `#if defined(__linux__) || defined(__APPLE__)` is gone: the dial is portable, Windows included | | `src/core/net/ReadinessDial.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/ReactorDial.hpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B8. `ReadinessDialOp` is `DialOp` and keeps the property that made it right -- it lives in the dialling coroutine's own frame -- and `SettleDial`/`DialPark` keep their shape over `EventLoop::registerPark`. New: stop-awareness, which upstream's dial has none of. A `StopCallback` routes a stop from any thread through `EventLoop::requestCancel`, and a cancelled dial UNWINDS rather than reporting a value, matching `ResultAwaitable::await_resume`. `Traits::Settle`'s three hooks collapse to one `Interest::Write` registration, because `selectReadinessCallback` gives a watched direction priority on every backend | | `src/core/net/ReadinessDial_test.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/EpollConnector_test.cpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B8. ONE suite over `testing::BackendMatrix`, where upstream had an epoll-only file and no kqueue counterpart at all -- which is how the macOS divergence Ruling R101 exists to prevent gets written back in. The refusal case is R101 in its natural habitat. New here: the backlog-saturation arrangement, which SKIPs rather than passing when a stack will not leave a dial outstanding, and a descriptor-leak check that reads the lowest free fd on POSIX | -| `src/core/net/SocketAddress.hpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/SocketAddress.hpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B8. camelBack. The BIND half is deliberately NOT imported -- `BindAndListen`, `BoundListener`, `BoundPortOf`, `PeerAddressOf`, `ReusePort`, `ExclusiveBindOption` -- because core-cpp's listeners already own their bind sequence, and a second one would be a second answer to who owns an address. `FormatPeerAddress` is `formatPeerAddress` and delegates to the module's existing `detail::formatPeer` | +| `src/core/net/SocketAddress.hpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/SocketAddress.hpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B8. camelBack. The BIND half is deliberately NOT imported -- `BindAndListen`, `BoundListener`, `BoundPortOf`, `PeerAddressOf`, `ReusePort`, `ExclusiveBindOption` -- because core-cpp's listeners already own their bind sequence, and a second one would be a second answer to who owns an address. `FormatPeerAddress` is `formatPeerAddress` and delegates to the module's existing `detail::formatPeer`; 0.24.0 (P13): `IAddressResolver::resolveClassified` (defaulted), `ResolverErrorRow`, `resolverErrorTable()`, `detail::endpointOfLiteral`, `detail::classifyResolverError`, `detail::resolverSystemCode` | | `src/core/net/SocketBuffers.hpp` | origin: core-cpp | - | - | v0.2.0: `SocketBufferSizes`, the kernel buffer sizes `ListenOptions` and `DialOptions` ask for; fastcached sized both to 1 MiB in its own socket setup | | `src/core/net/detail/StreamSocketOptions.hpp` | origin: core-cpp | - | - | v0.2.0: the one helper every dial and every accept calls; before it only the dial set `TCP_NODELAY` | | `src/core/net/posix/StreamSocketOptions.cpp` | origin: core-cpp | - | - | v0.2.0; `armKeepAlive` and `wholeSeconds` moved here unchanged from `posix/DialPrimitives.cpp` | @@ -471,14 +478,14 @@ others in notes. | `src/core/net/windows/PortSharing_test.cpp` | origin: core-cpp | - | - | v0.2.0: `PortSharing::Shared` is refused with `Unsupported` | | `src/core/net/AdoptSocket_test.cpp` | origin: core-cpp | - | - | v0.2.0: `adoptSocket` over a connection accepted with plain socket calls, on every backend | | `src/core/net/StreamSocketOptions_test.cpp` | origin: core-cpp | - | - | v0.2.0: reads `TCP_NODELAY` and the buffer sizes back from the kernel, for accepted and dialled sockets on every backend | -| `src/core/net/SocketAddress.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/SocketAddress.cpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B8. Only the four functions the header declares; the `addrinfo` walk is a `while` that steps to the next candidate first, as the listeners' already are. `GaiMessage` is a file-local `resolverMessage` | +| `src/core/net/SocketAddress.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/SocketAddress.cpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B8. Only the four functions the header declares; the `addrinfo` walk is a `while` that steps to the next candidate first, as the listeners' already are. `GaiMessage` is a file-local `resolverMessage`; 0.24.0 (P13): `SystemAddressResolver::resolveClassified` through the table, `resolve` its words; `isNumericHost` is `endpointOfLiteral` | | `src/core/net/SocketAddress_test.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/SocketAddress_test.cpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B8. The cases for the half that was imported. Every resolver case uses a LITERAL, so none depends on a working name server, and the one case that needs a failed lookup SKIPs where a wildcard-answering provider resolves an RFC 2606 `.invalid` name -- the network lying, not this code failing | | `src/core/net/SocketDeadline.hpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/SocketDeadline.hpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B8. camelBack; `IReactor*` is `EventLoop*` and `Clock().Now()` is `clock().now()`. A target holding a null socket arms nothing as well -- upstream checked the target pointer but not the socket in it, and the same caller reaches both | | `src/core/net/SocketDeadline_test.cpp` | origin: core-cpp | - | - | Task B8 fix round: upstream had none. A non-positive ceiling arms nothing, and an expiry records `expired` BEFORE it closes -- observed by a socket that reads the flag at the instant of its own close, since reading it afterwards cannot tell the two orders apart | | `src/core/net/Sockets.cpp` | origin: core-cpp | - | - | Task B8: contour's `connect()` re-implemented OVER `makeConnector` rather than beside it, which is what moves `getaddrinfo` off the loop's thread. Portable, so the two platform `Sockets*.cpp` files no longer carry a `connect` each. The overload taking an `IAsyncAddressResolver*` and `DialOptions` is new | | `src/core/net/ThreadedAddressResolver.hpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/ThreadedAddressResolver.hpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B8. camelBack; `IReactor*` is `EventLoop*`. `defaultAsyncResolver()` is new: the free `connect()` has nowhere to take a resolver from, so the process default is given a NAME -- the shape `defaultAddressResolver` and `platform::defaultSteadyClock` already use -- rather than being a private static nothing can reach past | -| `src/core/net/ThreadedAddressResolver.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/ThreadedAddressResolver.cpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B8. camelBack; `Submit` is `EventLoop::submit` and `Detail::Parked` is `async::detail::Parked`. `std::vector` is `std::vector` joined explicitly, for the reason `core/async/ThreadPoolExecutor.hpp` records: `__cpp_lib_jthread` is exactly what `StopToken.hpp` carries a fallback for | -| `src/core/net/ThreadedAddressResolver_test.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/ThreadedAddressResolver_test.cpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B8. A scripted blocking inner that RECORDS the thread each lookup ran on, so a name never resolving on the loop's thread is an assertion rather than a paragraph; a holding latch makes the full-queue and stopped-while-queued states arranged rather than raced. No name server is involved in any case here | +| `src/core/net/ThreadedAddressResolver.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/ThreadedAddressResolver.cpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B8. camelBack; `Submit` is `EventLoop::submit` and `Detail::Parked` is `async::detail::Parked`. `std::vector` is `std::vector` joined explicitly, for the reason `core/async/ThreadPoolExecutor.hpp` records: `__cpp_lib_jthread` is exactly what `StopToken.hpp` carries a fallback for; 0.24.0 (P13): both arms call `resolveClassified` P13 Task 7: the slot, its stop callback and the stop-aware awaiter move to `detail/ParkedCall.hpp`, whose one `SlotState` replaces the `done`/`cancelled` flags | +| `src/core/net/ThreadedAddressResolver_test.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/ThreadedAddressResolver_test.cpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B8. A scripted blocking inner that RECORDS the thread each lookup ran on, so a name never resolving on the loop's thread is an assertion rather than a paragraph; a holding latch makes the full-queue and stopped-while-queued states arranged rather than raced. No name server is involved in any case here P13 Task 7: the test-local scripted resolver is gone; the cases run over `testing::ScriptedAddressResolver`, which gained `callers()` | | `src/core/net/IDatagramSocket.hpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/IDatagramSocket.hpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B9. camelBack; `Send`/`Receive`/`Close`/`BoundAddress` as `send`/`receive`/`close`/`boundAddress` | | `src/core/net/UdpSocket.hpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/UdpSocket.hpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B9. `OpenUdpSocket` is `openUdpSocket` and returns `std::expected<..., NetError>` where upstream returned a null pointer; `MaxIpv4DatagramPayload` (65507) and `MaxIpv6DatagramPayload` (65527), chosen by the bound family, replace the private 8 KiB bound, and a datagram longer than the buffer is `DatagramWait::MessageTooLarge` rather than delivered cut short | | `src/core/net/posix/UdpSocket.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/UdpSocket.cpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B9: the POSIX half of upstream's `#if defined(_WIN32)` split. Close-on-exec (`makeDatagramSocket`); errors through `detail/SocketErrors.hpp`, so `EMSGSIZE` is `MessageTooLarge`; one receive buffer per socket | @@ -511,8 +518,10 @@ others in notes. | `src/core/net/detail/SocketErrors.hpp` | origin: core-cpp | - | - | Task B9: one socket-error table per platform, declared once | | `src/core/net/posix/SocketErrors.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/BlockingSocket.cpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B9: `TranslateErrorImpl`'s POSIX table, plus `EMSGSIZE`; 0.6.0: `EMFILE`, `ENFILE`, `ENOBUFS`, `ENOMEM` are `ResourceExhausted` | | `src/core/net/posix/SocketErrors_test.cpp` | origin: core-cpp | - | - | Task B13: every row of the one socket-error table, asserted -- every transport and the dial read their errors through it, and nothing else in the suite provokes most of these codes | +| `src/core/net/posix/ResolverErrors_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the `EAI_*` rows of `resolverErrorTable()`, and its completeness asked of `gai_strerror` | | `src/core/net/windows/SocketErrors.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/BlockingSocket.cpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B9: `TranslateErrorImpl`'s Winsock table, plus `WSAEMSGSIZE`; 0.6.0: `WSAEMFILE`, `WSAENOBUFS` are `ResourceExhausted` | | `src/core/net/windows/SocketErrors_test.cpp` | origin: core-cpp | - | - | Task B13: every row of the one socket-error table, asserted -- every transport and the dial read their errors through it, and nothing else in the suite provokes most of these codes | +| `src/core/net/windows/ResolverErrors_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the `WSA*` rows of `resolverErrorTable()`, held to the documented list whole | | `src/core/net/BlockingConnector.hpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/BlockingConnector.hpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B9, ruled from B8 because it constructs a `BlockingSocket`. camelBack | | `src/core/net/BlockingConnector.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/BlockingConnector.cpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B9. Over the shared `detail::runConnectFlow` and B8's dial primitives, rather than a socket/connect/`SO_ERROR` sequence of its own | | `src/core/net/BlockingConnector_test.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/BlockingConnector_test.cpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B9. Against loop listeners, since `BlockingListener` is not imported | diff --git a/src/core/net/AcceptPolicy.hpp b/src/core/net/AcceptPolicy.hpp index 7704da0d..4d2d41a1 100644 --- a/src/core/net/AcceptPolicy.hpp +++ b/src/core/net/AcceptPolicy.hpp @@ -118,6 +118,10 @@ inline constexpr auto AcceptErrorTable = // `WSA_NOT_ENOUGH_MEMORY`: out of descriptors, buffer space or memory. Accepting again at once // would spin a core; nothing else about it is wrong. { .code = NetErrorCode::ResourceExhausted, .disposition = AcceptDisposition::Exhausted }, + // A name lookup's answers, which an accept never gives -- like the bind-time ones above, + // nothing says they pass. + { .code = NetErrorCode::NameNotFound, .disposition = AcceptDisposition::Unclassified }, + { .code = NetErrorCode::ResolverTemporaryFailure, .disposition = AcceptDisposition::Unclassified }, } }; namespace detail diff --git a/src/core/net/AcceptPolicy_test.cpp b/src/core/net/AcceptPolicy_test.cpp index f08e74a0..23f01064 100644 --- a/src/core/net/AcceptPolicy_test.cpp +++ b/src/core/net/AcceptPolicy_test.cpp @@ -88,6 +88,9 @@ TEST_CASE("Only a closed or dead listener ends an accept loop at once", "[net][a // A poll timeout is one event under two names, and neither is a failure. expect(NetErrorCode::Timeout, AcceptDisposition::PollTick); expect(NetErrorCode::WouldBlock, AcceptDisposition::PollTick); + // A resolver's answers that an accept never gives, like the bind-time ones: nothing says they pass. + expect(NetErrorCode::NameNotFound, AcceptDisposition::Unclassified); + expect(NetErrorCode::ResolverTemporaryFailure, AcceptDisposition::Unclassified); // A value that is no code is unclassified: backed off on within a bound, never spun on. expect(NetErrorCode::Last, AcceptDisposition::Unclassified); INFO("classified wrongly: " << wrong); diff --git a/src/core/net/CMakeLists.txt b/src/core/net/CMakeLists.txt index f3183e35..20032f25 100644 --- a/src/core/net/CMakeLists.txt +++ b/src/core/net/CMakeLists.txt @@ -127,6 +127,7 @@ core_cpp_add_module(net KIND STATIC DeadlineTimer.hpp Diagnostics.hpp EventLoop.hpp + ExecutorAddressResolver.hpp HealthProbe.hpp HostDrivenBackend.hpp HttpServer.hpp @@ -162,6 +163,7 @@ core_cpp_add_module(net KIND STATIC WithTimeout.hpp WriteQueue.hpp detail/CompletionHook.hpp + detail/ParkedCall.hpp detail/ParkId.hpp detail/ParkTable.hpp detail/ReadinessSlot.hpp @@ -181,6 +183,7 @@ core_cpp_add_module(net KIND STATIC testing/NullBackend.hpp testing/ParkingReadableSocket.hpp testing/RawSockets.hpp + testing/ScriptedAddressResolver.hpp testing/ScriptedBackend.hpp testing/SocketDecorator.hpp testing/TestLoop.hpp @@ -194,6 +197,7 @@ core_cpp_add_module(net KIND STATIC ConnectFlow.cpp Connector.cpp Diagnostics.cpp + ExecutorAddressResolver.cpp HealthProbe.cpp HttpServer.cpp ISocket.cpp @@ -359,6 +363,7 @@ core_cpp_add_test(net ConnectFlow_test.cpp Connector_test.cpp EventLoop_test.cpp + ExecutorAddressResolver_test.cpp HealthProbe_test.cpp HttpServer_test.cpp IAdmissionControl_test.cpp @@ -378,10 +383,12 @@ core_cpp_add_test(net WaitReadable_test.cpp WithTimeout_test.cpp WriteQueue_test.cpp + detail/ParkedCall_test.cpp testing/FailingListener_test.cpp testing/InMemoryDatagram_test.cpp testing/InMemorySocket_test.cpp testing/ParkingReadableSocket_test.cpp + testing/ScriptedAddressResolver_test.cpp testing/TestLoop_test.cpp # POSIX-only, each for its own reason. `ReactorSocket_test` names PosixSocket directly, and # `SocketRegistration_test` counts what PosixSocket's kept registration costs the backend. @@ -412,6 +419,7 @@ core_cpp_add_test(net posix/AdoptListener_test.cpp posix/FdPassing_test.cpp posix/PortSharing_test.cpp + posix/ResolverErrors_test.cpp posix/SocketErrors_test.cpp posix/SshAgentEndpoint_test.cpp posix/UnixSocket_test.cpp @@ -424,6 +432,7 @@ core_cpp_add_test(net windows/NamedPipe_test.cpp windows/NetworkEvents_test.cpp windows/PortSharing_test.cpp + windows/ResolverErrors_test.cpp windows/SocketErrors_test.cpp windows/SshAgentEndpoint_test.cpp windows/UnixListener_test.cpp diff --git a/src/core/net/ExecutorAddressResolver.cpp b/src/core/net/ExecutorAddressResolver.cpp new file mode 100644 index 00000000..7a28a07c --- /dev/null +++ b/src/core/net/ExecutorAddressResolver.cpp @@ -0,0 +1,217 @@ +// SPDX-License-Identifier: Apache-2.0 +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace core::net +{ + +namespace +{ + + /// One lookup's rendezvous between the executor that runs it and the parked flow. + using ResolveCall = detail::ParkedCall; + + /// Whether a lookup got one of the budget's slots. + enum class SlotReservation : std::uint8_t + { + Refused, ///< The budget was full; nothing was taken. + Reserved, ///< One slot is the caller's, to be given back exactly once. + }; + + /// Takes one slot of @p inFlight's budget, if one is free. + /// + /// A loop of compare-exchange rather than an add and a take-back, so that a full budget is never + /// exceeded even for a moment -- several loops may resolve through one resolver at once. + /// @param inFlight The slots taken. + /// @param maxInFlight How many there are. + /// @return Whether one was taken. + [[nodiscard]] SlotReservation reserveSlot(std::atomic& inFlight, + std::size_t maxInFlight) noexcept + { + auto current = inFlight.load(std::memory_order_relaxed); + do + { + if (current >= maxInFlight) + return SlotReservation::Refused; + } while (!inFlight.compare_exchange_weak( + current, current + 1, std::memory_order_acq_rel, std::memory_order_relaxed)); + return SlotReservation::Reserved; + } + + /// One lookup's slot and its answer, owned by the detached flow that runs it. + /// + /// **Its destructor is the guard of the slot rule.** A lookup that finishes gives the slot back + /// and settles its call through @c finish. One that never gets there — its executor freed it + /// unrun, or its frame could not even be allocated — reaches the destructor with both still + /// held, and the destructor frees the slot and answers the waiter @c NetErrorCode::Cancelled, so + /// neither a coroutine nor a slot is stranded. Nothing on that path throws. + class LookupLease + { + public: + LookupLease(std::shared_ptr> inFlight, + std::shared_ptr call) noexcept: + _inFlight(std::move(inFlight)), _call(std::move(call)) + { + } + + LookupLease(LookupLease&&) noexcept = default; + LookupLease(LookupLease const&) = delete; + LookupLease& operator=(LookupLease const&) = delete; + LookupLease& operator=(LookupLease&&) = delete; + + ~LookupLease() { fail(NetErrorCode::Cancelled); } + + /// Gives the slot back, THEN answers the waiter. + /// + /// In that order so that a flow resumed with its answer never finds its own slot still + /// taken -- at the cap, a lookup it starts next would otherwise be refused for nothing. The + /// slot still stands for the executor's thread: it is given back only once the blocking + /// call has returned, a stopped lookup's included. At most once; a later call does nothing. + /// @param answer What the lookup came to. + void finish(ResolveResult answer) noexcept + { + auto const call = std::exchange(_call, nullptr); + auto const inFlight = std::exchange(_inFlight, nullptr); + if (!call) + return; + inFlight->fetch_sub(1, std::memory_order_acq_rel); + call->settle(std::move(answer)); + } + + /// Finishes with a failure that allocates nothing, for the paths that cannot take a throw. + /// @param code What the waiter is told. + void fail(NetErrorCode code) noexcept + { + if (!_call) + return; + // No context: a destructor and a catch-all have no message worth an allocation. + finish(std::unexpected(makeNetError(code))); + } + + private: + std::shared_ptr> _inFlight; + std::shared_ptr _call; + }; + + /// Runs one lookup on @p blocking and answers its call. + /// + /// Detached, because nobody may own it: the waiting flow can be stopped and gone long before + /// `getaddrinfo` returns. Everything it touches it holds by value or by share — never the + /// resolver that started it — so it outlives that resolver safely. Whatever is thrown on the + /// way -- an executor that cannot queue it, an allocation inside the inner resolver -- is caught + /// and answered @c NetErrorCode::SystemError: an exception escaping a detached flow ends the + /// process, and a waiter not answered would be stranded. + /// @param blocking Where the lookup runs. + /// @param inner The blocking resolver. + /// @param host The name to look up. + /// @param port The port to pair it with. + /// @param lease The lookup's slot and call. + async::DetachedTask runLookup(async::IExecutor* blocking, + std::shared_ptr inner, + std::string host, + std::uint16_t port, + LookupLease lease) + { + try + { + co_await async::ResumeOn { *blocking }; + auto resolved = inner->resolveClassified(host, port); + if (resolved.has_value()) + lease.finish(std::move(*resolved)); + else + lease.finish(std::unexpected(resolveFailure(host, port, std::move(resolved.error())))); + } + catch (...) + { + lease.fail(NetErrorCode::SystemError); + } + } + +} // namespace + +ExecutorAddressResolver::ExecutorAddressResolver(async::IExecutor& blocking, + std::shared_ptr inner, + ExecutorResolverOptions options): + _blocking(blocking), + _inner(std::move(inner)), + _options(options), + _inFlight(std::make_shared>(0)) +{ +} + +std::size_t ExecutorAddressResolver::refused() const noexcept +{ + return _refused.load(std::memory_order_relaxed); +} + +std::size_t ExecutorAddressResolver::offloaded() const noexcept +{ + return _offloaded.load(std::memory_order_relaxed); +} + +std::size_t ExecutorAddressResolver::inFlight() const noexcept +{ + return _inFlight->load(std::memory_order_acquire); +} + +async::Task ExecutorAddressResolver::resolve(std::string host, + std::uint16_t port, + EventLoop* loop) +{ + if (auto checked = detail::checkLookupHost(host); !checked.has_value()) + co_return std::unexpected(std::move(checked.error())); + + // A literal needs no lookup, so it needs neither the executor nor the inner resolver. + if (auto literal = detail::endpointOfLiteral(host, port)) + co_return std::vector { *literal }; + + // With nowhere to submit a result back to, offloading would park a coroutine nothing could + // ever resume. + if (loop == nullptr) + { + auto resolved = _inner->resolveClassified(host, port); + if (!resolved.has_value()) + co_return std::unexpected(resolveFailure(host, port, std::move(resolved.error()))); + co_return std::move(*resolved); + } + + // A flow already stopped is not handed to the executor at all: its lookup would take a slot + // and a thread for an answer nobody can receive. + if ((co_await async::thisCoroStopToken()).stop_requested()) + throw async::OperationCancelled {}; + + // Allocated before the slot is taken, so a failed allocation has no slot to give back. + auto call = std::make_shared(loop); + if (reserveSlot(*_inFlight, _options.maxInFlight) == SlotReservation::Refused) + { + _refused.fetch_add(1, std::memory_order_relaxed); + co_return std::unexpected( + makeNetError(NetErrorCode::ResourceExhausted, + 0, + std::format("the resolver budget is full ({} in flight); not resolving {}:{}", + _options.maxInFlight, + host, + port))); + } + + _offloaded.fetch_add(1, std::memory_order_relaxed); + runLookup(&_blocking, _inner, std::move(host), port, LookupLease { _inFlight, call }); + co_return co_await ResolveCall::wait(std::move(call)); +} + +} // namespace core::net diff --git a/src/core/net/ExecutorAddressResolver.hpp b/src/core/net/ExecutorAddressResolver.hpp new file mode 100644 index 00000000..da25c171 --- /dev/null +++ b/src/core/net/ExecutorAddressResolver.hpp @@ -0,0 +1,115 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// `ExecutorAddressResolver` — an @c IAsyncAddressResolver that owns no thread: every lookup runs +/// on a blocking executor its owner injects. + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace core::net +{ + +/// How many lookups may be outstanding at once. +/// +/// At namespace scope rather than nested in @c ExecutorAddressResolver, for the reason +/// @c ThreadedResolverOptions is: a defaulted parameter of a nested type whose own default member +/// initializers are not yet complete is rejected outright. +struct ExecutorResolverOptions +{ + /// Largest number of lookups holding a slot: handed to the executor and not yet returned from + /// the blocking resolver. A lookup past it is refused with @c NetErrorCode::ResourceExhausted. + std::size_t maxInFlight { 256 }; +}; + +/// Name resolution on an injected executor, with no thread of its own. +/// +/// `getaddrinfo` blocks and takes no timeout, so somebody's thread has to wait for it; where +/// @c ThreadedAddressResolver brings a pool of its own, this one runs every lookup on the +/// @c async::IExecutor it is given — the process's blocking pool, a host's worker, a test's +/// @c async::testing::ManualExecutor. Each lookup is a detached flow that hops onto that executor, +/// calls @c IAddressResolver::resolveClassified there, and hands the waiting flow back to its loop. +/// +/// - **A literal never reaches the executor**: it is parsed in place by +/// @c detail::endpointOfLiteral, and the inner resolver is not asked. +/// - **A null loop resolves inline** through the inner resolver, because with nowhere to hand a +/// result back to, offloading would park a coroutine nothing could resume. +/// - **The budget is bounded and a full one is refused**, as @c ThreadedAddressResolver's queue +/// is: over @c ExecutorResolverOptions::maxInFlight a lookup answers +/// @c NetErrorCode::ResourceExhausted at once rather than waiting for room on the loop thread. +/// - **A stop ends the wait, not the lookup.** The awaiting flow is handed back to its loop and +/// throws @c async::OperationCancelled; the lookup keeps its slot until the blocking call has +/// returned, because until then it still occupies the executor, and its late answer goes +/// nowhere. +/// - **A lookup the executor drops unrun** (an executor destroyed with it queued) releases its slot +/// and answers its waiter @c NetErrorCode::Cancelled, a cancellation by the resource and so a +/// value rather than a throw. +/// +/// - **A flow already stopped is not offloaded**: it throws @c async::OperationCancelled before it +/// takes a slot. +/// +/// **Teardown order.** A lookup outlives this resolver safely — it holds the inner resolver and +/// the slot count by share. What it does not outlive is the loop of a flow still parked on it, +/// which its answer is handed to: destroy a loop only once no flow of it is parked on a lookup +/// (each finished, or stopped -- a stopped flow's late answer goes nowhere). The executor, too, must +/// outlive every lookup queued on it, or drop them (which answers @c NetErrorCode::Cancelled). +/// +/// **A stopped @c async::ThreadPoolExecutor runs what is submitted inline**, on the submitting +/// thread: a lookup started after its `stop()` runs `getaddrinfo` on the LOOP thread, which is the +/// stall this class exists to remove. Stop resolving through this resolver before stopping its pool. +class CORE_NET_API ExecutorAddressResolver final: public IAsyncAddressResolver +{ + public: + /// @param blocking Where lookups run; must outlive, or drop, every lookup queued on it. + /// @param inner Shared, because a job may outlive the resolver. + /// @param options The lookup budget. + ExecutorAddressResolver(async::IExecutor& blocking, + std::shared_ptr inner, + ExecutorResolverOptions options = {}); + + ExecutorAddressResolver(ExecutorAddressResolver const&) = delete; + ExecutorAddressResolver& operator=(ExecutorAddressResolver const&) = delete; + ExecutorAddressResolver(ExecutorAddressResolver&&) = delete; + ExecutorAddressResolver& operator=(ExecutorAddressResolver&&) = delete; + ~ExecutorAddressResolver() override = default; + + /// @copydoc IAsyncAddressResolver::resolve + /// + /// A failure carries the code @c IAddressResolver::resolveClassified gave it. + /// Host text @c detail::checkLookupHost refuses (empty, an embedded NUL, more than 253 bytes) is + /// @c NetErrorCode::AddressError before any lookup starts, whatever @p loop is. + [[nodiscard]] async::Task resolve(std::string host, + std::uint16_t port, + EventLoop* loop) override; + + /// @return How many lookups have been refused for want of a slot. + [[nodiscard]] std::size_t refused() const noexcept; + + /// @return How many lookups this resolver has handed to its executor. Zero for a process that + /// only resolves literals. + [[nodiscard]] std::size_t offloaded() const noexcept; + + /// @return How many lookups hold a slot right now: handed to the executor and not yet returned + /// from the blocking resolver, a cancelled one included. + [[nodiscard]] std::size_t inFlight() const noexcept; + + private: + async::IExecutor& _blocking; + std::shared_ptr _inner; + ExecutorResolverOptions _options; + /// The slot count, shared with every lookup in flight, which releases its slot itself. + std::shared_ptr> _inFlight; + std::atomic _refused { 0 }; + std::atomic _offloaded { 0 }; +}; + +} // namespace core::net diff --git a/src/core/net/ExecutorAddressResolver_test.cpp b/src/core/net/ExecutorAddressResolver_test.cpp new file mode 100644 index 00000000..d908f234 --- /dev/null +++ b/src/core/net/ExecutorAddressResolver_test.cpp @@ -0,0 +1,496 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// `ExecutorAddressResolver`: a lookup runs on the executor it was given and on no thread of the +// resolver's own, a stop ends the wait and not the lookup, and its `maxInFlight` slot is held until +// the lookup it stands for has actually returned. +#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 + +using core::async::Task; +using core::async::testing::ManualExecutor; +using core::net::EventLoop; +using core::net::ExecutorAddressResolver; +using core::net::NetErrorCode; +using core::net::ResolvedEndpoint; +using core::net::ResolveResult; +using core::net::testing::ScriptedAddressResolver; +using core::net::testing::TestLoop; + +namespace +{ + +/// What one awaited lookup came to: nothing yet, an answer (possibly a failure), or a stop. +struct Outcome +{ + std::optional answer; + bool isCancelled = false; + std::atomic isFinished { false }; +}; + +/// Resolves @p host through @p resolver on @p loop and records how it ended, a stop included. +Task resolveInto(EventLoop* loop, ExecutorAddressResolver* resolver, std::string host, Outcome* out) +{ + try + { + out->answer = co_await resolver->resolve(std::move(host), 80, loop); + } + catch (core::async::OperationCancelled const&) + { + out->isCancelled = true; + } + out->isFinished.store(true, std::memory_order_release); +} + +/// A scripted inner that answers `db.test` with one endpoint. +[[nodiscard]] std::shared_ptr scriptedInner() +{ + auto inner = std::make_shared(); + inner->answer("db.test", { ResolvedEndpoint { .length = 16, .family = 2, .protocol = 6 } }); + return inner; +} + +} // namespace + +TEST_CASE("a literal resolves inline and never reaches the blocking executor", "[net][resolver]") +{ + auto clock = core::platform::ManualClock {}; + auto loop = TestLoop { clock }; + auto blocking = ManualExecutor {}; + auto inner = scriptedInner(); + auto resolver = ExecutorAddressResolver { blocking, inner }; + + auto outcome = Outcome {}; + // Spawned and drained rather than blocked on: a lookup that parked by mistake fails here + // instead of hanging the case. + loop.spawn(resolveInto(&loop, &resolver, "127.0.0.1", &outcome)); + loop.drain(); + REQUIRE(outcome.isFinished.load()); + + REQUIRE(outcome.answer.has_value()); + REQUIRE(outcome.answer->has_value()); + CHECK((*outcome.answer)->size() == 1); + CHECK(blocking.pending() == 0); + CHECK(resolver.offloaded() == 0); + CHECK(inner->calls() == 0); +} + +TEST_CASE("a null loop resolves inline, because there is nowhere to hand a result back to", "[net][resolver]") +{ + auto clock = core::platform::ManualClock {}; + auto loop = TestLoop { clock }; + auto blocking = ManualExecutor {}; + auto inner = scriptedInner(); + auto resolver = ExecutorAddressResolver { blocking, inner }; + + auto outcome = Outcome {}; + // Spawned and drained rather than blocked on: a lookup that parked by mistake fails here + // instead of hanging the case. + loop.spawn(resolveInto(nullptr, &resolver, "db.test", &outcome)); + loop.drain(); + REQUIRE(outcome.isFinished.load()); + + REQUIRE(outcome.answer.has_value()); + CHECK(outcome.answer->has_value()); + CHECK(blocking.pending() == 0); + CHECK(resolver.offloaded() == 0); + CHECK(inner->calls() == 1); +} + +TEST_CASE("a name is looked up on the injected executor and answered on the loop", "[net][resolver]") +{ + // The executor is drained by this thread, so the lookup running here proves it ran where the + // executor runs things: the resolver has no thread to run it anywhere else. + auto clock = core::platform::ManualClock {}; + auto loop = TestLoop { clock }; + auto blocking = ManualExecutor {}; + auto inner = scriptedInner(); + auto resolver = ExecutorAddressResolver { blocking, inner }; + + auto outcome = Outcome {}; + loop.spawn(resolveInto(&loop, &resolver, "db.test", &outcome)); + loop.drain(); + REQUIRE(blocking.pending() == 1); + CHECK(resolver.offloaded() == 1); + CHECK(resolver.inFlight() == 1); + CHECK(inner->calls() == 0); + CHECK_FALSE(outcome.isFinished.load()); + + CHECK(blocking.drain() == 1); + CHECK_FALSE(outcome.isFinished.load()); // handed back to the loop, never resumed by the executor + CHECK(loop.drain() > 0); + + REQUIRE(outcome.answer.has_value()); + REQUIRE(outcome.answer->has_value()); + CHECK((*outcome.answer)->size() == 1); + CHECK(resolver.inFlight() == 0); + REQUIRE(inner->callers().size() == 1); + CHECK(inner->callers().front() == std::this_thread::get_id()); +} + +TEST_CASE("a classified failure survives the hop to and from the blocking executor", "[net][resolver]") +{ + auto clock = core::platform::ManualClock {}; + auto loop = TestLoop { clock }; + auto blocking = ManualExecutor {}; + auto inner = std::make_shared(); + inner->failWithCode(core::net::makeNetError(NetErrorCode::ResolverTemporaryFailure, 0, "SERVFAIL")); + auto resolver = ExecutorAddressResolver { blocking, inner }; + + auto outcome = Outcome {}; + loop.spawn(resolveInto(&loop, &resolver, "flaky.test", &outcome)); + loop.drain(); + blocking.drain(); + loop.drain(); + + REQUIRE(outcome.answer.has_value()); + REQUIRE_FALSE(outcome.answer->has_value()); + CHECK(outcome.answer->error().code == NetErrorCode::ResolverTemporaryFailure); + CHECK(outcome.answer->error().context == "cannot resolve flaky.test:80: SERVFAIL"); +} + +TEST_CASE("a stop during an offloaded lookup throws on the loop and discards the late answer", + "[net][resolver]") +{ + // `getaddrinfo` cannot be interrupted, so a stop ends the WAIT: the flow is handed back to its + // loop at once and throws, while the lookup keeps its slot until it has really returned. Its + // answer then lands in a call nobody waits on, and a resumption queued to the loop is what + // delivering it into the gone frame would look like. + auto clock = core::platform::ManualClock {}; + auto loop = TestLoop { clock }; + auto blocking = ManualExecutor {}; + auto inner = scriptedInner(); + auto resolver = ExecutorAddressResolver { blocking, inner }; + + auto outcome = Outcome {}; + loop.spawn(resolveInto(&loop, &resolver, "db.test", &outcome)); + loop.drain(); + REQUIRE(blocking.pending() == 1); + + loop.rootStopSource().request_stop(); + loop.drain(); + CHECK(outcome.isCancelled); + CHECK_FALSE(outcome.answer.has_value()); + CHECK(resolver.inFlight() == 1); // the lookup has not run yet, so it still holds its slot + + blocking.drain(); + CHECK(loop.drain() == 0); + CHECK(resolver.inFlight() == 0); + CHECK(inner->calls() == 1); + CHECK_FALSE(outcome.answer.has_value()); +} + +TEST_CASE("a blocking executor dropping a queued lookup settles it Cancelled and frees its slot", + "[net][resolver]") +{ + // A job its executor destroys unrun is freed, not resumed; the lookup's guard runs in the + // freed frame and is what keeps the waiter from being stranded and the slot from leaking. + auto clock = core::platform::ManualClock {}; + auto loop = TestLoop { clock }; + auto blocking = std::make_unique(); + auto inner = scriptedInner(); + auto resolver = ExecutorAddressResolver { *blocking, inner }; + + auto outcome = Outcome {}; + loop.spawn(resolveInto(&loop, &resolver, "db.test", &outcome)); + loop.drain(); + REQUIRE(blocking->pending() == 1); + + SECTION("with the flow still waiting") + { + blocking.reset(); + CHECK(resolver.inFlight() == 0); + CHECK(loop.drain() > 0); + REQUIRE(outcome.answer.has_value()); + REQUIRE_FALSE(outcome.answer->has_value()); + CHECK(outcome.answer->error().code == NetErrorCode::Cancelled); + CHECK_FALSE(outcome.isCancelled); + } + + SECTION("after the flow was stopped") + { + loop.rootStopSource().request_stop(); + loop.drain(); + REQUIRE(outcome.isCancelled); + CHECK(resolver.inFlight() == 1); + + blocking.reset(); + CHECK(resolver.inFlight() == 0); + CHECK(loop.drain() == 0); + } + + CHECK(inner->calls() == 0); +} + +TEST_CASE("a stopped lookup keeps its slot until the blocking call returns", "[net][resolver][threading]") +{ + // The slot stands for the executor's thread, and a stop does not give that thread back: the + // lookup is still inside `getaddrinfo`. So the slot is held while the inner resolver is, and + // freed only once it returns. + constexpr auto Budget = std::chrono::seconds { 10 }; + + auto clock = core::platform::ManualClock {}; + auto loop = TestLoop { clock }; + auto inner = scriptedInner(); + inner->hold(); + auto pool = core::async::ThreadPoolExecutor { 1 }; + // Released on every way out, before the pool joins its held thread. + auto const releaseOnExit = core::net::detail::ScopeGuard { [&inner]() noexcept { inner->release(); } }; + auto resolver = ExecutorAddressResolver { pool, inner }; + + auto outcome = Outcome {}; + loop.spawn(resolveInto(&loop, &resolver, "db.test", &outcome)); + loop.drain(); + REQUIRE(inner->awaitEntered(1, Budget) == 1); + + loop.rootStopSource().request_stop(); + loop.drain(); + CHECK(outcome.isCancelled); + CHECK(resolver.inFlight() == 1); + + inner->release(); + auto const deadline = std::chrono::steady_clock::now() + Budget; + while (resolver.inFlight() != 0 && std::chrono::steady_clock::now() < deadline) + std::this_thread::yield(); + CHECK(resolver.inFlight() == 0); + pool.stop(); + CHECK(loop.drain() == 0); + CHECK_FALSE(outcome.answer.has_value()); +} + +TEST_CASE("a scoped IPv6 literal is offloaded, so its zone reaches the resolver", "[net][resolver]") +{ + // Parsed in place, the zone would be dropped where the platform's inet_pton accepts it (macOS); + // the blocking resolver keeps it, on every platform. + auto clock = core::platform::ManualClock {}; + auto loop = TestLoop { clock }; + auto blocking = ManualExecutor {}; + auto inner = scriptedInner(); + inner->answer("fe80::1%lo", { ResolvedEndpoint { .length = 16, .family = 2, .protocol = 6 } }); + auto resolver = ExecutorAddressResolver { blocking, inner }; + + auto outcome = Outcome {}; + loop.spawn(resolveInto(&loop, &resolver, "fe80::1%lo", &outcome)); + loop.drain(); + CHECK(blocking.pending() == 1); + CHECK(resolver.offloaded() == 1); + + blocking.drain(); + loop.drain(); + REQUIRE(outcome.answer.has_value()); + CHECK(outcome.answer->has_value()); + CHECK(inner->calls() == 1); +} + +TEST_CASE("a flow already stopped throws before it takes a slot", "[net][resolver]") +{ + auto clock = core::platform::ManualClock {}; + auto loop = TestLoop { clock }; + auto blocking = ManualExecutor {}; + auto inner = scriptedInner(); + auto resolver = ExecutorAddressResolver { blocking, inner }; + + loop.rootStopSource().request_stop(); + auto outcome = Outcome {}; + loop.spawn(resolveInto(&loop, &resolver, "db.test", &outcome)); + loop.drain(); + + REQUIRE(outcome.isFinished.load()); + CHECK(outcome.isCancelled); + CHECK(blocking.pending() == 0); + CHECK(resolver.offloaded() == 0); + CHECK(resolver.inFlight() == 0); +} + +TEST_CASE("a full lookup budget is refused rather than waited on", "[net][resolver]") +{ + auto clock = core::platform::ManualClock {}; + auto loop = TestLoop { clock }; + auto blocking = ManualExecutor {}; + auto inner = scriptedInner(); + auto resolver = ExecutorAddressResolver { blocking, inner, { .maxInFlight = 1 } }; + + auto first = Outcome {}; + loop.spawn(resolveInto(&loop, &resolver, "db.test", &first)); + loop.drain(); + REQUIRE(resolver.inFlight() == 1); + + auto second = Outcome {}; + // Spawned and drained rather than blocked on: a lookup that parked by mistake fails here + // instead of hanging the case. + loop.spawn(resolveInto(&loop, &resolver, "db.test", &second)); + loop.drain(); + REQUIRE(second.isFinished.load()); + REQUIRE(second.answer.has_value()); + REQUIRE_FALSE(second.answer->has_value()); + CHECK(second.answer->error().code == NetErrorCode::ResourceExhausted); + CHECK_FALSE(core::net::isDeadlineExpiry(second.answer->error().code)); + CHECK(resolver.refused() == 1); + CHECK(resolver.offloaded() == 1); + CHECK(blocking.pending() == 1); + + blocking.drain(); + loop.drain(); + REQUIRE(first.answer.has_value()); + CHECK(first.answer->has_value()); + CHECK(resolver.inFlight() == 0); + + // The slot is back: a third lookup is offloaded rather than refused. + auto third = Outcome {}; + loop.spawn(resolveInto(&loop, &resolver, "db.test", &third)); + loop.drain(); + CHECK(blocking.pending() == 1); + CHECK(resolver.refused() == 1); + blocking.drain(); + loop.drain(); + REQUIRE(third.answer.has_value()); + CHECK(third.answer->has_value()); +} + +TEST_CASE("a lookup outlives the resolver that started it", "[net][resolver]") +{ + // The job holds what it needs -- the inner resolver and the slot budget -- by share, so + // destroying the resolver first leaves it nothing dangling to touch (ASan watches this one). + auto clock = core::platform::ManualClock {}; + auto loop = TestLoop { clock }; + auto blocking = ManualExecutor {}; + auto inner = scriptedInner(); + auto resolver = std::make_unique(blocking, inner); + + auto outcome = Outcome {}; + loop.spawn(resolveInto(&loop, resolver.get(), "db.test", &outcome)); + loop.drain(); + REQUIRE(blocking.pending() == 1); + + resolver.reset(); + CHECK(blocking.drain() == 1); + CHECK(loop.drain() > 0); + REQUIRE(outcome.answer.has_value()); + CHECK(outcome.answer->has_value()); + CHECK(inner->calls() == 1); +} + +TEST_CASE("a stop racing a completion on a pool ends the flow exactly one way", "[net][resolver][threading]") +{ + // The stop is requested on this thread while a pool thread finishes the lookup and settles + // it, so the two take the waiter in either order. Whoever takes it decides: an answer or an + // `OperationCancelled`, never both and never neither. The stop comes after a delay that varies + // from round to round, so that both orders are actually met rather than assumed. + // + // One loop for every round, outliving the pool: an answer handed back to a loop is the loop's + // to receive until the pool has stopped, and a flow's own stop source is what each round needs. + constexpr auto Rounds = 1000; + constexpr auto Budget = std::chrono::seconds { 10 }; + + auto clock = core::platform::ManualClock {}; + auto loop = TestLoop { clock }; + auto inner = scriptedInner(); + auto pool = core::async::ThreadPoolExecutor { 2 }; + auto resolver = ExecutorAddressResolver { pool, inner }; + + auto answered = 0; + auto cancelled = 0; + for (auto const round: std::views::iota(0, Rounds)) + { + auto source = core::async::StopSource {}; + auto outcome = Outcome {}; + auto flow = resolveInto(&loop, &resolver, "db.test", &outcome); + flow.handle().promise().setStopToken(source.get_token()); + flow.handle().resume(); + + for ([[maybe_unused]] auto const spin: std::views::iota(0, round % 64)) + std::this_thread::yield(); + source.request_stop(); + + auto const deadline = std::chrono::steady_clock::now() + Budget; + while (!outcome.isFinished.load(std::memory_order_acquire) + && std::chrono::steady_clock::now() < deadline) + { + if (loop.drain() == 0) + std::this_thread::yield(); + } + REQUIRE(outcome.isFinished.load(std::memory_order_acquire)); + REQUIRE(flow.done()); + REQUIRE(outcome.answer.has_value() != outcome.isCancelled); + if (outcome.isCancelled) + ++cancelled; + else + ++answered; + + // A cancelled round's lookup may still be running; let it return before the next round. + while (resolver.inFlight() != 0 && std::chrono::steady_clock::now() < deadline) + std::this_thread::yield(); + REQUIRE(resolver.inFlight() == 0); + } + pool.stop(); + CHECK(loop.drain() == 0); + CHECK(answered + cancelled == Rounds); + CHECK(answered > 0); + CHECK(cancelled > 0); + CHECK(inner->calls() == static_cast(Rounds)); +} + +TEST_CASE("a host no name can be is refused before the inner resolver or the executor sees it", + "[net][resolver]") +{ + // An empty host would reach getaddrinfo as the wildcard address, a NUL would cut the name it + // looks up short, and more than 253 bytes is no DNS name: none of them is a lookup to run. + auto const tooLong = std::string(254, 'a'); + auto const host = GENERATE_COPY(std::string {}, std::string { "db.test\0evil", 12 }, tooLong); + auto const viaLoop = GENERATE(true, false); + CAPTURE(host.size(), viaLoop); + auto clock = core::platform::ManualClock {}; + auto loop = TestLoop { clock }; + auto blocking = ManualExecutor {}; + auto inner = scriptedInner(); + auto resolver = ExecutorAddressResolver { blocking, inner }; + + auto outcome = Outcome {}; + loop.spawn(resolveInto(viaLoop ? &loop : nullptr, &resolver, host, &outcome)); + loop.drain(); + REQUIRE(outcome.isFinished.load()); + REQUIRE(outcome.answer.has_value()); + REQUIRE_FALSE(outcome.answer->has_value()); + CHECK(outcome.answer->error().code == NetErrorCode::AddressError); + CHECK(blocking.pending() == 0); + CHECK(inner->calls() == 0); +} + +TEST_CASE("a 253-byte name is still looked up", "[net][resolver]") +{ + auto clock = core::platform::ManualClock {}; + auto loop = TestLoop { clock }; + auto blocking = ManualExecutor {}; + auto inner = scriptedInner(); + auto resolver = ExecutorAddressResolver { blocking, inner }; + + auto outcome = Outcome {}; + loop.spawn(resolveInto(nullptr, &resolver, std::string(253, 'a'), &outcome)); + loop.drain(); + REQUIRE(outcome.isFinished.load()); + CHECK(inner->calls() == 1); +} diff --git a/src/core/net/IAsyncAddressResolver.hpp b/src/core/net/IAsyncAddressResolver.hpp index b9fa162b..b4110a1f 100644 --- a/src/core/net/IAsyncAddressResolver.hpp +++ b/src/core/net/IAsyncAddressResolver.hpp @@ -44,16 +44,29 @@ using ResolveResult = std::expected, NetError>; /// @param port The port it was to be paired with. /// @param why The underlying resolver's own message. /// @return The structured error, coded @c NetErrorCode::AddressError — "address resolution or -/// parsing failed", in @c NetError.hpp's own words. Not @c NetErrorCode::AddressNotAvail, -/// which that header reserves for a BIND whose address is not local: a caller retrying a -/// DNS failure matches on this code, and one that read a lookup failure as a local bind -/// problem would stop retrying the thing that is worth retrying. +/// parsing failed", in @c NetError.hpp's own words: a failure only known in words claims +/// nothing about whether asking again helps. A resolver that knows the cause reports it +/// through the @c NetError overload below, so a caller retrying a DNS failure matches on +/// @c NetErrorCode::ResolverTemporaryFailure. Never @c NetErrorCode::AddressNotAvail, which +/// that header reserves for a BIND whose address is not local. [[nodiscard]] inline NetError resolveFailure(std::string_view host, std::uint16_t port, std::string_view why) { return makeNetError( NetErrorCode::AddressError, 0, std::format("cannot resolve {}:{}: {}", host, port, why)); } +/// Builds the error a failed classified lookup produces: @p why's code and system code, kept, with +/// its context worded as @c resolveFailure words it. +/// @param host The host that could not be resolved. +/// @param port The port it was to be paired with. +/// @param why What @c IAddressResolver::resolveClassified answered. +/// @return The same failure, its context naming what was being looked up. +[[nodiscard]] inline NetError resolveFailure(std::string_view host, std::uint16_t port, NetError why) +{ + why.context = std::format("cannot resolve {}:{}: {}", host, port, why.context); + return why; +} + /// Name resolution a coroutine can await. /// /// A seam beside @c IAddressResolver rather than a replacement for it. Binding happens once, at @@ -131,14 +144,19 @@ class InlineAddressResolver final: public IAsyncAddressResolver /// @copydoc IAsyncAddressResolver::resolve /// /// @p loop is accepted and ignored: this resolver has nothing to hand back FROM, so honouring - /// it would mean suspending for no reason. + /// it would mean suspending for no reason. A failure carries the code + /// @c IAddressResolver::resolveClassified gave it. Host text @c detail::checkLookupHost refuses + /// (empty, an embedded NUL, more than 253 bytes) is @c NetErrorCode::AddressError, and @p inner + /// is never asked, as with the threaded and the executor resolvers. [[nodiscard]] async::Task resolve(std::string host, std::uint16_t port, EventLoop* /*loop*/) override { - auto resolved = _inner.resolve(host, port); + if (auto checked = detail::checkLookupHost(host); !checked.has_value()) + co_return std::unexpected(std::move(checked.error())); + auto resolved = _inner.resolveClassified(host, port); if (!resolved.has_value()) - co_return std::unexpected(resolveFailure(host, port, resolved.error())); + co_return std::unexpected(resolveFailure(host, port, std::move(resolved.error()))); co_return std::move(*resolved); } diff --git a/src/core/net/NetError.hpp b/src/core/net/NetError.hpp index 79aeaab1..d636f8a9 100644 --- a/src/core/net/NetError.hpp +++ b/src/core/net/NetError.hpp @@ -23,31 +23,40 @@ namespace core::net /// either lineage still has a code for every failure it used to distinguish. enum class NetErrorCode : std::uint8_t { - Ok = 0, ///< No error. Not stored in an error result; it is what a `NetErrorCode` - ///< variable holds before anything has failed. - Eof, ///< The peer finished sending (it closed its write side cleanly). - Cancelled, ///< The operation was cancelled by the resource (close, cancelRead, a closed - ///< listener). A cancel from the flow's own stop token throws instead. - Timeout, ///< A deadline elapsed before the operation completed. - WouldBlock, ///< The operation would block (transient; the backend reports readiness). - BadHandle, ///< The socket, descriptor or handle is closed or invalid. - ConnReset, ///< The peer reset the connection mid-flight. - ConnRefused, ///< A connect was refused by the peer. - AddressInUse, ///< A bind failed because the endpoint is taken. - AddressNotAvail, ///< A bind failed because the address is not available locally. - AddressError, ///< Address resolution or parsing failed. - HostUnreach, ///< The network reports the destination as unreachable. - PermissionDenied, ///< The OS refused the operation (a low-numbered port without privileges, a - ///< firewall's EACCES). - Unsupported, ///< The operation is not supported on this platform or transport. - MessageTooLarge, ///< A framed unit (line, PDU, datagram) exceeded its configured bound. - SystemError, ///< An OS error nothing classified further; inspect `NetError::systemCode`. - ResourceExhausted, ///< The process or the system ran out of something the call needs: descriptors - ///< (`EMFILE`, `ENFILE`, `WSAEMFILE`), buffer space (`ENOBUFS`, `WSAENOBUFS`) - ///< or memory (`ENOMEM`). Transient where `SystemError` may be permanent: the - ///< same call can succeed once something is released, so an accept loop backs - ///< off and accepts again (`AcceptPolicy.hpp`). After `SystemError` rather - ///< than beside its neighbours so that no earlier code is renumbered. + Ok = 0, ///< No error. Not stored in an error result; it is what a `NetErrorCode` + ///< variable holds before anything has failed. + Eof, ///< The peer finished sending (it closed its write side cleanly). + Cancelled, ///< The operation was cancelled by the resource (close, cancelRead, a closed + ///< listener). A cancel from the flow's own stop token throws instead. + Timeout, ///< A deadline elapsed before the operation completed. + WouldBlock, ///< The operation would block (transient; the backend reports readiness). + BadHandle, ///< The socket, descriptor or handle is closed or invalid. + ConnReset, ///< The peer reset the connection mid-flight. + ConnRefused, ///< A connect was refused by the peer. + AddressInUse, ///< A bind failed because the endpoint is taken. + AddressNotAvail, ///< A bind failed because the address is not available locally. + AddressError, ///< Address resolution or parsing failed. For a name lookup: a permanent + ///< resolver failure (`EAI_FAIL`, WASI's `permanent-resolver-failure`), and + ///< any lookup failure nothing classified further. + HostUnreach, ///< The network reports the destination as unreachable. + PermissionDenied, ///< The OS refused the operation (a low-numbered port without privileges, a + ///< firewall's EACCES). + Unsupported, ///< The operation is not supported on this platform or transport. + MessageTooLarge, ///< A framed unit (line, PDU, datagram) exceeded its configured bound. + SystemError, ///< An OS error nothing classified further; inspect `NetError::systemCode`. + ResourceExhausted, ///< The process or the system ran out of something the call needs: descriptors + ///< (`EMFILE`, `ENFILE`, `WSAEMFILE`), buffer space (`ENOBUFS`, `WSAENOBUFS`) + ///< or memory (`ENOMEM`). Transient where `SystemError` may be permanent: the + ///< same call can succeed once something is released, so an accept loop backs + ///< off and accepts again (`AcceptPolicy.hpp`). After `SystemError` rather + ///< than beside its neighbours so that no earlier code is renumbered. + NameNotFound, ///< A name lookup answered that the name does not exist, or has no address: + ///< `EAI_NONAME`, `WSAHOST_NOT_FOUND` (WASI's `name-unresolvable`). Asking + ///< again gives the same answer. Classified by @c resolverErrorTable. + ResolverTemporaryFailure, ///< The resolver could not answer now, a name server not reachable or + ///< not responding: `EAI_AGAIN`, `WSATRY_AGAIN` (WASI's + ///< `temporary-resolver-failure`). Asking again later may succeed. A + ///< permanent resolver failure stays @c AddressError. Last, ///< Not a code: the number of codes above it, so a table or a test can cover every one of ///< them without restating the list. Never constructed, never returned, never compared @@ -91,6 +100,8 @@ enum class NetErrorCode : std::uint8_t case NetErrorCode::MessageTooLarge: return "message too large"; case NetErrorCode::SystemError: return "system error"; case NetErrorCode::ResourceExhausted: return "resource exhausted"; + case NetErrorCode::NameNotFound: return "name not found"; + case NetErrorCode::ResolverTemporaryFailure: return "resolver temporarily unavailable"; case NetErrorCode::Last: break; } return "unknown error"; diff --git a/src/core/net/NetError_test.cpp b/src/core/net/NetError_test.cpp index d4adb2ec..e2f67335 100644 --- a/src/core/net/NetError_test.cpp +++ b/src/core/net/NetError_test.cpp @@ -143,6 +143,22 @@ TEST_CASE("No code hides above Last", "[net][types]") CHECK(hiddenAt == -1); } +TEST_CASE("A lookup that found no such name is told from a resolver that could not answer", "[net][types]") +{ + // The two outcomes wasi:sockets' ip-name-lookup names `name-unresolvable` and + // `temporary-resolver-failure`: the first is the answer, the second says to ask again later, and + // a caller that receives one code for both retries a typo forever or gives up on a flaky link. + CHECK(core::net::toString(NetErrorCode::NameNotFound) == "name not found"); + CHECK(core::net::toString(NetErrorCode::ResolverTemporaryFailure) == "resolver temporarily unavailable"); + CHECK(NetErrorCode::NameNotFound != NetErrorCode::AddressError); + CHECK(NetErrorCode::ResolverTemporaryFailure != NetErrorCode::AddressError); + + // Appended, so no code a consumer has already stored or logged is renumbered. + CHECK(NetErrorCode::ResourceExhausted < NetErrorCode::NameNotFound); + CHECK(NetErrorCode::NameNotFound < NetErrorCode::ResolverTemporaryFailure); + CHECK(NetErrorCode::ResolverTemporaryFailure < NetErrorCode::Last); +} + TEST_CASE("A value outside the enumeration is described as unknown", "[net][types]") { CHECK(core::net::toString(static_cast(0xFF)) == "unknown error"); diff --git a/src/core/net/SocketAddress.cpp b/src/core/net/SocketAddress.cpp index 58f6c63b..960fa754 100644 --- a/src/core/net/SocketAddress.cpp +++ b/src/core/net/SocketAddress.cpp @@ -20,10 +20,9 @@ #include #include -#include #include #include -#include +#include #include namespace core::net @@ -49,6 +48,14 @@ namespace std::expected, std::string> SystemAddressResolver::resolve( std::string_view host, std::uint16_t port) +{ + return resolveClassified(host, port).transform_error([](NetError error) { + return std::move(error.context); + }); +} + +std::expected, NetError> SystemAddressResolver::resolveClassified( + std::string_view host, std::uint16_t port) { platform::ensureWinsockInitialized(); @@ -67,7 +74,14 @@ std::expected, std::string> SystemAddressResolver: addrinfo* head = nullptr; if (auto const rc = ::getaddrinfo(node, service.c_str(), &hints, &head); rc != 0) - return std::unexpected(std::format("cannot resolve '{}': {}", host, resolverMessage(rc))); + { + // The system code first: on POSIX it is errno for EAI_SYSTEM, which formatting may change. + auto const systemCode = detail::resolverSystemCode(rc); + return std::unexpected( + makeNetError(detail::classifyResolverError(rc), + systemCode, + std::format("cannot resolve '{}': {}", host, resolverMessage(rc)))); + } auto endpoints = std::vector {}; auto const* next = head; @@ -89,7 +103,8 @@ std::expected, std::string> SystemAddressResolver: ::freeaddrinfo(head); if (endpoints.empty()) - return std::unexpected(std::format("cannot resolve '{}': no usable address", host)); + return std::unexpected(makeNetError( + NetErrorCode::AddressError, 0, std::format("cannot resolve '{}': no usable address", host))); return endpoints; } @@ -114,21 +129,71 @@ std::string formatPeerAddress(ResolvedEndpoint const& endpoint) namespace detail { - bool isNumericHost(std::string_view host) noexcept + std::expected checkLookupHost(std::string_view host) { if (host.empty()) - return false; + return std::unexpected( + makeNetError(NetErrorCode::AddressError, 0, "an empty host names no host to look up")); + if (host.contains('\0')) + return std::unexpected( + makeNetError(NetErrorCode::AddressError, 0, "a host with an embedded NUL is no name")); + if (host.size() > MaxLookupHostLength) + return std::unexpected(makeNetError( + NetErrorCode::AddressError, + 0, + std::format( + "a host of {} bytes is longer than a DNS name's {}", host.size(), MaxLookupHostLength))); + return {}; + } + + bool isNumericHost(std::string_view host) noexcept + { + return endpointOfLiteral(host, 0).has_value(); + } + + std::optional endpointOfLiteral(std::string_view host, std::uint16_t port) noexcept + { + // An embedded NUL would end the text inet_pton reads early, and "127.0.0.1\0evil" would + // parse as the address before it. + if (host.empty() || host.contains('\0')) + return std::nullopt; + + // A scoped literal (`fe80::1%eth0`) is a name here on every platform, never a literal: macOS's + // inet_pton accepts the zone and drops it, so the endpoint would lose the scope a link-local + // dial needs. getaddrinfo keeps it, so such a host goes to the resolver everywhere. + if (host.contains('%')) + return std::nullopt; // inet_pton needs a NUL-terminated string, and a host is short. auto const text = std::string { host }; - // The two families in a table rather than two ifs, so a third — there is none today — - // would be a row. The scratch is sized for the larger of the two. - constexpr auto Families = std::array { AF_INET, AF_INET6 }; - auto scratch = std::array {}; - return std::ranges::any_of(Families, [&](int family) noexcept { - return ::inet_pton(family, text.c_str(), scratch.data()) == 1; - }); + auto v4 = sockaddr_in {}; + if (::inet_pton(AF_INET, text.c_str(), &v4.sin_addr) == 1) + { + v4.sin_family = AF_INET; + v4.sin_port = htons(port); + auto endpoint = endpointFromSockaddr(&v4, sizeof(v4)); + endpoint.protocol = IPPROTO_TCP; + return endpoint; + } + + auto v6 = sockaddr_in6 {}; + if (::inet_pton(AF_INET6, text.c_str(), &v6.sin6_addr) == 1) + { + v6.sin6_family = AF_INET6; + v6.sin6_port = htons(port); + auto endpoint = endpointFromSockaddr(&v6, sizeof(v6)); + endpoint.protocol = IPPROTO_TCP; + return endpoint; + } + return std::nullopt; + } + + NetErrorCode classifyResolverError(int gaiCode) noexcept + { + auto const table = resolverErrorTable(); + auto const row = std::ranges::find(table, gaiCode, &ResolverErrorRow::gaiCode); + return row != table.end() ? row->code : NetErrorCode::AddressError; } ResolvedEndpoint endpointFromSockaddr(void const* sockaddr, std::uint32_t length) noexcept diff --git a/src/core/net/SocketAddress.hpp b/src/core/net/SocketAddress.hpp index a25ae49d..88b8cebc 100644 --- a/src/core/net/SocketAddress.hpp +++ b/src/core/net/SocketAddress.hpp @@ -14,14 +14,18 @@ /// own their bind sequence, so `BindAndListen`, `BoundPortOf` and `ReusePort` are deliberately /// not here. +#include #include #include #include #include #include +#include +#include #include #include +#include #include namespace core::net @@ -71,6 +75,27 @@ class IAddressResolver /// @return A non-empty list of candidates, or a message saying why there are none. [[nodiscard]] virtual std::expected, std::string> resolve( std::string_view host, std::uint16_t port) = 0; + + /// Resolves @p host : @p port as @c resolve does, and says WHICH failure a failure is. + /// + /// What the asynchronous resolvers call, so a name that does not exist + /// (@c NetErrorCode::NameNotFound) reaches their caller apart from a resolver that could not + /// answer now (@c NetErrorCode::ResolverTemporaryFailure). + /// + /// **The default knows only words**, and classifies nothing: it wraps @c resolve's message into + /// @c NetErrorCode::AddressError, the code that claims nothing about whether asking again could + /// help, with the message as the error's context. A resolver that knows the cause overrides it, + /// as @c SystemAddressResolver does through @c resolverErrorTable. + /// @param host As for @c resolve. + /// @param port As for @c resolve. + /// @return A non-empty list of candidates, or the classified failure. + [[nodiscard]] virtual std::expected, NetError> resolveClassified( + std::string_view host, std::uint16_t port) + { + return resolve(host, port).transform_error([](std::string message) { + return makeNetError(NetErrorCode::AddressError, 0, std::move(message)); + }); + } }; /// The `getaddrinfo`-backed resolver: the one place in this library that issues the lookup. @@ -78,10 +103,35 @@ class CORE_NET_API SystemAddressResolver final: public IAddressResolver { public: /// @copydoc IAddressResolver::resolve + /// + /// The message is the context of what @c resolveClassified reports. [[nodiscard]] std::expected, std::string> resolve( std::string_view host, std::uint16_t port) override; + + /// @copydoc IAddressResolver::resolveClassified + /// + /// Classified by @c resolverErrorTable. A lookup that succeeded with no address this library + /// can carry is @c NetErrorCode::AddressError. + [[nodiscard]] std::expected, NetError> resolveClassified( + std::string_view host, std::uint16_t port) override; }; +/// One row of @c resolverErrorTable: a code `getaddrinfo` returns, and its category. +struct ResolverErrorRow +{ + int gaiCode; ///< The platform's code: an `EAI_*` value on POSIX, a `WSA*` value on Windows. + NetErrorCode code; ///< What a caller is told. +}; + +/// Every code this platform's `getaddrinfo` can return, classified: one table per OS, in +/// `posix/SocketsPosix.cpp` and `windows/SocketsWin32.cpp`. +/// +/// A code no row names is @c NetErrorCode::AddressError (@c detail::classifyResolverError). Each +/// platform's test asserts the table complete -- POSIX by asking `gai_strerror` which codes its libc +/// knows -- so a new code is a failing case until its row is a decision. +/// @return The table; each code appears once. +[[nodiscard]] CORE_NET_API std::span resolverErrorTable() noexcept; + /// @return The process-wide @c SystemAddressResolver, for a caller with no resolver of its own. /// /// An ambient resource with a name, in the shape this tree already uses for @@ -107,16 +157,57 @@ namespace detail /// resolver thread, and what lets the whole connect path be tested with no thread existing. /// /// Answered with `inet_pton` for both families rather than by inspecting the characters, so - /// there is one definition of "literal" and it is the platform's own. Which means a **scoped** - /// literal (`fe80::1%eth0`) is platform-dependent, and that is fine: glibc's `inet_pton` - /// rejects the zone suffix and macOS's accepts it, so the same text is a name on one host and - /// a literal on the next, and either answer produces a working dial. What must never happen is - /// the other direction — a NAME reported as a literal would be handed to `::connect` as an - /// address and could not resolve at all. + /// there is one definition of "literal" and it is the platform's own -- with one exception: a + /// **scoped** literal (`fe80::1%eth0`) is a name on every platform. macOS's `inet_pton` accepts + /// the zone and drops it, so treating it as a literal there would lose the scope a link-local + /// dial needs; `getaddrinfo` keeps it. What must never happen is a NAME reported as a literal: + /// it would be handed to `::connect` as an address and could not resolve at all. /// @param host Host text, unbracketed. /// @return True when @p host parses as an IPv4 or IPv6 literal. [[nodiscard]] CORE_NET_API bool isNumericHost(std::string_view host) noexcept; + /// Parses a literal address into the endpoint a lookup of it would produce, with no lookup. + /// + /// The same parse as @c isNumericHost, so the two never disagree about what a literal is. Text + /// with an IPv6 zone suffix (`%eth0`) is no literal on any platform, so its scope reaches + /// `getaddrinfo` instead of being dropped. Only the strict forms are literals: a dotted quad, or IPv6 + /// text (an IPv4-mapped `::ffff:1.2.3.4` included). The shorthand `127.1` that `getaddrinfo` also accepts + /// is not one; it is a name, and a resolver looks it up -- which `getaddrinfo` then answers as + /// `127.0.0.1`. Text with a port, brackets or an embedded NUL is no literal. + /// @param host Host text, unbracketed. + /// @param port The port to carry, in host byte order. + /// @return A `sockaddr_in` or `sockaddr_in6` endpoint whose protocol is TCP, or nothing when + /// @p host is not a literal. + [[nodiscard]] CORE_NET_API std::optional endpointOfLiteral(std::string_view host, + std::uint16_t port) noexcept; + + /// The longest host text an asynchronous resolver looks up: a DNS name's 253 bytes. + constexpr auto MaxLookupHostLength = std::size_t { 253 }; + + /// Refuses host text that names no host before any resolver sees it. + /// + /// Empty text reaches `getaddrinfo` as the wildcard address rather than a name, an embedded NUL + /// cuts the C string it reads short (`a.test\0b.test` would look up `a.test`), and more than + /// @c MaxLookupHostLength bytes is no DNS name. The asynchronous resolvers ask this first, so none + /// of the three takes a slot, a thread, or a lookup; @c bind keeps its passive wildcard. + /// @param host Host text, unbracketed. + /// @return Nothing, or @c NetErrorCode::AddressError naming which rule @p host broke. + [[nodiscard]] CORE_NET_API std::expected checkLookupHost(std::string_view host); + + /// @param gaiCode A failure code `getaddrinfo` returned. + /// @return Its row's category in @c resolverErrorTable, or @c NetErrorCode::AddressError -- the + /// documented catch-all, a permanent resolver failure -- for a code no row names. + [[nodiscard]] CORE_NET_API NetErrorCode classifyResolverError(int gaiCode) noexcept; + + /// The OS error number behind a `getaddrinfo` failure, for @c NetError::systemCode. + /// + /// Per platform, beside its table: on POSIX only `EAI_SYSTEM` has one (it is `errno`, so call + /// this before anything else can change it), and every other code is 0; on Windows the code is + /// itself the `WSAGetLastError` value. + /// @param gaiCode A failure code `getaddrinfo` returned. + /// @return The OS error number, or 0. + [[nodiscard]] CORE_NET_API int resolverSystemCode(int gaiCode) noexcept; + /// Copies a raw sockaddr into a platform-free @c ResolvedEndpoint, reading the family from /// the sockaddr itself. /// @param sockaddr Pointer to a `sockaddr` / `sockaddr_in` / `sockaddr_in6`. diff --git a/src/core/net/SocketAddress_test.cpp b/src/core/net/SocketAddress_test.cpp index fd24cdc8..5b5e1373 100644 --- a/src/core/net/SocketAddress_test.cpp +++ b/src/core/net/SocketAddress_test.cpp @@ -1,11 +1,16 @@ // SPDX-License-Identifier: Apache-2.0 +#include +#include #include +#include #include +#include #include #include #include +#include #include #include @@ -42,9 +47,8 @@ namespace TEST_CASE("a literal is told from a name by the platform's own parser", "[net]") { // The half that is pinned STRICTLY is "a name is never reported as a literal": such a host - // would be handed straight to ::connect as an address and could not resolve at all. The - // other direction is deliberately loose — a scoped literal (`fe80::1%eth0`) is a literal on - // macOS and a name on glibc, and both answers produce a working dial. + // would be handed straight to ::connect as an address and could not resolve at all. A scoped + // literal (`fe80::1%eth0`) is a name everywhere, so its zone reaches getaddrinfo. CHECK(core::net::detail::isNumericHost("127.0.0.1")); CHECK(core::net::detail::isNumericHost("0.0.0.0")); CHECK(core::net::detail::isNumericHost("::1")); @@ -114,3 +118,99 @@ TEST_CASE("the system resolver reports why a host produced nothing", "[net]") } CHECK(resolved.error().contains("core-cpp-b8.invalid")); } + +TEST_CASE("a literal becomes the endpoint a dial reads, port included", "[net]") +{ + auto const v4 = core::net::detail::endpointOfLiteral("192.0.2.7", 8080); + REQUIRE(v4.has_value()); + CHECK(v4->family == AF_INET); + CHECK(v4->length == sizeof(sockaddr_in)); + CHECK(v4->protocol == IPPROTO_TCP); + CHECK(core::net::formatPeerAddress(*v4) == "192.0.2.7"); + CHECK(core::net::detail::portOfSockaddr(v4->storage.data(), v4->length) == 8080); + + auto const v6 = core::net::detail::endpointOfLiteral("2001:db8::1", 53); + REQUIRE(v6.has_value()); + CHECK(v6->family == AF_INET6); + CHECK(v6->length == sizeof(sockaddr_in6)); + CHECK(core::net::formatPeerAddress(*v6) == "2001:db8::1"); + CHECK(core::net::detail::portOfSockaddr(v6->storage.data(), v6->length) == 53); + + // Exactly the texts isNumericHost refuses: one definition of "literal", the platform's. + CHECK_FALSE(core::net::detail::endpointOfLiteral("", 1).has_value()); + CHECK_FALSE(core::net::detail::endpointOfLiteral("localhost", 1).has_value()); + CHECK_FALSE(core::net::detail::endpointOfLiteral("[::1]", 1).has_value()); + CHECK_FALSE(core::net::detail::endpointOfLiteral("1.2.3.4:80", 1).has_value()); + CHECK_FALSE(core::net::detail::endpointOfLiteral(std::string_view { "127.0.0.1\0x", 11 }, 1).has_value()); + + // The shorthand getaddrinfo expands is not a literal: it is looked up, never parsed here. + CHECK_FALSE(core::net::detail::endpointOfLiteral("127.1", 1).has_value()); + + // An IPv4-mapped IPv6 address is IPv6 text, and stays an IPv6 endpoint. + auto const mapped = core::net::detail::endpointOfLiteral("::ffff:1.2.3.4", 7); + REQUIRE(mapped.has_value()); + CHECK(mapped->family == AF_INET6); + CHECK(core::net::detail::portOfSockaddr(mapped->storage.data(), mapped->length) == 7); + + // A zone suffix makes the text a name on every platform, whatever the platform's inet_pton + // would accept: a literal parse would drop the scope (macOS), and getaddrinfo keeps it. + CHECK_FALSE(core::net::detail::endpointOfLiteral("fe80::1%lo", 80).has_value()); + CHECK_FALSE(core::net::detail::endpointOfLiteral("fe80::1%eth0", 1).has_value()); + CHECK_FALSE(core::net::detail::isNumericHost("fe80::1%lo")); +} + +TEST_CASE("every resolver table row names a real failure, once", "[net][errors]") +{ + // A code with two rows answers whichever the walk meets first, and a row that says Ok reports a + // failed lookup as a success: both are a table edit away, and nothing else would notice. + auto const table = core::net::resolverErrorTable(); + REQUIRE_FALSE(table.empty()); + auto seen = std::set {}; + for (auto const& row: table) + { + INFO("resolver code " << row.gaiCode); + CHECK(seen.insert(row.gaiCode).second); + CHECK(row.code != core::net::NetErrorCode::Ok); + CHECK(row.code < core::net::NetErrorCode::Last); + CHECK(core::net::detail::classifyResolverError(row.gaiCode) == row.code); + } +} + +TEST_CASE("a resolver code no row names is a permanent resolver failure", "[net][errors]") +{ + // The documented catch-all: AddressError claims nothing about whether asking again helps, which + // is all that can be said of a code nobody classified. Never Ok, never a guess. + constexpr auto Unlisted = 987654; + REQUIRE(std::ranges::none_of(core::net::resolverErrorTable(), + [](auto const& row) { return row.gaiCode == Unlisted; })); + CHECK(core::net::detail::classifyResolverError(Unlisted) == core::net::NetErrorCode::AddressError); +} + +TEST_CASE("the system resolver classifies a name that does not exist", "[net]") +{ + auto resolver = core::net::SystemAddressResolver {}; + auto const resolved = resolver.resolveClassified("core-cpp-p13.invalid", 80); + if (resolved.has_value()) + SKIP("this host's resolver answers for RFC 2606 .invalid names, so a failure cannot be provoked"); + if (resolved.error().code == core::net::NetErrorCode::ResolverTemporaryFailure) + SKIP("this host has no reachable name server, so the lookup could not be answered either way"); + CHECK(resolved.error().code == core::net::NetErrorCode::NameNotFound); + CHECK(resolved.error().context.contains("core-cpp-p13.invalid")); +} + +TEST_CASE("a listener bound to a name that does not exist says so", "[net]") +{ + // The listeners resolve their bind address themselves; their failure goes through the same table + // as a dial's, rather than reporting a raw resolver code as if it were an OS error number. + auto backend = core::net::makeBackend(core::net::preferredBackendKind()); + REQUIRE(backend != nullptr); + auto loop = core::net::EventLoop { *backend }; + auto const listener = + core::net::listen(loop, core::net::ListenOptions { .host = "core-cpp-p13.invalid" }); + if (listener.has_value()) + SKIP("this host's resolver answers for RFC 2606 .invalid names, so a failure cannot be provoked"); + if (listener.error().code == core::net::NetErrorCode::ResolverTemporaryFailure) + SKIP("this host has no reachable name server, so the lookup could not be answered either way"); + CHECK(listener.error().code == core::net::NetErrorCode::NameNotFound); + CHECK(listener.error().context == "getaddrinfo"); +} diff --git a/src/core/net/Sockets.cpp b/src/core/net/Sockets.cpp index 9d939cd2..38714666 100644 --- a/src/core/net/Sockets.cpp +++ b/src/core/net/Sockets.cpp @@ -20,7 +20,9 @@ namespace core::net /// network. What changed is whose thread pays for the lookup, and three things a caller can see, /// each recorded under Breaking in the CHANGELOG: the host is a `std::string` rather than a /// `string_view`, a stop of the flow's own token throws rather than returning -/// @c NetErrorCode::Cancelled, and an unresolvable name is @c NetErrorCode::AddressError. +/// @c NetErrorCode::Cancelled, and an unresolvable name is a lookup error: since 0.24.0 +/// @c NetErrorCode::NameNotFound or @c NetErrorCode::ResolverTemporaryFailure where the resolver +/// says which, otherwise @c NetErrorCode::AddressError. /// /// The connector is built per call rather than kept, and that is cheap by construction: it holds /// two references and allocates nothing else. Keeping one would mean caching it per loop, which diff --git a/src/core/net/Sockets.hpp b/src/core/net/Sockets.hpp index 27d292b4..b1efce48 100644 --- a/src/core/net/Sockets.hpp +++ b/src/core/net/Sockets.hpp @@ -142,7 +142,9 @@ struct ListenOptions /// then. `connect(loop, makeHost(), port)` is the ordinary call that would dangle. /// @param port The remote port. /// @return A task resolving to the connected socket, or a @c NetError on failure: a name that -/// cannot be resolved is @c NetErrorCode::AddressError. +/// does not exist is @c NetErrorCode::NameNotFound, a resolver that could not answer +/// @c NetErrorCode::ResolverTemporaryFailure, and any other lookup failure +/// @c NetErrorCode::AddressError. /// @throws async::OperationCancelled if the awaiting flow is stopped while the dial is outstanding. [[nodiscard]] CORE_NET_API async::Task connect(EventLoop* loop, std::string host, diff --git a/src/core/net/ThreadedAddressResolver.cpp b/src/core/net/ThreadedAddressResolver.cpp index 78575ab5..4b44fdc3 100644 --- a/src/core/net/ThreadedAddressResolver.cpp +++ b/src/core/net/ThreadedAddressResolver.cpp @@ -1,20 +1,15 @@ // SPDX-License-Identifier: Apache-2.0 #include -#include -#include -#include -#include #include +#include #include #include -#include #include #include #include #include -#include #include #include #include @@ -27,165 +22,7 @@ namespace { /// One lookup's rendezvous between a worker thread and the parked coroutine. - /// - /// Shared, because either side may reach it last: the worker must be able to publish into it - /// after the task was abandoned, and the task must be able to read it after the worker is - /// gone. - /// - /// **Whoever takes @c waiter first decides the outcome**, and the other finds it empty. The - /// worker takes it to deliver an answer (@c done), a stop takes it to deliver a cancellation - /// (@c cancelled), and both do so under @c mutex — so exactly one of them hands the coroutine - /// back, and the loser's news goes nowhere. That is what makes an answer arriving after a - /// stop harmless: the frame it would have been delivered into may already be gone. - struct ResolveSlot - { - std::mutex mutex; - ResolveResult result { std::vector {} }; - async::ParkedWork waiter {}; - bool done = false; - bool cancelled = false; - }; - - /// Hands @p waiter back to @p loop, or frees it where there is nowhere to hand it. - /// - /// An `async::detail::Parked` rather than a bare `ParkedWork`, so the branch that hands - /// nothing on FREES an unowned chain instead of dropping it. That is `ParkedWork`'s contract — - /// resumed or freed, never neither. Nothing changes for a BORROWED handle: the claim is empty, - /// so the guard destroys nothing and the caller's owner still frees it. - /// @param waiter What was taken out of the slot; may be empty. - /// @param loop Where to hand it back, or null. - void handBack(async::detail::Parked waiter, EventLoop* loop) - { - if (waiter.handle() && loop != nullptr) - loop->submit(waiter.take()); - } - - /// Publishes a result and hands the waiter back to its loop. - /// - /// **It never calls `resume()`.** The consumer must continue on the loop's thread and not on - /// whichever worker happened to finish the lookup — that is the entire point of the hand-back, - /// and resuming here would run the caller's continuation on a resolver thread, which is the - /// stall this class exists to remove wearing a different hat. - /// @param slot The rendezvous to fill. - /// @param loop Where to hand the waiter back, or null when there is nowhere. - /// @param result What the lookup produced. - void settle(ResolveSlot& slot, EventLoop* loop, ResolveResult result) - { - auto waiter = async::detail::Parked {}; - { - auto const guard = std::scoped_lock { slot.mutex }; - slot.result = std::move(result); - slot.done = true; - waiter = async::detail::Parked { std::exchange(slot.waiter, async::ParkedWork {}) }; - } - handBack(std::move(waiter), loop); - } - - /// The stop callback of a parked lookup: takes the waiter back from the worker and hands it - /// to the loop, cancelled. - /// - /// **It may run on any thread** — the loop's, a whenAny sibling's, a watchdog's — so it does - /// what @c settle does and nothing more: it takes the waiter under the slot's lock and - /// SUBMITS it. It never resumes, for @c settle's reason: the flow continues on the loop's - /// thread and on no other. - /// - /// A named functor holding two plain pointers rather than a `std::function`, so registering - /// the callback allocates nothing. The slot outlives it: the awaiter that owns this callback - /// also holds the slot's `shared_ptr`, and drops the callback first. - struct CancelLookup - { - ResolveSlot* slot = nullptr; - EventLoop* loop = nullptr; - - void operator()() const - { - auto waiter = async::detail::Parked {}; - { - auto const guard = std::scoped_lock { slot->mutex }; - // An answer that got here first is delivered, and a stop after it changes nothing: - // the flow is already on its way back with a result it can use. - if (slot->done) - return; - slot->cancelled = true; - waiter = async::detail::Parked { std::exchange(slot->waiter, async::ParkedWork {}) }; - } - handBack(std::move(waiter), loop); - } - }; - - /// Suspends until a slot is filled, or until the awaiting flow is stopped. - /// - /// Race-free the way @c ResultAwaitable is: the completion check and the waiter registration - /// happen under one lock, so a result landing between them resumes through the normal path - /// rather than parking on an answer that has already arrived. - /// - /// **Stop-aware, because @c IAsyncAddressResolver says a suspending resolver must be.** The - /// lookup itself cannot be interrupted — `getaddrinfo` has no cancellation — but the WAIT for - /// it can, and that wait is what a dial's budget, a `whenAny` and a loop's shutdown all need - /// to end. On a stop the flow is handed back cancelled and throws; the worker finishes in its - /// own time and publishes into a slot nobody is waiting on. - struct SlotPark - { - std::shared_ptr slot; - EventLoop* loop = nullptr; - std::optional> cancelReg {}; - - /// @return False. Whether the answer is already there is @c await_suspend's first question, - /// asked under the slot's mutex: taking a lock is a call, and MSVC 19.44's ARM64 - /// code generator drops the enclosing `try` of a `co_await` on a temporary awaiter - /// whose `await_ready` makes one (fastcached#1546, `.agent/rules/async-and-net.md`). - [[nodiscard]] constexpr bool await_ready() const noexcept { return false; } - - /// Templated on the promise so `parkedWorkFor` can ask the PARKING coroutine's own - /// promise whether anything else owns its chain: @c settle hands this chain to a loop - /// that may be destroyed before it runs it, and by then the handle is erased, so this is - /// the last place the question can be asked. The same promise is where the flow's stop - /// token is read. - /// - /// **An answer already there resumes at once, before the stop callback exists**, which is - /// what `await_ready` answered when it held that check: a stop that has already fired - /// cannot then turn a finished lookup into a cancellation. - /// - /// **The stop callback is registered BEFORE the waiter is published.** A stop landing in - /// between then finds no waiter, records @c ResolveSlot::cancelled, and the check below - /// sees it and does not park; registered after, a stop that had already fired would run - /// the callback inline, find the waiter, and hand it to the loop while this function is - /// still deciding whether to suspend — the same frame queued and returned-into at once. - /// @tparam Promise The suspending coroutine's promise type. - /// @param handle The suspended lookup. - /// @return True to stay suspended; false when the answer or the stop arrived first. - template - [[nodiscard]] bool await_suspend(std::coroutine_handle handle) - { - { - auto const guard = std::scoped_lock { slot->mutex }; - if (slot->done) - return false; - } - if constexpr (async::HasStopToken) - cancelReg.emplace(handle.promise().stopToken(), - CancelLookup { .slot = slot.get(), .loop = loop }); - - auto const guard = std::scoped_lock { slot->mutex }; - if (slot->done || slot->cancelled) - return false; - slot->waiter = async::detail::parkedWorkFor(handle); - return true; - } - - /// @return The lookup's answer. - /// @throws async::OperationCancelled if the flow was stopped before the answer arrived. - [[nodiscard]] ResolveResult await_resume() - { - // Dropped first: it waits for a callback running on another thread to finish, so the - // slot is not read while that callback is still writing it. - cancelReg.reset(); - auto const guard = std::scoped_lock { slot->mutex }; - if (slot->cancelled) - throw async::OperationCancelled {}; - return slot->result; - } - }; + using ResolveCall = detail::ParkedCall; } // namespace @@ -202,8 +39,7 @@ struct ThreadedAddressResolver::Impl /// One queued lookup. struct Job { - std::shared_ptr slot; - EventLoop* loop = nullptr; + std::shared_ptr call; std::string host; std::uint16_t port = 0; }; @@ -231,13 +67,12 @@ struct ThreadedAddressResolver::Impl queue.pop_front(); } - auto resolved = inner.resolve(job.host, job.port); + auto resolved = inner.resolveClassified(job.host, job.port); if (resolved.has_value()) - settle(*job.slot, job.loop, std::move(*resolved)); + job.call->settle(std::move(*resolved)); else - settle(*job.slot, - job.loop, - std::unexpected(resolveFailure(job.host, job.port, resolved.error()))); + job.call->settle( + std::unexpected(resolveFailure(job.host, job.port, std::move(resolved.error())))); } } @@ -302,10 +137,8 @@ void ThreadedAddressResolver::stop() noexcept // Every queued lookup is resumed rather than dropped, so no coroutine is left parked on an // answer that will never come. for (auto& job: abandoned) - settle(*job.slot, - job.loop, - std::unexpected( - makeNetError(NetErrorCode::Cancelled, 0, "the resolver stopped before the lookup ran"))); + job.call->settle(std::unexpected( + makeNetError(NetErrorCode::Cancelled, 0, "the resolver stopped before the lookup ran"))); _impl->joinWorkers(); } @@ -314,6 +147,9 @@ async::Task ThreadedAddressResolver::resolve(std::string host, std::uint16_t port, EventLoop* loop) { + if (auto checked = detail::checkLookupHost(host); !checked.has_value()) + co_return std::unexpected(std::move(checked.error())); + // A literal needs no lookup, so it needs no thread. See the class comment: here that is the // common case, not the exotic one. // @@ -322,13 +158,13 @@ async::Task ThreadedAddressResolver::resolve(std::string host, // resume. if (loop == nullptr || detail::isNumericHost(host)) { - auto resolved = _impl->inner.resolve(host, port); + auto resolved = _impl->inner.resolveClassified(host, port); if (!resolved.has_value()) - co_return std::unexpected(resolveFailure(host, port, resolved.error())); + co_return std::unexpected(resolveFailure(host, port, std::move(resolved.error()))); co_return std::move(*resolved); } - auto slot = std::make_shared(); + auto call = std::make_shared(loop); { auto const guard = std::scoped_lock { _impl->mutex }; if (_impl->stopping) @@ -338,7 +174,7 @@ async::Task ThreadedAddressResolver::resolve(std::string host, { _impl->refusedCount.fetch_add(1, std::memory_order_relaxed); co_return std::unexpected( - makeNetError(NetErrorCode::WouldBlock, + makeNetError(NetErrorCode::ResourceExhausted, 0, std::format("the resolver queue is full ({} waiting); not resolving {}:{}", _impl->queue.size(), @@ -347,13 +183,12 @@ async::Task ThreadedAddressResolver::resolve(std::string host, } _impl->ensureStarted(); - _impl->queue.push_back( - Impl::Job { .slot = slot, .loop = loop, .host = std::move(host), .port = port }); + _impl->queue.push_back(Impl::Job { .call = call, .host = std::move(host), .port = port }); _impl->offloadedCount.fetch_add(1, std::memory_order_relaxed); } _impl->wake.notify_one(); - co_return co_await SlotPark { .slot = std::move(slot), .loop = loop }; + co_return co_await ResolveCall::wait(std::move(call)); } ThreadedAddressResolver& defaultAsyncResolver() diff --git a/src/core/net/ThreadedAddressResolver.hpp b/src/core/net/ThreadedAddressResolver.hpp index 0fc50928..6a2bf945 100644 --- a/src/core/net/ThreadedAddressResolver.hpp +++ b/src/core/net/ThreadedAddressResolver.hpp @@ -59,9 +59,10 @@ struct ThreadedResolverOptions /// /// An unbounded queue is a memory-exhaustion hole reachable by whatever provokes dials. And /// blocking the caller to wait for room would reintroduce, on the loop thread, precisely the -/// stall this class exists to remove — so over-depth returns @c NetErrorCode::WouldBlock -/// immediately. `WouldBlock` and not `SystemError`, because a caller can retry the first and can -/// do nothing at all with the second. +/// stall this class exists to remove — so over-depth returns @c NetErrorCode::ResourceExhausted +/// immediately. Not `SystemError`, because a caller can retry once a lookup has returned and can +/// do nothing at all with the second; and not `WouldBlock`, which @c isDeadlineExpiry reads as a +/// deadline's tick. class CORE_NET_API ThreadedAddressResolver final: public IAsyncAddressResolver { public: @@ -84,6 +85,11 @@ class CORE_NET_API ThreadedAddressResolver final: public IAsyncAddressResolver /// to @p loop cancelled at once, and the worker, which cannot be interrupted inside the /// blocking resolver, finishes in its own time and publishes into a slot nobody waits on. /// The lookup still occupies its thread until then — a stop ends the WAIT, not the lookup. + /// + /// A failure carries the code @c IAddressResolver::resolveClassified gave it, so a name that does + /// not exist and a resolver that could not answer reach the caller apart. + /// Host text @c detail::checkLookupHost refuses (empty, an embedded NUL, more than 253 bytes) is + /// @c NetErrorCode::AddressError before any lookup starts, whatever @p loop is. [[nodiscard]] async::Task resolve(std::string host, std::uint16_t port, EventLoop* loop) override; diff --git a/src/core/net/ThreadedAddressResolver_test.cpp b/src/core/net/ThreadedAddressResolver_test.cpp index c5589ed7..753f998e 100644 --- a/src/core/net/ThreadedAddressResolver_test.cpp +++ b/src/core/net/ThreadedAddressResolver_test.cpp @@ -2,24 +2,24 @@ #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 @@ -29,83 +29,23 @@ using core::net::EventLoop; using core::net::ResolvedEndpoint; using core::net::ResolveResult; using core::net::ThreadedAddressResolver; +using core::net::testing::ScriptedAddressResolver; namespace { -/// A blocking resolver with no DNS behind it: it answers from a script and records who asked. +/// How long a case waits for a held lookup to reach the resolver before it gives up. +constexpr auto EnterBudget = std::chrono::seconds { 10 }; + +/// Scripts @p inner to answer `example.test`; any other name is not found. /// /// The whole point of the seam is that a test can say what resolution costs and observe which /// thread paid for it, so every property below is provable without a name server anywhere. -class ScriptedResolver final: public core::net::IAddressResolver +/// @param inner The resolver to script. +void scriptExample(ScriptedAddressResolver& inner) { - public: - [[nodiscard]] std::expected, std::string> resolve( - std::string_view host, std::uint16_t /*port*/) override - { - { - auto const guard = std::scoped_lock { _mutex }; - _callers.push_back(std::this_thread::get_id()); - ++_calls; - } - _entered.notify_all(); - - // Held here until a case releases it, so "the queue is full" and "a lookup is still in - // flight" are arranged states rather than races. - auto lock = std::unique_lock { _mutex }; - _release.wait(lock, [this] { return !_hold; }); - lock.unlock(); - - if (host == "unresolvable.invalid") - return std::unexpected(std::string { "scripted failure" }); - return std::vector { ResolvedEndpoint { - .length = 16, .family = 2, .protocol = 6 } }; - } - - /// Makes every later lookup block inside @c resolve until @c release is called. - void hold() noexcept - { - auto const guard = std::scoped_lock { _mutex }; - _hold = true; - } - - void release() noexcept - { - { - auto const guard = std::scoped_lock { _mutex }; - _hold = false; - } - _release.notify_all(); - } - - /// Blocks until @p count lookups have entered @c resolve. - void awaitEntered(std::size_t count) - { - auto lock = std::unique_lock { _mutex }; - _entered.wait(lock, [&] { return _calls >= count; }); - } - - [[nodiscard]] std::size_t calls() const - { - auto const guard = std::scoped_lock { _mutex }; - return _calls; - } - - /// @return The thread each lookup ran on, in call order. - [[nodiscard]] std::vector callers() const - { - auto const guard = std::scoped_lock { _mutex }; - return _callers; - } - - private: - mutable std::mutex _mutex; - std::condition_variable _release; - std::condition_variable _entered; - std::vector _callers; - std::size_t _calls = 0; - bool _hold = false; -}; + inner.answer("example.test", { ResolvedEndpoint { .length = 16, .family = 2, .protocol = 6 } }); +} /// Resolves through @p resolver on @p loop and records what came back. Task resolveOn(EventLoop* loop, @@ -143,7 +83,8 @@ TEST_CASE("a literal never reaches the resolver pool", "[net]") // to a literal, and paying a thread hand-off plus two context switches for `inet_pton` would // be a real regression on the hot path. It is also what lets the whole connect path be // exercised with no thread existing at all. - auto inner = ScriptedResolver {}; + auto inner = ScriptedAddressResolver {}; + scriptExample(inner); auto resolver = ThreadedAddressResolver { inner }; auto clock = core::platform::ManualClock {}; @@ -165,7 +106,8 @@ TEST_CASE("a name is resolved on another thread and resumes on the loop's", "[ne // The property the whole task exists for, asserted at the seam rather than through a dial: // the lookup runs somewhere that is NOT the thread driving the loop, and the coroutine that // asked for it continues where it was — on the loop. - auto inner = ScriptedResolver {}; + auto inner = ScriptedAddressResolver {}; + scriptExample(inner); auto resolver = ThreadedAddressResolver { inner }; auto backend = core::net::makeBackend(core::net::preferredBackendKind()); @@ -187,7 +129,8 @@ TEST_CASE("a null loop resolves inline, because there is nowhere to hand a resul { // A correctness requirement rather than a second optimisation: with nothing to submit the // result to, offloading would park a coroutine that nothing could ever resume. - auto inner = ScriptedResolver {}; + auto inner = ScriptedAddressResolver {}; + scriptExample(inner); auto resolver = ThreadedAddressResolver { inner }; auto clock = core::platform::ManualClock {}; @@ -207,9 +150,10 @@ TEST_CASE("a full resolver queue is refused rather than waited on", "[net]") { // An unbounded queue is a memory-exhaustion hole reachable by whatever provokes dials, and // blocking the caller to wait for room would reintroduce, on the loop thread, exactly the - // stall this class exists to remove. `WouldBlock` and not `SystemError`, because a caller can - // retry the first and can do nothing at all with the second. - auto inner = ScriptedResolver {}; + // stall this class exists to remove. `ResourceExhausted`, which a caller may retry once a lookup + // has returned, and never `WouldBlock`, which an accept loop reads as a deadline's tick. + auto inner = ScriptedAddressResolver {}; + scriptExample(inner); inner.hold(); auto resolver = ThreadedAddressResolver { inner, { .threads = 1, .maxQueueDepth = 1 } }; @@ -226,14 +170,15 @@ TEST_CASE("a full resolver queue is refused rather than waited on", "[net]") loop.spawn(resolveOn(&loop, &resolver, "one.test", &first, &where)); loop.runUntilIdle(); - inner.awaitEntered(1); + REQUIRE(inner.awaitEntered(1, EnterBudget) >= 1); loop.spawn(resolveOn(&loop, &resolver, "two.test", &second, &where)); loop.runUntilIdle(); // The third has nowhere to go: the worker is busy and the queue slot is taken. loop.blockOn(resolveOn(&loop, &resolver, "three.test", &third, &where)); REQUIRE_FALSE(third.has_value()); - CHECK(third.error().code == core::net::NetErrorCode::WouldBlock); + CHECK(third.error().code == core::net::NetErrorCode::ResourceExhausted); + CHECK_FALSE(core::net::isDeadlineExpiry(third.error().code)); CHECK(resolver.refused() == 1); inner.release(); @@ -245,7 +190,8 @@ TEST_CASE("stopping the resolver resumes a queued lookup rather than stranding i // A queued lookup whose coroutine is never resumed is a leaked frame, so `stop` fails // everything queued instead of dropping it. A lookup already inside the blocking call cannot // be interrupted — there is no portable way — so the join waits for that one. - auto inner = ScriptedResolver {}; + auto inner = ScriptedAddressResolver {}; + scriptExample(inner); inner.hold(); auto resolver = ThreadedAddressResolver { inner, { .threads = 1, .maxQueueDepth = 8 } }; @@ -259,7 +205,7 @@ TEST_CASE("stopping the resolver resumes a queued lookup rather than stranding i loop.spawn(resolveOn(&loop, &resolver, "in-flight.test", &inFlight, &where)); loop.runUntilIdle(); - inner.awaitEntered(1); + REQUIRE(inner.awaitEntered(1, EnterBudget) >= 1); loop.spawn(resolveOn(&loop, &resolver, "queued.test", &queued, &where)); loop.runUntilIdle(); @@ -298,7 +244,8 @@ TEST_CASE("a stop ends a lookup that never returns and the answer that arrives l // returns. It is released only after the flow is gone, which is the second half: the worker // then publishes an answer for a frame that no longer exists, and that answer must go // nowhere. A hand-back queued to the loop is what delivering it would look like. - auto inner = ScriptedResolver {}; + auto inner = ScriptedAddressResolver {}; + scriptExample(inner); inner.hold(); auto resolver = ThreadedAddressResolver { inner, { .threads = 1, .maxQueueDepth = 8 } }; @@ -309,7 +256,7 @@ TEST_CASE("a stop ends a lookup that never returns and the answer that arrives l auto cancelled = false; loop.spawn(resolveOrUnwind(&loop, &resolver, "silent.test", &answer, &cancelled)); loop.drain(); - inner.awaitEntered(1); + REQUIRE(inner.awaitEntered(1, EnterBudget) >= 1); loop.rootStopSource().request_stop(); loop.drain(); @@ -331,7 +278,8 @@ TEST_CASE("a stop from another thread ends a lookup that never returns", "[net]" // request it: off the loop. The stop callback then runs on THAT thread, beside a worker // thread that may be publishing at the same moment, which is the arrangement // ThreadSanitizer needs to see. - auto inner = ScriptedResolver {}; + auto inner = ScriptedAddressResolver {}; + scriptExample(inner); inner.hold(); auto resolver = ThreadedAddressResolver { inner, { .threads = 1, .maxQueueDepth = 8 } }; @@ -349,7 +297,9 @@ TEST_CASE("a stop from another thread ends a lookup that never returns", "[net]" // release is what finally resumes the flow — with an ANSWER, which the CHECK below reports as // a red instead of the case hanging until ctest's TIMEOUT says nothing about why. auto stopper = std::thread { [&loop, &inner, &flowDone] { - inner.awaitEntered(1); + // Not asserted: Catch2 is not thread-safe, and a lookup that never entered leaves the flow + // parked, which the CHECK on the test's thread reports. + static_cast(inner.awaitEntered(1, EnterBudget)); loop.rootStopSource().request_stop(); for ([[maybe_unused]] auto const tick: std::views::iota(0, 5000)) { @@ -374,3 +324,88 @@ TEST_CASE("a stop from another thread ends a lookup that never returns", "[net]" stopper.join(); resolver.stop(); } + +TEST_CASE("a classified resolver failure survives the hop to and from the resolver thread", "[net]") +{ + // A name that does not exist and a resolver that could not answer are two different things to + // the flow that asked, and the pool must not flatten them into one `AddressError` on the way + // back. Both arms: the offloaded one, and the inline one a null loop takes. + auto script = ScriptedAddressResolver {}; + script.failWithCode(core::net::makeNetError(core::net::NetErrorCode::NameNotFound, 0, "NXDOMAIN")); + auto resolver = ThreadedAddressResolver { script, { .threads = 1, .maxQueueDepth = 8 } }; + + auto backend = core::net::makeBackend(core::net::preferredBackendKind()); + REQUIRE(backend != nullptr); + auto loop = EventLoop { *backend }; + + auto offloaded = ResolveResult {}; + auto inlined = ResolveResult {}; + auto where = std::thread::id {}; + loop.blockOn(resolveOn(&loop, &resolver, "missing.test", &offloaded, &where)); + loop.blockOn(resolveOn(nullptr, &resolver, "missing.test", &inlined, &where)); + + CHECK(resolver.offloaded() == 1); + REQUIRE_FALSE(offloaded.has_value()); + CHECK(offloaded.error().code == core::net::NetErrorCode::NameNotFound); + CHECK(offloaded.error().context == "cannot resolve missing.test:80: NXDOMAIN"); + REQUIRE_FALSE(inlined.has_value()); + CHECK(inlined.error().code == core::net::NetErrorCode::NameNotFound); +} + +TEST_CASE("a held scripted lookup parks the flow until it is released", "[net]") +{ + // The scripted resolver's hold, driven across the thread it is for: the flow stays parked while + // the worker is held inside the lookup, and resumes with the scripted answer once released. + auto script = ScriptedAddressResolver {}; + script.answer("db.test", { ResolvedEndpoint { .length = 16, .family = 2, .protocol = 6 } }); + script.hold(); + auto resolver = ThreadedAddressResolver { script, { .threads = 1, .maxQueueDepth = 8 } }; + auto const releaseOnExit = core::net::detail::ScopeGuard { [&script]() noexcept { script.release(); } }; + + auto backend = core::net::makeBackend(core::net::preferredBackendKind()); + REQUIRE(backend != nullptr); + auto loop = EventLoop { *backend }; + + auto answer = ResolveResult { std::unexpected(core::net::makeNetError(core::net::NetErrorCode::Ok)) }; + auto resumedOn = std::thread::id {}; + loop.spawn(resolveOn(&loop, &resolver, "db.test", &answer, &resumedOn)); + loop.runUntilIdle(); + REQUIRE(script.awaitEntered(1, EnterBudget) == 1); + loop.runUntilIdle(); + CHECK(resumedOn == std::thread::id {}); // still parked: the worker is held + + script.release(); + for ([[maybe_unused]] auto const turn: std::views::iota(0, 5000)) + { + if (resumedOn != std::thread::id {}) + break; + loop.runUntilIdle(); + std::this_thread::sleep_for(std::chrono::milliseconds { 1 }); + } + CHECK(resumedOn == std::this_thread::get_id()); + REQUIRE(answer.has_value()); + CHECK(answer->size() == 1); + resolver.stop(); +} + +TEST_CASE("a host no name can be is refused before any resolver thread sees it", "[net]") +{ + // The same refusal as ExecutorAddressResolver's: an empty host (getaddrinfo's wildcard), a NUL, + // or more than 253 bytes. + auto const tooLong = std::string(254, 'a'); + auto const host = GENERATE_COPY(std::string {}, std::string { "example.test\0evil", 17 }, tooLong); + auto const viaLoop = GENERATE(true, false); + CAPTURE(host.size(), viaLoop); + auto inner = ScriptedAddressResolver {}; + scriptExample(inner); + auto resolver = ThreadedAddressResolver { inner }; + auto clock = core::platform::ManualClock {}; + auto loop = core::net::testing::TestLoop { clock }; + auto answer = ResolveResult {}; + auto resumedOn = std::thread::id {}; + loop.blockOn(resolveOn(viaLoop ? &loop : nullptr, &resolver, host, &answer, &resumedOn)); + REQUIRE_FALSE(answer.has_value()); + CHECK(answer.error().code == core::net::NetErrorCode::AddressError); + CHECK(resolver.offloaded() == 0); + CHECK(inner.calls() == 0); +} diff --git a/src/core/net/detail/ParkedCall.hpp b/src/core/net/detail/ParkedCall.hpp new file mode 100644 index 00000000..87cebf29 --- /dev/null +++ b/src/core/net/detail/ParkedCall.hpp @@ -0,0 +1,222 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// `detail::ParkedCall` — one blocking call's rendezvous between whatever runs it and the +/// coroutine on a loop that waits for its answer, with a stop that ends the wait and not the call. +/// +/// Shared by every resolver that hands `getaddrinfo` to somebody else's thread +/// (@c ThreadedAddressResolver, @c ExecutorAddressResolver), and shaped for any other call that +/// cannot be interrupted once it has started. + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace core::net::detail +{ + +/// Where a parked call stands. One state rather than an `answered` and a `cancelled` flag, because +/// the waiter is handed back exactly once and so exactly one of the two outcomes reached it. +enum class SlotState : std::uint8_t +{ + Pending, ///< Nobody has decided yet; a waiter, if there is one, is parked. + Answered, ///< The answer took the waiter (or arrived before there was one) and will be delivered. + Cancelled, ///< A stop took the waiter first; the flow throws, and a later answer is only kept. +}; + +/// One call's rendezvous between the thread that runs it and the coroutine that waits for it. +/// +/// Held by `std::shared_ptr`, because either side may reach it last: the runner must be able to +/// publish into it after the waiting flow was abandoned, and the flow must be able to read it after +/// the runner is gone. +/// +/// **Whoever takes the waiter first decides the outcome**, and the other finds it empty. @c settle +/// takes it to deliver an answer, a stop takes it to deliver a cancellation, and both do so under +/// the one mutex — so exactly one of them hands the coroutine back, and the loser's news goes +/// nowhere. That is what makes an answer arriving after a stop harmless: the frame it would have +/// been delivered into may already be gone. Such an answer is still stored, and an owner who keeps +/// the call (a stream whose bytes must not be lost) takes it with @c takeLateAnswer. +/// +/// **Nothing here resumes inline.** The waiter is SUBMITTED to the loop it parked on, so the flow +/// continues on the loop's thread and never on the runner's, or the stopper's. +/// +/// **Settling never throws.** It runs where nothing can take an exception -- a detached flow, a +/// destructor, a stop callback -- so the one call that can fail, the loop's `submit` running out of +/// memory, ends the process (`noexcept`): a waiter that cannot be handed back can be neither resumed +/// nor freed safely from here. +/// @tparam T What the call answers. +template +class ParkedCall +{ + static_assert(std::is_nothrow_move_constructible_v, + "settling moves the answer where nothing can take a throw"); + + public: + /// @param loop Where the waiter is handed back. Null only where nothing ever parks on the call; + /// a waiter with nowhere to go is freed rather than leaked (@c async::detail::Parked). + explicit ParkedCall(EventLoop* loop) noexcept: _loop(loop) {} + + /// Publishes the answer and hands the waiter back to the loop. + /// + /// The first answer wins; a second is ignored. After a stop the answer is kept but delivered + /// to nobody. + /// @param answer What the call produced. + void settle(T answer) noexcept + { + auto waiter = async::detail::Parked {}; + { + auto const guard = std::scoped_lock { _mutex }; + if (_answer.has_value()) + return; + _answer.emplace(std::move(answer)); + if (_state == SlotState::Pending) + _state = SlotState::Answered; + waiter = async::detail::Parked { std::exchange(_waiter, async::ParkedWork {}) }; + } + handBack(std::move(waiter)); + } + + /// The stop callback of a parked call: takes the waiter back and hands it to the loop, + /// cancelled. + /// + /// **It may run on any thread** — the loop's, a whenAny sibling's, a watchdog's — so it does + /// what @c settle does and nothing more. A named functor holding one plain pointer rather than + /// a `std::function`, so registering it allocates nothing. The call outlives it: the awaiter + /// that owns this callback also holds the call's `shared_ptr`, and drops the callback first. + struct Cancel + { + ParkedCall* call = nullptr; + + void operator()() const noexcept + { + auto waiter = async::detail::Parked {}; + { + auto const guard = std::scoped_lock { call->_mutex }; + // An answer that got here first is delivered, and a stop after it changes nothing: + // the flow is already on its way back with a result it can use. + if (call->_state != SlotState::Pending) + return; + call->_state = SlotState::Cancelled; + waiter = async::detail::Parked { std::exchange(call->_waiter, async::ParkedWork {}) }; + } + call->handBack(std::move(waiter)); + } + }; + + /// Suspends until the call is settled, or until the awaiting flow is stopped. + /// + /// Race-free the way @c ResultAwaitable is: the answer check and the waiter registration + /// happen under one lock, so an answer landing between them resumes through the normal path + /// rather than parking on an answer that has already arrived. + struct Awaiter + { + std::shared_ptr call; + std::optional> cancelReg {}; + + /// @return False. Whether the answer is already there is @c await_suspend's first question, + /// asked under the call's mutex: taking a lock is a call, and MSVC 19.44's ARM64 + /// code generator drops the enclosing `try` of a `co_await` on a temporary awaiter + /// whose `await_ready` makes one (fastcached#1546, `.agent/rules/async-and-net.md`). + [[nodiscard]] constexpr bool await_ready() const noexcept { return false; } + + /// Templated on the promise so `parkedWorkFor` can ask the PARKING coroutine's own promise + /// whether anything else owns its chain: @c settle hands this chain to a loop that may be + /// destroyed before it runs it, so this is the last place the question can be asked. The + /// same promise is where the flow's stop token is read. + /// + /// **An answer already there resumes at once, before the stop callback exists**, so a stop + /// that has already fired cannot turn a finished call into a cancellation. + /// + /// **The stop callback is registered BEFORE the waiter is published.** A stop landing in + /// between then finds no waiter, records @c SlotState::Cancelled, and the check below sees + /// it and does not park; registered after, a stop that had already fired would run the + /// callback inline, find the waiter, and hand it to the loop while this function is still + /// deciding whether to suspend — the same frame queued and returned-into at once. + /// @tparam Promise The suspending coroutine's promise type. + /// @param handle The suspended flow. + /// @return True to stay suspended; false when the answer or the stop arrived first. + template + [[nodiscard]] bool await_suspend(std::coroutine_handle handle) + { + { + auto const guard = std::scoped_lock { call->_mutex }; + if (call->_state == SlotState::Answered) + return false; + } + if constexpr (async::HasStopToken) + cancelReg.emplace(handle.promise().stopToken(), Cancel { .call = call.get() }); + + auto const guard = std::scoped_lock { call->_mutex }; + if (call->_state != SlotState::Pending) + return false; + call->_waiter = async::detail::parkedWorkFor(handle); + return true; + } + + /// @return The call's answer. + /// @throws async::OperationCancelled if the flow was stopped before the answer arrived. + [[nodiscard]] T await_resume() + { + // Dropped first: it waits for a callback running on another thread to finish, so the + // call is not read while that callback is still writing it. + cancelReg.reset(); + auto const guard = std::scoped_lock { call->_mutex }; + if (call->_state == SlotState::Cancelled) + throw async::OperationCancelled {}; + return std::move(*call->_answer); + } + }; + + /// @param call The call to wait for; the awaiter keeps it alive. + /// @return What a flow `co_await`s to wait for @p call's answer. + [[nodiscard]] static Awaiter wait(std::shared_ptr call) noexcept + { + return Awaiter { .call = std::move(call) }; + } + + /// Takes the answer that arrived after a stop had already handed the waiter back. + /// + /// For an owner that must not lose it -- bytes a blocking read returned after its reader gave + /// up are the next read's, not nobody's. An answer that was delivered is never here. + /// @return The late answer, once; nothing if the call was not stopped or has not answered yet. + [[nodiscard]] std::optional takeLateAnswer() noexcept + { + auto const guard = std::scoped_lock { _mutex }; + if (_state != SlotState::Cancelled) + return std::nullopt; + return std::exchange(_answer, std::nullopt); + } + + private: + /// Hands @p waiter back to the loop, or frees it where there is nowhere to hand it. + /// + /// An `async::detail::Parked` rather than a bare `ParkedWork`, so the branch that hands nothing + /// on FREES an unowned chain instead of dropping it — `ParkedWork`'s contract, resumed or freed, + /// never neither. A BORROWED handle's claim is empty, so the guard destroys nothing and the + /// caller's owner still frees it. + /// @param waiter What was taken out of the call; may be empty. + void handBack(async::detail::Parked waiter) noexcept + { + if (waiter.handle() && _loop != nullptr) + _loop->submit(waiter.take()); + } + + EventLoop* _loop; + std::mutex _mutex; + std::optional _answer; + async::ParkedWork _waiter {}; + SlotState _state = SlotState::Pending; +}; + +} // namespace core::net::detail diff --git a/src/core/net/detail/ParkedCall_test.cpp b/src/core/net/detail/ParkedCall_test.cpp new file mode 100644 index 00000000..370527a7 --- /dev/null +++ b/src/core/net/detail/ParkedCall_test.cpp @@ -0,0 +1,121 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// `detail::ParkedCall`: the rendezvous both resolvers park on, and Task 11's stdin read will. +// Whoever takes the waiter first decides; an answer after a stop is kept for the owner, not lost. +#include +#include +#include +#include +#include + +#include + +#include +#include +#include + +using core::async::Task; +using core::net::detail::ParkedCall; +using core::net::testing::TestLoop; + +namespace +{ + +/// How one wait on a call ended. +struct Outcome +{ + std::optional answer; + bool isCancelled = false; + bool isFinished = false; +}; + +/// Waits for @p call's answer and records how the wait ended. +Task waitInto(std::shared_ptr> call, Outcome* out) +{ + try + { + out->answer = co_await ParkedCall::wait(std::move(call)); + } + catch (core::async::OperationCancelled const&) + { + out->isCancelled = true; + } + out->isFinished = true; +} + +} // namespace + +TEST_CASE("a parked call delivers its answer through the loop", "[net][parked-call]") +{ + auto clock = core::platform::ManualClock {}; + auto loop = TestLoop { clock }; + auto call = std::make_shared>(&loop); + + auto outcome = Outcome {}; + loop.spawn(waitInto(call, &outcome)); + loop.drain(); + REQUIRE_FALSE(outcome.isFinished); + + call->settle(7); + CHECK_FALSE(outcome.isFinished); // handed to the loop, not resumed by the settler + loop.drain(); + REQUIRE(outcome.isFinished); + CHECK(outcome.answer == 7); + CHECK_FALSE(call->takeLateAnswer().has_value()); // delivered, so never a late one +} + +TEST_CASE("an answer already there is taken without parking", "[net][parked-call]") +{ + auto clock = core::platform::ManualClock {}; + auto loop = TestLoop { clock }; + auto call = std::make_shared>(&loop); + call->settle(3); + + // Stopped too: an answer that is already there is not turned into a cancellation. + loop.rootStopSource().request_stop(); + auto outcome = Outcome {}; + loop.spawn(waitInto(call, &outcome)); + loop.drain(); + REQUIRE(outcome.isFinished); + CHECK(outcome.answer == 3); +} + +TEST_CASE("the first answer wins", "[net][parked-call]") +{ + auto clock = core::platform::ManualClock {}; + auto loop = TestLoop { clock }; + auto call = std::make_shared>(&loop); + + auto outcome = Outcome {}; + loop.spawn(waitInto(call, &outcome)); + loop.drain(); + call->settle(1); + call->settle(2); + loop.drain(); + REQUIRE(outcome.isFinished); + CHECK(outcome.answer == 1); +} + +TEST_CASE("a stop hands the flow back cancelled and keeps the late answer for its owner", + "[net][parked-call]") +{ + auto clock = core::platform::ManualClock {}; + auto loop = TestLoop { clock }; + auto call = std::make_shared>(&loop); + + auto outcome = Outcome {}; + loop.spawn(waitInto(call, &outcome)); + loop.drain(); + CHECK_FALSE(call->takeLateAnswer().has_value()); // nothing answered yet + + loop.rootStopSource().request_stop(); + loop.drain(); + REQUIRE(outcome.isFinished); + CHECK(outcome.isCancelled); + CHECK_FALSE(call->takeLateAnswer().has_value()); // stopped, but not answered yet + + call->settle(9); + CHECK(loop.drain() == 0); // nobody to deliver it to + CHECK(call->takeLateAnswer() == 9); + CHECK_FALSE(call->takeLateAnswer().has_value()); // taken once +} diff --git a/src/core/net/posix/PosixListener.cpp b/src/core/net/posix/PosixListener.cpp index 72ce7295..47c27ae7 100644 --- a/src/core/net/posix/PosixListener.cpp +++ b/src/core/net/posix/PosixListener.cpp @@ -113,8 +113,14 @@ std::expected, NetError> PosixListener::bind(Even addrinfo* resolved = nullptr; auto const rc = ::getaddrinfo(hostStr.empty() ? nullptr : hostStr.c_str(), portStr.c_str(), &hints, &resolved); - if (rc != 0 || resolved == nullptr) - return std::unexpected(makeNetError(NetErrorCode::AddressError, rc, "getaddrinfo")); + if (rc != 0) + { + // The system code first: for EAI_SYSTEM it is errno, which nothing may touch before it. + auto const systemCode = detail::resolverSystemCode(rc); + return std::unexpected(makeNetError(detail::classifyResolverError(rc), systemCode, "getaddrinfo")); + } + if (resolved == nullptr) + return std::unexpected(makeNetError(NetErrorCode::AddressError, 0, "getaddrinfo")); int fd = -1; NetError lastError = makeNetError(NetErrorCode::AddressError, 0, "no usable address"); diff --git a/src/core/net/posix/ResolverErrors_test.cpp b/src/core/net/posix/ResolverErrors_test.cpp new file mode 100644 index 00000000..5a3c227e --- /dev/null +++ b/src/core/net/posix/ResolverErrors_test.cpp @@ -0,0 +1,138 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The POSIX half of "a resolver failure is classified in ONE table": every `getaddrinfo` code this +// platform can answer has a row of `resolverErrorTable()`, and the rows the WASI `ip-name-lookup` +// mapping depends on land where it says. The Windows half is `windows/ResolverErrors_test.cpp`. +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include + +using core::net::NetErrorCode; +using core::net::resolverErrorTable; +using core::net::detail::classifyResolverError; +using core::net::detail::resolverSystemCode; + +namespace +{ + +/// One `getaddrinfo` code and the category it must land in. +struct Row +{ + int gaiCode; ///< The `EAI_*` value. + NetErrorCode code; ///< Its category. +}; + +// Every row of the table, restated: a row whose category changes fails here, not only a row that +// goes missing. The codes only some libcs define are guarded by their own macro, as in the table; +// FreeBSD keeps the values of the two it retired, which its `gai_strerror` still describes. +constexpr auto Rows = std::array { + Row { .gaiCode = EAI_NONAME, .code = NetErrorCode::NameNotFound }, +#ifdef EAI_NODATA + Row { .gaiCode = EAI_NODATA, .code = NetErrorCode::NameNotFound }, +#elifdef __FreeBSD__ + Row { .gaiCode = 7, .code = NetErrorCode::NameNotFound }, +#endif +#ifdef EAI_ADDRFAMILY + Row { .gaiCode = EAI_ADDRFAMILY, .code = NetErrorCode::NameNotFound }, +#elifdef __FreeBSD__ + Row { .gaiCode = 1, .code = NetErrorCode::NameNotFound }, +#endif + Row { .gaiCode = EAI_AGAIN, .code = NetErrorCode::ResolverTemporaryFailure }, + Row { .gaiCode = EAI_FAIL, .code = NetErrorCode::AddressError }, + Row { .gaiCode = EAI_MEMORY, .code = NetErrorCode::ResourceExhausted }, + Row { .gaiCode = EAI_SYSTEM, .code = NetErrorCode::SystemError }, + Row { .gaiCode = EAI_FAMILY, .code = NetErrorCode::AddressError }, + Row { .gaiCode = EAI_SOCKTYPE, .code = NetErrorCode::AddressError }, + Row { .gaiCode = EAI_BADFLAGS, .code = NetErrorCode::AddressError }, + Row { .gaiCode = EAI_SERVICE, .code = NetErrorCode::AddressError }, + Row { .gaiCode = EAI_OVERFLOW, .code = NetErrorCode::AddressError }, +#ifdef EAI_BADHINTS + Row { .gaiCode = EAI_BADHINTS, .code = NetErrorCode::AddressError }, +#endif +#ifdef EAI_PROTOCOL + Row { .gaiCode = EAI_PROTOCOL, .code = NetErrorCode::AddressError }, +#endif +#ifdef EAI_INPROGRESS + Row { .gaiCode = EAI_INPROGRESS, .code = NetErrorCode::AddressError }, +#endif +#ifdef EAI_CANCELED + Row { .gaiCode = EAI_CANCELED, .code = NetErrorCode::AddressError }, +#endif +#ifdef EAI_NOTCANCELED + Row { .gaiCode = EAI_NOTCANCELED, .code = NetErrorCode::AddressError }, +#endif +#ifdef EAI_ALLDONE + Row { .gaiCode = EAI_ALLDONE, .code = NetErrorCode::AddressError }, +#endif +#ifdef EAI_INTR + Row { .gaiCode = EAI_INTR, .code = NetErrorCode::AddressError }, +#endif +#ifdef EAI_IDN_ENCODE + Row { .gaiCode = EAI_IDN_ENCODE, .code = NetErrorCode::AddressError }, +#endif +}; + +} // namespace + +TEST_CASE("Every POSIX resolver code lands in its category, and the table holds nothing else", + "[net][errors]") +{ + for (auto const& row: Rows) + { + INFO("EAI code " << row.gaiCode << ": " << ::gai_strerror(row.gaiCode)); + CHECK(classifyResolverError(row.gaiCode) == row.code); + } + + auto expected = std::map {}; + for (auto const& row: Rows) + expected.emplace(row.gaiCode, row.code); + auto actual = std::map {}; + for (auto const& row: resolverErrorTable()) + actual.emplace(row.gaiCode, row.code); + CHECK(actual == expected); +} + +TEST_CASE("Every code this platform's getaddrinfo can answer has a row", "[net][errors]") +{ + // Asked of the platform rather than of a list written here: `gai_strerror` describes every code + // its libc defines, and the same text for every value it does not. A libc that grows a code fails + // this case until the code's row is a decision, instead of reporting it as the catch-all. + // + // glibc numbers its codes from -1 down, with `getaddrinfo_a`'s around -100; macOS and the BSDs + // number theirs from 1 up. The window covers both with room to spare. + auto const unknown = std::string { ::gai_strerror(-424242) }; + auto missing = std::string {}; + for (auto const gaiCode: std::views::iota(-512, 513)) + { + if (gaiCode == 0 || std::string_view { ::gai_strerror(gaiCode) } == unknown) + continue; + auto const listed = std::ranges::any_of( + resolverErrorTable(), [gaiCode](auto const& row) { return row.gaiCode == gaiCode; }); + if (!listed) + missing += std::to_string(gaiCode) + " (" + ::gai_strerror(gaiCode) + "); "; + } + INFO("getaddrinfo codes without a row: " << missing); + CHECK(missing.empty()); +} + +TEST_CASE("Only EAI_SYSTEM carries an errno", "[net][errors]") +{ + // `EAI_SYSTEM` says "look in errno", and is the one code whose cause is not the code itself. Every + // other code is no errno, and reporting the errno left over from some earlier call would name a + // cause that has nothing to do with the lookup. + errno = ECONNREFUSED; + CHECK(resolverSystemCode(EAI_SYSTEM) == ECONNREFUSED); + CHECK(resolverSystemCode(EAI_NONAME) == 0); + CHECK(resolverSystemCode(EAI_AGAIN) == 0); +} diff --git a/src/core/net/posix/SocketsPosix.cpp b/src/core/net/posix/SocketsPosix.cpp index 0e29d78b..567a178f 100644 --- a/src/core/net/posix/SocketsPosix.cpp +++ b/src/core/net/posix/SocketsPosix.cpp @@ -1,4 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 +#include #include #include #include @@ -10,10 +11,12 @@ #include #include +#include #include #include #include #include +#include #include #include @@ -169,4 +172,94 @@ std::expected, NetError> adoptFd(EventLoop& loop, int f return std::unique_ptr(new PosixSocket(loop, fd)); } +namespace +{ +#if defined(__FreeBSD__) && !defined(EAI_NODATA) + /// FreeBSD's retired `EAI_NODATA`: its `netdb.h` has it under `#if 0`, but `gai_strerror` still + /// describes the value, so the table holds a row for it. + constexpr auto FreeBsdObsoleteNoData = 7; +#endif +#if defined(__FreeBSD__) && !defined(EAI_ADDRFAMILY) + /// FreeBSD's retired `EAI_ADDRFAMILY`, kept the same way. + constexpr auto FreeBsdObsoleteAddrFamily = 1; +#endif + + /// Every `EAI_*` code a POSIX libc defines, classified. The codes only some libcs define are + /// guarded by their own macro, which is the per-OS choice: glibc and macOS name `EAI_NODATA` and + /// `EAI_ADDRFAMILY`, macOS alone `EAI_BADHINTS` and `EAI_PROTOCOL`, glibc alone the + /// `getaddrinfo_a` codes. `posix/ResolverErrors_test.cpp` asks `gai_strerror` which codes this + /// libc knows and fails on one without a row. + constexpr auto ResolverErrors = std::array { + // No such name, or no address for it: WASI's `name-unresolvable`. `EAI_NODATA` is a name + // with no address at all, `EAI_ADDRFAMILY` one with none of the asked family -- with + // `AF_UNSPEC`, the same thing. + ResolverErrorRow { .gaiCode = EAI_NONAME, .code = NetErrorCode::NameNotFound }, +#ifdef EAI_NODATA + ResolverErrorRow { .gaiCode = EAI_NODATA, .code = NetErrorCode::NameNotFound }, +#elifdef __FreeBSD__ + ResolverErrorRow { .gaiCode = FreeBsdObsoleteNoData, .code = NetErrorCode::NameNotFound }, +#endif +#ifdef EAI_ADDRFAMILY + ResolverErrorRow { .gaiCode = EAI_ADDRFAMILY, .code = NetErrorCode::NameNotFound }, +#elifdef __FreeBSD__ + ResolverErrorRow { .gaiCode = FreeBsdObsoleteAddrFamily, .code = NetErrorCode::NameNotFound }, +#endif + // The name server did not answer now: WASI's `temporary-resolver-failure`. + ResolverErrorRow { .gaiCode = EAI_AGAIN, .code = NetErrorCode::ResolverTemporaryFailure }, + // The name server answered that it cannot: WASI's `permanent-resolver-failure`. + ResolverErrorRow { .gaiCode = EAI_FAIL, .code = NetErrorCode::AddressError }, + ResolverErrorRow { .gaiCode = EAI_MEMORY, .code = NetErrorCode::ResourceExhausted }, + // The cause is in errno (`detail::resolverSystemCode`). + ResolverErrorRow { .gaiCode = EAI_SYSTEM, .code = NetErrorCode::SystemError }, + // Refusals of the request itself. The hints and the numeric service are this library's own + // (`AF_UNSPEC`, `SOCK_STREAM`), so none of these is expected; each is permanent, and the WASI + // mapping has no third answer for a lookup than not-found, temporary and permanent. + ResolverErrorRow { .gaiCode = EAI_FAMILY, .code = NetErrorCode::AddressError }, + ResolverErrorRow { .gaiCode = EAI_SOCKTYPE, .code = NetErrorCode::AddressError }, + ResolverErrorRow { .gaiCode = EAI_BADFLAGS, .code = NetErrorCode::AddressError }, + ResolverErrorRow { .gaiCode = EAI_SERVICE, .code = NetErrorCode::AddressError }, + ResolverErrorRow { .gaiCode = EAI_OVERFLOW, .code = NetErrorCode::AddressError }, +#ifdef EAI_BADHINTS + ResolverErrorRow { .gaiCode = EAI_BADHINTS, .code = NetErrorCode::AddressError }, +#endif +#ifdef EAI_PROTOCOL + ResolverErrorRow { .gaiCode = EAI_PROTOCOL, .code = NetErrorCode::AddressError }, +#endif + // glibc's `getaddrinfo_a` and IDN codes. `getaddrinfo` without `AI_IDN` returns none of them; + // they are rows because `gai_strerror` knows them, and a row is a decision where a missing + // one would be a guess. +#ifdef EAI_INPROGRESS + ResolverErrorRow { .gaiCode = EAI_INPROGRESS, .code = NetErrorCode::AddressError }, +#endif +#ifdef EAI_CANCELED + ResolverErrorRow { .gaiCode = EAI_CANCELED, .code = NetErrorCode::AddressError }, +#endif +#ifdef EAI_NOTCANCELED + ResolverErrorRow { .gaiCode = EAI_NOTCANCELED, .code = NetErrorCode::AddressError }, +#endif +#ifdef EAI_ALLDONE + ResolverErrorRow { .gaiCode = EAI_ALLDONE, .code = NetErrorCode::AddressError }, +#endif +#ifdef EAI_INTR + ResolverErrorRow { .gaiCode = EAI_INTR, .code = NetErrorCode::AddressError }, +#endif +#ifdef EAI_IDN_ENCODE + ResolverErrorRow { .gaiCode = EAI_IDN_ENCODE, .code = NetErrorCode::AddressError }, +#endif + }; +} // namespace + +std::span resolverErrorTable() noexcept +{ + return ResolverErrors; +} + +namespace detail +{ + int resolverSystemCode(int gaiCode) noexcept + { + return gaiCode == EAI_SYSTEM ? errno : 0; + } +} // namespace detail + } // namespace core::net diff --git a/src/core/net/testing/ScriptedAddressResolver.hpp b/src/core/net/testing/ScriptedAddressResolver.hpp new file mode 100644 index 00000000..9dad3733 --- /dev/null +++ b/src/core/net/testing/ScriptedAddressResolver.hpp @@ -0,0 +1,199 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// `ScriptedAddressResolver` — a blocking resolver that answers from a script, deterministically, +/// with no name server and no thread of its own. + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace core::net::testing +{ + +/// An @c IAddressResolver whose answers a test writes. +/// +/// - A **literal** (`127.0.0.1`, `::1`) is parsed by @c detail::endpointOfLiteral, as a real +/// resolver parses it, and never answered from the script: a dial to one tests what production does. +/// Only the strict forms are literals; `127.1`, which `getaddrinfo` expands, is a name here and must +/// be scripted by a test that dials it. +/// - A **name** given to @c answer resolves to its endpoints, verbatim. +/// - Any other name fails as the last of @c failWith or @c failWithCode said, and by default as +/// @c NetErrorCode::NameNotFound, which is what a real resolver says of a name it does not know. +/// +/// @c failWith scripts a failure in words only, so @c resolveClassified reports it through the +/// default classification of @c IAddressResolver -- the double for a resolver written before that +/// seam existed. @c failWithCode scripts the classified failure itself. +/// +/// **It owns no thread.** Every lookup runs on the caller's. Its state is locked, so a resolver that +/// offloads lookups (@c ThreadedAddressResolver) may call it from its own threads; @c hold is for +/// exactly that case, since a held lookup blocks the thread that called it until @c release. +class ScriptedAddressResolver final: public IAddressResolver +{ + public: + /// Scripts @p host to resolve to @p endpoints. + /// @param host The name, as a lookup will be asked for it. + /// @param endpoints The answer, in preference order. Their ports are not rewritten. + void answer(std::string host, std::vector endpoints) + { + auto const guard = std::scoped_lock { _mutex }; + _answers.insert_or_assign(std::move(host), std::move(endpoints)); + } + + /// Fails every unscripted name with @p message, unclassified. + /// @param message What @c resolve reports, and the context of the default classification. + void failWith(std::string message) + { + auto const guard = std::scoped_lock { _mutex }; + _failure = std::move(message); + } + + /// Fails every unscripted name with @p error. + /// @param error What @c resolveClassified reports; @c resolve reports it as words. + void failWithCode(NetError error) + { + auto const guard = std::scoped_lock { _mutex }; + _failure = std::move(error); + } + + /// Makes every later lookup block inside the resolver, on the calling thread, until @c release. + void hold() + { + auto const guard = std::scoped_lock { _mutex }; + _isHeld = true; + } + + /// Lets every held lookup, and every later one, return. + void release() + { + { + auto const guard = std::scoped_lock { _mutex }; + _isHeld = false; + } + _released.notify_all(); + } + + /// Waits, at most @p budget, until @p count lookups have entered the resolver. + /// @param count How many lookups to wait for, counted since construction. + /// @param budget The longest this waits. + /// @return How many lookups had entered when the wait ended: @p count or more, or fewer when + /// the budget ran out. + [[nodiscard]] std::size_t awaitEntered(std::size_t count, std::chrono::milliseconds budget) const + { + auto lock = std::unique_lock { _mutex }; + _entered.wait_for(lock, budget, [&] { return _calls >= count; }); + return _calls; + } + + /// @return How many lookups were asked of this resolver, literals included. + [[nodiscard]] std::size_t calls() const + { + auto const guard = std::scoped_lock { _mutex }; + return _calls; + } + + /// @return The thread each lookup ran on, in call order, literals included -- so a test can + /// say which thread paid for a lookup an async resolver offloaded. + [[nodiscard]] std::vector callers() const + { + auto const guard = std::scoped_lock { _mutex }; + return _callers; + } + + /// @copydoc IAddressResolver::resolve + [[nodiscard]] std::expected, std::string> resolve( + std::string_view host, std::uint16_t port) override + { + auto outcome = lookup(host, port); + if (auto* const endpoints = std::get_if>(&outcome)) + return std::move(*endpoints); + if (auto* const message = std::get_if(&outcome)) + return std::unexpected(std::move(*message)); + return std::unexpected(std::get(outcome).toString()); + } + + /// @copydoc IAddressResolver::resolveClassified + /// + /// A failure scripted by @c failWith takes the default classification. + [[nodiscard]] std::expected, NetError> resolveClassified( + std::string_view host, std::uint16_t port) override + { + auto outcome = lookup(host, port); + if (auto* const endpoints = std::get_if>(&outcome)) + return std::move(*endpoints); + if (auto* const error = std::get_if(&outcome)) + return std::unexpected(std::move(*error)); + auto message = std::move(std::get(outcome)); + return Unclassified { std::move(message) }.resolveClassified(host, port); + } + + private: + /// What one lookup came to: endpoints, a worded failure, or a classified one. + using Outcome = std::variant, std::string, NetError>; + + /// A resolver that knows only words, so that @c resolveClassified reaches the default + /// classification through the interface rather than restating it. + class Unclassified final: public IAddressResolver + { + public: + explicit Unclassified(std::string message) noexcept: _message(std::move(message)) {} + + [[nodiscard]] std::expected, std::string> resolve( + std::string_view /*host*/, std::uint16_t /*port*/) override + { + return std::unexpected(_message); + } + + private: + std::string _message; + }; + + /// Counts the lookup, waits out a hold, and answers it. + [[nodiscard]] Outcome lookup(std::string_view host, std::uint16_t port) + { + auto lock = std::unique_lock { _mutex }; + ++_calls; + _callers.push_back(std::this_thread::get_id()); + _entered.notify_all(); + _released.wait(lock, [this] { return !_isHeld; }); + + if (auto literal = detail::endpointOfLiteral(host, port)) + return std::vector { *literal }; + if (auto const answer = _answers.find(host); answer != _answers.end()) + return answer->second; + if (auto const* const message = std::get_if(&_failure)) + return *message; + if (auto const* const error = std::get_if(&_failure)) + return *error; + return makeNetError(NetErrorCode::NameNotFound, 0, std::format("no script answers '{}'", host)); + } + + mutable std::mutex _mutex; + mutable std::condition_variable _entered; + std::condition_variable _released; + std::map, std::less<>> _answers; + /// The unscripted names' failure: none scripted yet (`std::monostate`, @c NetErrorCode::NameNotFound), + /// worded, or classified. + std::variant _failure; + std::vector _callers; + std::size_t _calls = 0; + bool _isHeld = false; +}; + +} // namespace core::net::testing diff --git a/src/core/net/testing/ScriptedAddressResolver_test.cpp b/src/core/net/testing/ScriptedAddressResolver_test.cpp new file mode 100644 index 00000000..11e95734 --- /dev/null +++ b/src/core/net/testing/ScriptedAddressResolver_test.cpp @@ -0,0 +1,192 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// `testing::ScriptedAddressResolver`, and the default `IAddressResolver::resolveClassified` it is the +// first resolver to exercise: a resolver that only says WHY in words is a permanent failure, with +// those words kept. +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +using core::async::Task; +using core::net::makeNetError; +using core::net::NetErrorCode; +using core::net::ResolvedEndpoint; +using core::net::ResolveResult; +using core::net::testing::ScriptedAddressResolver; + +namespace +{ + +/// An endpoint no literal would produce, so a case can tell a scripted answer from a parsed one. +[[nodiscard]] ResolvedEndpoint scriptedEndpoint() +{ + return ResolvedEndpoint { .length = 16, .family = 2, .protocol = 6 }; +} + +/// Resolves @p host through @p resolver and stores what came back. +Task resolveInto(core::net::IAsyncAddressResolver* resolver, std::string host, ResolveResult* out) +{ + *out = co_await resolver->resolve(std::move(host), 80, nullptr); +} + +} // namespace + +TEST_CASE("the default classification of a worded failure is a permanent one that keeps the words", + "[net][resolver]") +{ + // A resolver written before the classified seam existed overrides only `resolve`. Its failures + // must still reach a caller of `resolveClassified` -- as `AddressError`, the one code that claims + // nothing about whether asking again could help, and with its message intact. + auto script = ScriptedAddressResolver {}; + script.failWith("no such host"); + + auto const resolved = script.resolveClassified("missing.test", 80); + REQUIRE_FALSE(resolved.has_value()); + CHECK(resolved.error().code == NetErrorCode::AddressError); + CHECK(resolved.error().context == "no such host"); + CHECK(resolved.error().systemCode == 0); + + auto const worded = script.resolve("missing.test", 80); + REQUIRE_FALSE(worded.has_value()); + CHECK(worded.error() == "no such host"); +} + +TEST_CASE("a scripted code reaches a classified caller as it was scripted", "[net][resolver]") +{ + auto script = ScriptedAddressResolver {}; + script.failWithCode(makeNetError(NetErrorCode::ResolverTemporaryFailure, 0, "server failure")); + + auto const resolved = script.resolveClassified("flaky.test", 80); + REQUIRE_FALSE(resolved.has_value()); + CHECK(resolved.error().code == NetErrorCode::ResolverTemporaryFailure); + CHECK(resolved.error().context == "server failure"); + + // The worded seam renders the same failure in words, so a caller of either sees one answer. + auto const worded = script.resolve("flaky.test", 80); + REQUIRE_FALSE(worded.has_value()); + CHECK(worded.error() == "resolver temporarily unavailable (server failure)"); +} + +TEST_CASE("a scripted name answers its endpoints and an unscripted one is not found", "[net][resolver]") +{ + auto script = ScriptedAddressResolver {}; + script.answer("db.test", { scriptedEndpoint(), scriptedEndpoint() }); + + auto const answered = script.resolveClassified("db.test", 5432); + REQUIRE(answered.has_value()); + CHECK(answered->size() == 2); + CHECK(answered->front().length == 16); + + // Deterministic without a script for it: the answer a real resolver gives an unknown name. + auto const unknown = script.resolveClassified("other.test", 5432); + REQUIRE_FALSE(unknown.has_value()); + CHECK(unknown.error().code == NetErrorCode::NameNotFound); + CHECK(unknown.error().context.contains("other.test")); + + CHECK(script.calls() == 2); +} + +TEST_CASE("a literal is parsed, never answered from the script", "[net][resolver]") +{ + // What a real resolver does with a literal, so a test of a dial to one exercises what production + // would: the address and the port come from the text, whatever the script says. + auto script = ScriptedAddressResolver {}; + script.answer("127.0.0.1", { scriptedEndpoint() }); + script.failWithCode(makeNetError(NetErrorCode::NameNotFound, 0, "scripted")); + + auto const v4 = script.resolveClassified("127.0.0.1", 9); + REQUIRE(v4.has_value()); + REQUIRE(v4->size() == 1); + CHECK(core::net::formatPeerAddress(v4->front()) == "127.0.0.1"); + CHECK(core::net::detail::portOfSockaddr(v4->front().storage.data(), v4->front().length) == 9); + + auto const v6 = script.resolveClassified("::1", 443); + REQUIRE(v6.has_value()); + REQUIRE(v6->size() == 1); + CHECK(core::net::formatPeerAddress(v6->front()) == "::1"); + CHECK(core::net::detail::portOfSockaddr(v6->front().storage.data(), v6->front().length) == 443); + + CHECK(script.calls() == 2); // asked, and answered without the script + + // The shorthand getaddrinfo expands is a name here, as `endpointOfLiteral` documents. + auto const shorthand = script.resolveClassified("127.1", 9); + REQUIRE_FALSE(shorthand.has_value()); + CHECK(shorthand.error().code == NetErrorCode::NameNotFound); +} + +TEST_CASE("the inline resolver reports what the classified seam said", "[net][resolver]") +{ + auto script = ScriptedAddressResolver {}; + script.failWithCode(makeNetError(NetErrorCode::NameNotFound, 0, "NXDOMAIN")); + auto resolver = core::net::InlineAddressResolver { script }; + + auto clock = core::platform::ManualClock {}; + auto loop = core::net::testing::TestLoop { clock }; + + auto answer = ResolveResult {}; + loop.blockOn(resolveInto(&resolver, "missing.test", &answer)); + REQUIRE_FALSE(answer.has_value()); + CHECK(answer.error().code == NetErrorCode::NameNotFound); + CHECK(answer.error().context == "cannot resolve missing.test:80: NXDOMAIN"); +} + +TEST_CASE("the inline resolver refuses a host no name can be before its inner resolver sees it", + "[net][resolver]") +{ + // The same refusal as the threaded and the executor resolvers': an empty host (getaddrinfo's + // wildcard), a NUL, or more than 253 bytes. + struct Row + { + std::string_view what; + std::string host; + }; + auto const rows = std::vector { + { .what = "empty", .host = {} }, + { .what = "an embedded NUL", .host = std::string { "example.test\0evil", 17 } }, + { .what = "254 bytes", .host = std::string(254, 'a') }, + }; + for (auto const& row: rows) + { + DYNAMIC_SECTION(row.what) + { + auto script = ScriptedAddressResolver {}; + auto resolver = core::net::InlineAddressResolver { script }; + auto clock = core::platform::ManualClock {}; + auto loop = core::net::testing::TestLoop { clock }; + + auto answer = ResolveResult {}; + loop.blockOn(resolveInto(&resolver, row.host, &answer)); + REQUIRE_FALSE(answer.has_value()); + CHECK(answer.error().code == NetErrorCode::AddressError); + CHECK(script.calls() == 0); + } + } +} + +TEST_CASE("a held lookup waits for release, and the wait for it is bounded", "[net][resolver]") +{ + // Nothing is entered: the bounded wait says so instead of hanging. + auto script = ScriptedAddressResolver {}; + CHECK(script.awaitEntered(1, std::chrono::milliseconds { 1 }) == 0); + + // Held, a lookup on the caller's thread would never return, so the hold is observed through the + // count alone here; `ThreadedAddressResolver_test.cpp` drives a held lookup across a thread. + script.hold(); + script.release(); + auto const resolved = script.resolveClassified("127.0.0.1", 1); + CHECK(resolved.has_value()); + CHECK(script.awaitEntered(1, std::chrono::milliseconds { 1 }) == 1); +} diff --git a/src/core/net/windows/IocpSocket.cpp b/src/core/net/windows/IocpSocket.cpp index 53235737..8e9e514b 100644 --- a/src/core/net/windows/IocpSocket.cpp +++ b/src/core/net/windows/IocpSocket.cpp @@ -1285,8 +1285,11 @@ std::expected, NetError> IocpListener::bind(EventL addrinfo* resolved = nullptr; if (auto const rc = ::getaddrinfo( hostString.empty() ? nullptr : hostString.c_str(), portString.c_str(), &hints, &resolved); - rc != 0 || resolved == nullptr) - return std::unexpected(makeNetError(NetErrorCode::AddressError, rc, "getaddrinfo")); + rc != 0) + return std::unexpected( + makeNetError(detail::classifyResolverError(rc), detail::resolverSystemCode(rc), "getaddrinfo")); + if (resolved == nullptr) + return std::unexpected(makeNetError(NetErrorCode::AddressError, 0, "getaddrinfo")); auto socket = detail::InvalidSocket; auto lastError = makeNetError(NetErrorCode::AddressError, 0, "no usable address"); diff --git a/src/core/net/windows/ResolverErrors_test.cpp b/src/core/net/windows/ResolverErrors_test.cpp new file mode 100644 index 00000000..1f8c5c40 --- /dev/null +++ b/src/core/net/windows/ResolverErrors_test.cpp @@ -0,0 +1,79 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The Windows half of "a resolver failure is classified in ONE table". Winsock's `getaddrinfo` +// answers `WSA*` codes (its `EAI_*` macros are spellings of them), and Windows has no `gai_strerror` +// that tells a known code from an unknown one -- it formats any system message -- so completeness is +// asserted against the documented list here, the whole table and nothing beside it. + +// clang-format off +#include +#include +// clang-format on + +#include +#include + +#include + +#include +#include + +using core::net::NetErrorCode; +using core::net::resolverErrorTable; +using core::net::detail::classifyResolverError; +using core::net::detail::resolverSystemCode; + +namespace +{ + +/// One Winsock resolver code and the category it must land in. +struct Row +{ + int gaiCode; ///< The `WSA*` value `getaddrinfo` returned. + NetErrorCode code; ///< Its category. +}; + +// `getaddrinfo`'s documented return values, plus `WSANO_DATA` (a name with no address of the asked +// family, which it answers in practice) and `WSANOTINITIALISED`. +constexpr auto Rows = std::array { + Row { .gaiCode = WSAHOST_NOT_FOUND, .code = NetErrorCode::NameNotFound }, + Row { .gaiCode = WSANO_DATA, .code = NetErrorCode::NameNotFound }, + Row { .gaiCode = WSATRY_AGAIN, .code = NetErrorCode::ResolverTemporaryFailure }, + Row { .gaiCode = WSANO_RECOVERY, .code = NetErrorCode::AddressError }, + Row { .gaiCode = WSAEINVAL, .code = NetErrorCode::AddressError }, + Row { .gaiCode = WSATYPE_NOT_FOUND, .code = NetErrorCode::AddressError }, + Row { .gaiCode = WSA_SECURE_HOST_NOT_FOUND, .code = NetErrorCode::AddressError }, + Row { .gaiCode = WSA_IPSEC_NAME_POLICY_ERROR, .code = NetErrorCode::AddressError }, + Row { .gaiCode = WSAEAFNOSUPPORT, .code = NetErrorCode::AddressError }, + Row { .gaiCode = WSAESOCKTNOSUPPORT, .code = NetErrorCode::AddressError }, + Row { .gaiCode = WSA_NOT_ENOUGH_MEMORY, .code = NetErrorCode::ResourceExhausted }, + Row { .gaiCode = WSANOTINITIALISED, .code = NetErrorCode::SystemError }, +}; + +} // namespace + +TEST_CASE("Every Winsock resolver code lands in its category, and the table holds nothing else", + "[net][errors]") +{ + for (auto const& row: Rows) + { + INFO("WSA code " << row.gaiCode); + CHECK(classifyResolverError(row.gaiCode) == row.code); + } + + auto expected = std::map {}; + for (auto const& row: Rows) + expected.emplace(row.gaiCode, row.code); + auto actual = std::map {}; + for (auto const& row: resolverErrorTable()) + actual.emplace(row.gaiCode, row.code); + CHECK(actual == expected); +} + +TEST_CASE("A Winsock resolver code is its own system code", "[net][errors]") +{ + // On Windows the code `getaddrinfo` returns IS the `WSAGetLastError` value, so it is reported as + // the error's system code; POSIX has nothing like it outside `EAI_SYSTEM`. + CHECK(resolverSystemCode(WSAHOST_NOT_FOUND) == WSAHOST_NOT_FOUND); + CHECK(resolverSystemCode(WSATRY_AGAIN) == WSATRY_AGAIN); +} diff --git a/src/core/net/windows/SocketsWin32.cpp b/src/core/net/windows/SocketsWin32.cpp index 6cb68b92..bb4d3241 100644 --- a/src/core/net/windows/SocketsWin32.cpp +++ b/src/core/net/windows/SocketsWin32.cpp @@ -9,15 +9,18 @@ // clang-format on #include +#include #include #include #include #include #include +#include #include #include #include +#include #include #include @@ -178,4 +181,47 @@ std::expected, NetError> adoptFd(EventLoop& /*loop*/, i return std::unexpected(makeNetError(NetErrorCode::Unsupported, 0, "adoptFd on Windows")); } +namespace +{ + /// Every code Winsock's `getaddrinfo` returns, classified: its documented return values, which + /// its `EAI_*` macros spell, plus `WSANO_DATA` (a name with no address, which it answers in + /// practice) and `WSANOTINITIALISED`. `windows/ResolverErrors_test.cpp` holds the table to that + /// list, whole. + constexpr auto ResolverErrors = std::array { + // No such name, or no address for it: WASI's `name-unresolvable`. + ResolverErrorRow { .gaiCode = WSAHOST_NOT_FOUND, .code = NetErrorCode::NameNotFound }, + ResolverErrorRow { .gaiCode = WSANO_DATA, .code = NetErrorCode::NameNotFound }, + // The name server did not answer now: WASI's `temporary-resolver-failure`. + ResolverErrorRow { .gaiCode = WSATRY_AGAIN, .code = NetErrorCode::ResolverTemporaryFailure }, + // The name server answered that it cannot: WASI's `permanent-resolver-failure`. + ResolverErrorRow { .gaiCode = WSANO_RECOVERY, .code = NetErrorCode::AddressError }, + // Refusals of the request itself (`EAI_BADFLAGS`, `EAI_SERVICE`), and the two secure-name + // answers (`EAI_NOSECURENAME`, `EAI_IPSECPOLICY`): permanent. + ResolverErrorRow { .gaiCode = WSAEINVAL, .code = NetErrorCode::AddressError }, + ResolverErrorRow { .gaiCode = WSATYPE_NOT_FOUND, .code = NetErrorCode::AddressError }, + ResolverErrorRow { .gaiCode = WSA_SECURE_HOST_NOT_FOUND, .code = NetErrorCode::AddressError }, + ResolverErrorRow { .gaiCode = WSA_IPSEC_NAME_POLICY_ERROR, .code = NetErrorCode::AddressError }, + // A family or socket type refused (`EAI_FAMILY`, `EAI_SOCKTYPE`): the hints are this + // library's own, so permanent, as on POSIX. + ResolverErrorRow { .gaiCode = WSAEAFNOSUPPORT, .code = NetErrorCode::AddressError }, + ResolverErrorRow { .gaiCode = WSAESOCKTNOSUPPORT, .code = NetErrorCode::AddressError }, + ResolverErrorRow { .gaiCode = WSA_NOT_ENOUGH_MEMORY, .code = NetErrorCode::ResourceExhausted }, + ResolverErrorRow { .gaiCode = WSANOTINITIALISED, .code = NetErrorCode::SystemError }, + }; +} // namespace + +std::span resolverErrorTable() noexcept +{ + return ResolverErrors; +} + +namespace detail +{ + int resolverSystemCode(int gaiCode) noexcept + { + // Winsock's resolver codes are WSAGetLastError values. + return gaiCode; + } +} // namespace detail + } // namespace core::net From 080493985ed92290c11aa0256f10204bdd75bbb2 Mon Sep 17 00:00:00 2001 From: Christian Parpart Date: Thu, 26 Nov 2026 20:33:36 +0100 Subject: [PATCH 06/19] feat(net): endpoints, IpSocketAddress and unconnected TCP sockets Local and remote endpoints with ports, and IpSocketAddress. `IpSocketAddress` is an IPv4 or IPv6 socket address as typed values (octets, host-order segments, port, IPv6 flow label and scope), with `toEndpoint` and `toIpSocketAddress` converting to and from the raw `ResolvedEndpoint`; the two are the only code that knows the sockaddr layouts. `ISocket` gains `localEndpoint()`/`remoteEndpoint()` and `IListener` gains `localEndpoint()`, all non-pure and defaulting to `Unsupported`, so existing implementers keep compiling. The platform sockets (POSIX, IOCP, blocking) and listeners answer through one per-OS `detail::socketEndpoint` (`getsockname`/`getpeername`), `BadHandle` once closed. `SocketDecorator`, the TLS socket and `SplitSocket` forward; `InMemorySocket` reports the endpoints it, or its `InMemorySocketPair`, was created with. Unconnected TCP sockets with bind, connect, listen and options. `openTcpSocket(loop, family)` returns an `ITcpSocket`: a TCP socket that binds to a chosen address, then connects (becoming an `ISocket`) or listens (becoming an `IListener`). Either step consumes it, and every later call answers `BadHandle`. A connect takes the socket when it is called, so a task dropped before it runs closes the socket. - `bind` sets the platform's reuse-address rows first: `SO_REUSEADDR` on POSIX and none on Windows. A port in TIME_WAIT binds again; a port a live listener holds stays `AddressInUse`. - `SocketOption` and the per-platform `socketOptionTable()` cover buffer sizes, the unicast hop limit and the keepalive set. Linux's doubled buffer sizes are a row scale, and the hop limit is `IP_TTL` or `IPV6_UNICAST_HOPS` depending on the family. `option()`/`setOption()` are on `ITcpSocket`, and on `ISocket` and `IListener` with `Unsupported` defaults. The POSIX and IOCP sockets and listeners implement them; `SocketDecorator`, `SplitSocket` and the TLS socket forward them. - IPv6 sockets are IPv6-only on every platform. - The readiness and `ConnectEx` dials are split so they can take a socket the caller opened (`dialReadinessOn`, `dialCompletionOn`), owned by `detail::DialSocket`. POSIX `armKeepAlive` goes through the option rows. Also in this commit: - endpoint docs attach to the right declarations - BlockingSocket endpoints, and closed sockets refuse without the OS - TCP socket options clamp to per-row maxima, and a bound socket refuses a second bind - ask only POSIX for its lowest-free-handle order - name dialCompletionOn's socket and the endpoint calls as clang-tidy's naming rules require on Windows Signed-off-by: Christian Parpart --- .agent/reference/provenance.md | 47 +- src/core/net/BlockingSocket.cpp | 15 + src/core/net/BlockingSocket.hpp | 2 + src/core/net/BlockingSocket_test.cpp | 34 + src/core/net/CMakeLists.txt | 18 + src/core/net/IListener.hpp | 43 + src/core/net/ISocket.cpp | 23 + src/core/net/ISocket.hpp | 39 + src/core/net/ITcpSocket.hpp | 127 +++ src/core/net/IpSocketAddress.cpp | 141 +++ src/core/net/IpSocketAddress.hpp | 89 ++ src/core/net/IpSocketAddress_test.cpp | 230 +++++ src/core/net/ReadinessDial.cpp | 19 +- src/core/net/SocketEndpoints_test.cpp | 244 ++++++ src/core/net/SocketOption.cpp | 83 ++ src/core/net/SocketOption.hpp | 70 ++ src/core/net/SplitSocket.hpp | 29 + src/core/net/TcpSocket.cpp | 169 ++++ src/core/net/TcpSocket_test.cpp | 828 ++++++++++++++++++ src/core/net/Tls.cpp | 28 + src/core/net/TlsSocket_test.cpp | 92 ++ src/core/net/detail/DialPrimitives.hpp | 78 ++ src/core/net/detail/SocketEndpoint.hpp | 33 + src/core/net/detail/SocketOptionAccess.hpp | 120 +++ src/core/net/detail/TcpSocketPrimitives.hpp | 42 + .../net/linux/AcceptedSocketOptions_test.cpp | 109 +++ src/core/net/posix/DialPrimitives.cpp | 12 + src/core/net/posix/PosixListener.cpp | 24 + src/core/net/posix/PosixListener.hpp | 9 + src/core/net/posix/PosixSocket.cpp | 30 + src/core/net/posix/PosixSocket.hpp | 4 + src/core/net/posix/PosixTcpSocket.cpp | 58 ++ src/core/net/posix/SocketOptionTable.cpp | 122 +++ src/core/net/posix/SocketsPosix.cpp | 25 + src/core/net/posix/StreamSocketOptions.cpp | 44 +- src/core/net/testing/InMemorySocket.cpp | 41 +- src/core/net/testing/InMemorySocket.hpp | 36 +- src/core/net/testing/SocketDecorator.hpp | 41 +- src/core/net/windows/DialPrimitives.cpp | 10 +- src/core/net/windows/IocpDial.cpp | 45 +- src/core/net/windows/IocpSocket.cpp | 56 ++ src/core/net/windows/IocpSocket.hpp | 13 + src/core/net/windows/IocpTcpSocket.cpp | 70 ++ src/core/net/windows/SocketOptionTable.cpp | 109 +++ src/core/net/windows/SocketsWin32.cpp | 28 + 45 files changed, 3464 insertions(+), 65 deletions(-) create mode 100644 src/core/net/ITcpSocket.hpp create mode 100644 src/core/net/IpSocketAddress.cpp create mode 100644 src/core/net/IpSocketAddress.hpp create mode 100644 src/core/net/IpSocketAddress_test.cpp create mode 100644 src/core/net/SocketEndpoints_test.cpp create mode 100644 src/core/net/SocketOption.cpp create mode 100644 src/core/net/SocketOption.hpp create mode 100644 src/core/net/TcpSocket.cpp create mode 100644 src/core/net/TcpSocket_test.cpp create mode 100644 src/core/net/detail/SocketEndpoint.hpp create mode 100644 src/core/net/detail/SocketOptionAccess.hpp create mode 100644 src/core/net/detail/TcpSocketPrimitives.hpp create mode 100644 src/core/net/linux/AcceptedSocketOptions_test.cpp create mode 100644 src/core/net/posix/PosixTcpSocket.cpp create mode 100644 src/core/net/posix/SocketOptionTable.cpp create mode 100644 src/core/net/windows/IocpTcpSocket.cpp create mode 100644 src/core/net/windows/SocketOptionTable.cpp diff --git a/.agent/reference/provenance.md b/.agent/reference/provenance.md index c391d921..afbd4eac 100644 --- a/.agent/reference/provenance.md +++ b/.agent/reference/provenance.md @@ -273,6 +273,22 @@ others in notes. | `src/core/net/ExecutorAddressResolver.hpp` | origin: core-cpp | - | - | P13 Task 7: the resolver that owns no thread | | `src/core/net/ExecutorAddressResolver.cpp` | origin: core-cpp | - | - | P13 Task 7 | | `src/core/net/ExecutorAddressResolver_test.cpp` | origin: core-cpp | - | - | P13 Task 7 | +| `src/core/net/IpSocketAddress.hpp` | origin: core-cpp | - | - | P13 Task 8: typed IPv4/IPv6 socket addresses, and their conversions to and from `ResolvedEndpoint` | +| `src/core/net/IpSocketAddress.cpp` | origin: core-cpp | - | - | P13 Task 8 | +| `src/core/net/IpSocketAddress_test.cpp` | origin: core-cpp | - | - | P13 Task 8 | +| `src/core/net/SocketEndpoints_test.cpp` | origin: core-cpp | - | - | P13 Task 8: `localEndpoint`/`remoteEndpoint` over loopback, decorators and the in-memory pair | +| `src/core/net/ITcpSocket.hpp` | origin: core-cpp | - | - | P13 Task 9: an unconnected TCP socket -- bind, then connect or listen -- and `openTcpSocket` | +| `src/core/net/SocketOption.hpp` | origin: core-cpp | - | - | P13 Task 9: `SocketOption`, `OptionScale` and the per-platform `socketOptionTable()` | +| `src/core/net/SocketOption.cpp` | origin: core-cpp | - | - | P13 Task 9: the one interpreter of the option rows | +| `src/core/net/TcpSocket.cpp` | origin: core-cpp | - | - | P13 Task 9: the `ITcpSocket` lifecycle, written once over the per-platform primitives | +| `src/core/net/TcpSocket_test.cpp` | origin: core-cpp | - | - | P13 Task 9 | +| `src/core/net/detail/SocketOptionAccess.hpp` | origin: core-cpp | - | - | P13 Task 9: option reads and writes through the rows, and the `int`-option calls beneath them | +| `src/core/net/detail/TcpSocketPrimitives.hpp` | origin: core-cpp | - | - | P13 Task 9: socket creation, `bind` and `listen`, defined per platform | +| `src/core/net/posix/PosixTcpSocket.cpp` | origin: core-cpp | - | - | P13 Task 9 | +| `src/core/net/posix/SocketOptionTable.cpp` | origin: core-cpp | - | - | P13 Task 9. Chooses constants within the platform family by `#if` in the data (Ruling R42, P13 ruling R11): `__linux__` for the doubled buffer sizes, `TCP_KEEPIDLE` against macOS's `TCP_KEEPALIVE`; fix round 1: per-row maxima, the buffer maximum chosen per kernel (`__linux__`, `__APPLE__`) | +| `src/core/net/windows/IocpTcpSocket.cpp` | origin: core-cpp | - | - | P13 Task 9 | +| `src/core/net/windows/SocketOptionTable.cpp` | origin: core-cpp | - | - | P13 Task 9; the reuse-address rows are empty by P13 ruling R17; fix round 1: per-row maxima | +| `src/core/net/linux/AcceptedSocketOptions_test.cpp` | origin: core-cpp | - | - | P13 Task 9 fix round 1: what a Linux listener's accepted connections inherit | | `src/core/net/HostDrivenBackend.cpp` | origin: core-cpp | - | - | its body: the coalescing (several wakes before the host gets a turn are one pump), the clamp of a deadline already past to a zero delay, and the schedule cleared BEFORE a pump runs so the turn it drives can arm the next one | | `src/core/net/HostDrivenBackend.hpp` | origin: core-cpp | - | - | Task B3: the IoBackend for a loop that is PUMPED rather than one that blocks. Portable, and tested on every platform over testing::ManualHostScheduler -- the browser is one of its hosts, not its definition | | `src/core/net/HostDrivenBackend_test.cpp` | origin: core-cpp | - | - | Task B3: the host-driven backend over testing::ManualHostScheduler, on every platform including Emscripten -- the alternative leaves its behaviour observable only in a node run | @@ -319,9 +335,9 @@ others in notes. | `src/core/net/HttpServer_test.cpp` | contour-terminal/contour | `src/net/HttpServer_test.cpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | namespaces and includes; the `for` over `find()` positions is a `while` Task B8: `localPort` is `boundPort` Task B10: a case for the handshake `serve` awaits; 0.5.0, core-cpp#35: a refusal over an unread body reaches the client and ends in EOF; 0.6.0: `serve` takes its loop; cases for the accept policy over `testing::FailingListener` | | `src/core/net/ICompletionPort.hpp` | origin: core-cpp | - | - | Task B7a: the seam a completion-based backend lends its sockets, and the ONE place a handle is associated with a port -- which is what lets guarantee G4 be asserted rather than left to `CreateIoCompletionPort`, whose refusal of a second association is `ERROR_INVALID_PARAMETER` and so indistinguishable from six ordinary mistakes. fastcached had `IocpReactor::AttachHandle` and `NativeHandle()` on the reactor itself, so every consumer of the port also had the reactor; nothing upstream has the record or the refusal. Declared on every platform, not behind `#if defined(_WIN32)` as the design spec sketches it, because a public header that changes shape per platform is one a consumer's build can disagree with this one about (`.agent/rules/platform.md`) Task B7b: `beginOperation` and `withdrawOperation`, typed `void*` so the header stays portable -- the record that lets a port tell an owner's packet from its own. | | `src/core/net/IHostScheduler.hpp` | origin: core-cpp | - | - | Task B3: the one thing a host event loop has to lend core-cpp's -- `callAfter(delay, fn, state)` and nothing else. The design spec names it (Part I §2); nothing upstream has it, because neither contour nor fastcached has a loop that does not own its thread | -| `src/core/net/IListener.hpp` | contour-terminal/contour | `src/net/IListener.hpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | namespaces and includes only Task B8: `localPort` is `boundPort` (the spec's rename map), and `AcceptResult` becomes an ALIAS of `SocketResult` rather than a second spelling of the same type -- accept and connect answer the same question; 0.6.0: `close()` is the base class's and fires `closeToken()`, as the destructor does; an implementation overrides `doClose()` | +| `src/core/net/IListener.hpp` | contour-terminal/contour | `src/net/IListener.hpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | namespaces and includes only Task B8: `localPort` is `boundPort` (the spec's rename map), and `AcceptResult` becomes an ALIAS of `SocketResult` rather than a second spelling of the same type -- accept and connect answer the same question; 0.6.0: `close()` is the base class's and fires `closeToken()`, as the destructor does; an implementation overrides `doClose()`; 0.24.0 (P13 Task 8): `localEndpoint()`, defaulting to `Unsupported`; P13 Task 9: `option()`/`setOption()`, defaulting to `Unsupported` | | `src/core/net/ISocket.cpp` | origin: core-cpp | - | - | Task B6: the out-of-line defaults `ISocket`'s awaitable signatures need. `readWithFd` and `writeVectored` are coroutine-backed here, because a base class has nowhere frame-free to keep an inner operation -- every transport that can do better overrides them, and all of the ones here do | -| `src/core/net/ISocket.hpp` | contour-terminal/contour | `src/net/ISocket.hpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | Task B6 merged fastcached's `src/FastCache/Net/ISocket.hpp` (`0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21`) into it: every operation is now a frame-free `ResultAwaitable` rather than an `async::Task`, and `writeVectored`, `waitReadable`, `cancelRead`, `shutdownWrite` and `setReceiveDeadline` arrive from there with their reasoning. contour's `readWithFd` and the EOF latch on `isClosed` are kept | +| `src/core/net/ISocket.hpp` | contour-terminal/contour | `src/net/ISocket.hpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | Task B6 merged fastcached's `src/FastCache/Net/ISocket.hpp` (`0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21`) into it: every operation is now a frame-free `ResultAwaitable` rather than an `async::Task`, and `writeVectored`, `waitReadable`, `cancelRead`, `shutdownWrite` and `setReceiveDeadline` arrive from there with their reasoning. contour's `readWithFd` and the EOF latch on `isClosed` are kept; 0.24.0 (P13 Task 8): `localEndpoint()`/`remoteEndpoint()`, defaulting to `Unsupported`; P13 Task 9: `option()`/`setOption()`, defaulting to `Unsupported` | | `src/core/net/ITlsContext.hpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/TlsWrap.hpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B11: `WrapTls` as `wrapTls`, over contour's `ITlsContext` (moved here from `src/net/Tls.hpp` at `6777ff05014f8ff163b071e8b0e942830119db80`) instead of a preprocessor switch; `certificateFingerprint` from upstream's `TlsContext` | | `src/core/net/ITlsSession.hpp` | origin: core-cpp | - | - | the per-connection TLS queries: channel binding, peer fingerprint, negotiated version | | `src/core/net/InterruptibleSleep.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Async/InterruptibleSleep.cpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B5. Upstream's `while` over `NextWakeStep` is gone: the wait parks once and a stop callback wakes it. New here is `TokenDelayAwaiter`, which watches TWO tokens -- the supplied one and the awaiting flow's own -- because `DelayAwaiter` reads its token out of the parking promise and this function is told which token to watch | @@ -353,9 +369,9 @@ others in notes. | `src/core/net/SocketRegistration_test.cpp` | origin: core-cpp | - | - | v0.2.0: counts the backend calls a parked `PosixSocket` read and write cost, the guard for the registration a socket keeps for its life (`RegistrationLifetime::UntilClosed`) | | `src/core/net/Socket_test.cpp` | contour-terminal/contour | `src/net/Socket_test.cpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | namespaces and includes only Task B8: `localPort` is `boundPort` | | `src/core/net/Sockets.hpp` | contour-terminal/contour | `src/net/Sockets.hpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | namespaces and includes only Task B8: `ListenOptions` and `listen(loop, ListenOptions)` (the spec's rename map for `*Listener::Bind`), `adoptListener`, and a `connect` overload taking an `IAsyncAddressResolver*` and `DialOptions`. The positional `listen` stays as a forwarder. `connect` no longer resolves on the caller's thread, which is the behaviour change its callers inherit; both `connect` overloads take the host as `std::string`, since a lazy coroutine's `string_view` parameter can dangle before the body runs; `listenUnix()` and `connectUnix()` document their path as UTF-8; `listenUnix()` documents `NetErrorCode::AddressError` for a path that is not UTF-8 on Windows | -| `src/core/net/SplitSocket.hpp` | contour-terminal/contour | `src/net/SplitSocket.hpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | namespaces and includes only Task B10: `close()` checks a liveness token between its two retirements | +| `src/core/net/SplitSocket.hpp` | contour-terminal/contour | `src/net/SplitSocket.hpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | namespaces and includes only Task B10: `close()` checks a liveness token between its two retirements; 0.24.0 (P13 Task 8): forwards the endpoints from the read half; P13 Task 9: `option()`/`setOption()` forward to the read half | | `src/core/net/Timers_test.cpp` | origin: core-cpp | - | - | Task B5: `addTimer`/`cancelTimer`, which have no upstream -- fastcached had no frameless timer, only `DeadlineTimer`'s coroutine. It holds the firing order ACROSS the two kinds of park, the cancellation window between step 5 queueing a due timer and step 2 running it, and the measurement of what lazy deadline-heap pruning costs (Task B4's report, concern 4) | -| `src/core/net/Tls.cpp` | contour-terminal/contour | `src/net/Tls.cpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | namespaces and includes; no `NOLINT`: contour's three `NOLINTNEXTLINE(readability-identifier-naming)` on `HandshakeGate`'s `await_*` hooks are gone, since `.clang-tidy` exempts the hook names; the `core::net_tls` target, which links OpenSSL PRIVATE Task B11 merged fastcached's `src/FastCache/Net/TlsSocket.cpp` and `TlsContext.cpp` (`0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21`) into it: `ERR_clear_error()` before every classified `SSL_*` call, the `SSL_peek` `waitReadable`, an eager `handshakeIfNeeded`, the P-256 generator with subjectAltNames, the certificate fingerprint; and wrote the `close_notify` half-close, one outbound flush at a time, chain serving and the random serial; `readFile()`'s refusal spells the path through `core::pathToUtf8()` | +| `src/core/net/Tls.cpp` | contour-terminal/contour | `src/net/Tls.cpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | namespaces and includes; no `NOLINT`: contour's three `NOLINTNEXTLINE(readability-identifier-naming)` on `HandshakeGate`'s `await_*` hooks are gone, since `.clang-tidy` exempts the hook names; the `core::net_tls` target, which links OpenSSL PRIVATE Task B11 merged fastcached's `src/FastCache/Net/TlsSocket.cpp` and `TlsContext.cpp` (`0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21`) into it: `ERR_clear_error()` before every classified `SSL_*` call, the `SSL_peek` `waitReadable`, an eager `handshakeIfNeeded`, the P-256 generator with subjectAltNames, the certificate fingerprint; and wrote the `close_notify` half-close, one outbound flush at a time, chain serving and the random serial; `readFile()`'s refusal spells the path through `core::pathToUtf8()`; P13 Task 9: the TLS socket forwards `option()`/`setOption()` to the inner transport | | `src/core/net/Tls.hpp` | contour-terminal/contour | `src/net/Tls.hpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | namespaces and includes; the `core::net_tls` target Task B11: `SelfSignedOptions` (fastcached's `CreateSelfSigned` parameters, without its hard-coded common name), `makeTlsServerContextFromFiles`, `certificateFingerprint`; `ITlsContext` moved to `ITlsContext.hpp` | | `src/core/net/Tls_test.cpp` | contour-terminal/contour | `src/net/Tls_test.cpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | namespaces and includes; the two two-reactor cases make the client context before the server thread starts, so no `REQUIRE` can unwind past a joinable `std::thread` (`.agent/rules/testing.md`); the `core-cpp.net_tls` test Task B8: `localPort` is `boundPort` Task B11: `generateSelfSignedCertificate` takes `SelfSignedOptions` | | `src/core/net/TlsContext_test.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/TlsContext_test.cpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B11: onto core-cpp's factories; certificates generated at run time rather than read from `testdata/tls/`, whose committed certificate expires; plus the common-name, chain, file-loading, `wrapTls` and `constantTimeEquals` cases | @@ -372,6 +388,7 @@ others in notes. | `src/core/net/bsd/KqueueBackend.cpp` | contour-terminal/contour | `src/net/KqueueEventSource.cpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | Task B3 rewrote it behind `IoBackend`: readiness is DISPATCHED to the callbacks on the `ReadinessHandler` a caller registers, instead of being collected into a `WaitOutcome` of tokens for the caller to route. The `EV_RECEIPT` handling is unchanged and still load-bearing; what changed is where its verdict goes -- a refused filter is now a `NetError` carrying the kernel's errno rather than an invalid token (fastcached#1054) Task B7b: refuses `HandleKind::Completion` by name with `Unsupported`.; 0.6.0: a refused registration is classified by the one socket-error table | | `src/core/net/bsd/KqueueBackend.hpp` | contour-terminal/contour | `src/net/KqueueEventSource.hpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | Task B3: `KqueueEventSource` renamed `KqueueBackend`. Task B3 rewrote it behind `IoBackend`: readiness is DISPATCHED to the callbacks on the `ReadinessHandler` a caller registers, instead of being collected into a `WaitOutcome` of tokens for the caller to route; `attach` here registers NOTHING with the kernel, and says so -- kqueue has no 'add with no filters' operation, so only `setInterest` can answer whether the kernel accepted the descriptor (fastcached#1057) | | `src/core/net/detail/ParkedCall.hpp` | origin: core-cpp | - | - | P13 Task 7: `ParkedCall`, extracted from `ThreadedAddressResolver.cpp` and shared with `ExecutorAddressResolver` | +| `src/core/net/detail/SocketEndpoint.hpp` | origin: core-cpp | - | - | P13 Task 8: `getsockname`/`getpeername` into a `ResolvedEndpoint`, defined per platform | | `src/core/net/detail/ParkedCall_test.cpp` | origin: core-cpp | - | - | P13 Task 7 fix round 1: first answer wins, the late answer kept and taken once | | `src/core/net/detail/ParkId.hpp` | origin: core-cpp | - | - | Task B13: `ParkId` and its hash, moved out of `detail/ParkTable.hpp` so that `IoAwaitable.hpp` -- and so `ISocket.hpp` -- no longer includes the park table for one strong integer (core-cpp#43) | | `src/core/net/detail/ParkTable.hpp` | origin: core-cpp | - | - | Task B4: `ParkId`, `ParkEntry` and the table. fastcached had no unified one -- a submission queue, a timer heap and each reactor's own descriptor map -- and cancellation therefore meant something slightly different in each. One table, one id space that never wraps, and the id IS the generation check: a cancel for a park that has gone resolves to nothing Task B13: `ParkId` moves out to `detail/ParkId.hpp` Parity lane (v0.2.0): the parks are keyed in `ParkMap`, an open-addressing table with backward-shift deletion, instead of `std::unordered_map`; taken parks are recycled; a park on a handle's lifetime registration points at its `HandleWatch` rather than being filed by handle, and `fileByHandle` files one displaced from its slot | @@ -401,9 +418,9 @@ others in notes. | `src/core/net/posix/FdUtils.hpp` | contour-terminal/contour | `src/net/posix/FdUtils.hpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | namespaces and includes; never had a file-wide guard; it keeps the `#ifndef MSG_NOSIGNAL` fallback and the `#if defined(SOCK_NONBLOCK) && defined(SOCK_CLOEXEC)` branch, which choose within POSIX | | `src/core/net/posix/PollBackend.cpp` | contour-terminal/contour | `src/net/PollEventSource.cpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | its POSIX half (Ruling R40). Task B3 rewrote it behind `IoBackend`: readiness is DISPATCHED to the callbacks on the `ReadinessHandler` a caller registers, instead of being collected into a `WaitOutcome` of tokens for the caller to route; the muting trick -- a negative descriptor in the `pollfd`, because `events == 0` does not stop the kernel reporting POLLHUP/POLLERR/POLLNVAL -- is kept verbatim, and POLLNVAL now reads as `Readiness::Failed` Task B7b: refuses `HandleKind::Completion` by name with `Unsupported`. | | `src/core/net/posix/PollBackend.hpp` | contour-terminal/contour | `src/net/PollEventSource.hpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | Task B3: `PollEventSource` renamed `PollBackend`. Task B3 rewrote it behind `IoBackend`: readiness is DISPATCHED to the callbacks on the `ReadinessHandler` a caller registers, instead of being collected into a `WaitOutcome` of tokens for the caller to route. Its Windows half is a class of its own now (`windows/WfmoBackend.hpp`), so this one is POSIX-only and private: a program reaches it through `makeBackend(BackendKind::Poll)` | -| `src/core/net/posix/PosixListener.cpp` | contour-terminal/contour | `src/net/posix/PosixListener.cpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | namespaces and includes; the `addrinfo` walk is a `while` that steps to the next candidate first; no file-wide `#ifndef _WIN32` guard: `SOURCES_POSIX` selects the file (Ruling R42) Task B8: `adopt`, which asks the KERNEL for the port through `detail::portOfSockaddr` rather than taking one on trust -- the caller adopting a descriptor is exactly the caller that does not know which port it is. v0.2.0: `ListenOptions::sharing` sets `SO_REUSEPORT_LB` where the constant is defined and `SO_REUSEPORT` elsewhere -- the one `#if`, on a constant an SDK may lack -- and the accepted sockets' buffer sizes are asked of the listening socket before `listen`; `native()`; 0.6.0: `doClose()`; a failed `socket` is classified by the one socket-error table | +| `src/core/net/posix/PosixListener.cpp` | contour-terminal/contour | `src/net/posix/PosixListener.cpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | namespaces and includes; the `addrinfo` walk is a `while` that steps to the next candidate first; no file-wide `#ifndef _WIN32` guard: `SOURCES_POSIX` selects the file (Ruling R42) Task B8: `adopt`, which asks the KERNEL for the port through `detail::portOfSockaddr` rather than taking one on trust -- the caller adopting a descriptor is exactly the caller that does not know which port it is. v0.2.0: `ListenOptions::sharing` sets `SO_REUSEPORT_LB` where the constant is defined and `SO_REUSEPORT` elsewhere -- the one `#if`, on a constant an SDK may lack -- and the accepted sockets' buffer sizes are asked of the listening socket before `listen`; `native()`; 0.6.0: `doClose()`; a failed `socket` is classified by the one socket-error table; P13 Task 9: `option()`/`setOption()` | | `src/core/net/posix/PosixListener.hpp` | contour-terminal/contour | `src/net/posix/PosixListener.hpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | namespaces and includes; no file-wide `#ifndef _WIN32` guard: `SOURCES_POSIX` selects the file (Ruling R42) Task B8: `localPort` is `boundPort`, and `adopt` joins `bind` for a descriptor this process did not create; 0.6.0: `doClose()`, and `close(FdWakePolicy)` is `closeWith` | -| `src/core/net/posix/PosixSocket.cpp` | contour-terminal/contour | `src/net/posix/PosixSocket.cpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | Task B6 rewrote it frame-free over fastcached's `src/FastCache/Net/EpollSocket.cpp` and `src/FastCache/Net/KqueueSocket.cpp` (`0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21`): the retry loop runs in a frameless readiness callback rather than in the awaiting coroutine. contour's `recvmsg` SCM_RIGHTS walk, its `ENOTSOCK`/`EIO` PTY handling, the stale-`errno` zero-write fix and the `SO_NOSIGPIPE` option are kept unchanged; the `MSG_PEEK` probe, the vectored cursor and the detach-then-complete ordering are fastcached's. No file-wide `#ifndef _WIN32` guard: `SOURCES_POSIX` selects the file (Ruling R42) Perf lane (v0.2.0): its parks ask for `RegistrationLifetime::UntilClosed`, one registration for the socket's life, and `armWrite` arms both write verbs. Upstream registers per operation; a re-sync from it would bring that back, which `SocketRegistration_test` catches. | +| `src/core/net/posix/PosixSocket.cpp` | contour-terminal/contour | `src/net/posix/PosixSocket.cpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | Task B6 rewrote it frame-free over fastcached's `src/FastCache/Net/EpollSocket.cpp` and `src/FastCache/Net/KqueueSocket.cpp` (`0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21`): the retry loop runs in a frameless readiness callback rather than in the awaiting coroutine. contour's `recvmsg` SCM_RIGHTS walk, its `ENOTSOCK`/`EIO` PTY handling, the stale-`errno` zero-write fix and the `SO_NOSIGPIPE` option are kept unchanged; the `MSG_PEEK` probe, the vectored cursor and the detach-then-complete ordering are fastcached's. No file-wide `#ifndef _WIN32` guard: `SOURCES_POSIX` selects the file (Ruling R42) Perf lane (v0.2.0): its parks ask for `RegistrationLifetime::UntilClosed`, one registration for the socket's life, and `armWrite` arms both write verbs. Upstream registers per operation; a re-sync from it would bring that back, which `SocketRegistration_test` catches.; P13 Task 9: `option()`/`setOption()` | | `src/core/net/posix/PosixSocket.hpp` | contour-terminal/contour | `src/net/posix/PosixSocket.hpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | Task B6 rewrote it as ONE socket replacing fastcached's `src/FastCache/Net/EpollSocket.hpp` and `src/FastCache/Net/KqueueSocket.hpp` (`0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21`), which differed from each other only in the reactor type they named. The per-direction operation structs are theirs; there is no `Impl` pimpl, because the multiplexer is `IoBackend`'s and nothing platform-shaped is left to hide. No file-wide `#ifndef _WIN32` guard: `SOURCES_POSIX` selects the file (Ruling R42) | | `src/core/net/posix/SocketsPosix.cpp` | contour-terminal/contour | `src/net/posix/SocketsPosix.cpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | namespaces and includes; `ensureWinsockInitialized()` is `core::platform`'s; the `addrinfo` walk is a `while` that steps to the next candidate first; no file-wide `#ifndef _WIN32` guard: `SOURCES_POSIX` selects the file (Ruling R42) Task B8: `connect` is gone from here -- it is portable now, over `makeConnector`, in `Sockets.cpp` -- and `listen(loop, ListenOptions)` plus `adoptListener` arrive. `connectUnix` is untouched: an AF_UNIX dial resolves no name; 0.6.0: the AF_UNIX dial classifies its errors by the one socket-error table; 0.24.0 (P13): the `EAI_*` half of `resolverErrorTable()` and `detail::resolverSystemCode` | | `src/core/net/TlsCancelRead_test.cpp` | origin: core-cpp | - | - | Task B11 fix round 1: `cancelRead` during a handshake a read drives. POSIX-only until Task B13 gave `WindowsSocket` its `cancelRead`; it runs on every platform since | @@ -430,10 +447,10 @@ others in notes. | `src/core/net/windows/IocpBackend.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Async/IocpReactor.cpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B7a. The port, its creation with one concurrent thread, `PostQueuedCompletionStatus` as the wake and the `GetQueuedCompletionStatusEx` batch loop are upstream's; everything else is new, because upstream's was a REACTOR (its own timer heap, its own submission queue, its own run loop) and this is the one blocking primitive an `EventLoop` drives. New here: the three readiness bridges a port has no concept of -- a thread-pool wait for a waitable HANDLE, a zero-byte `WSARecv` for socket readability (`src/FastCache/Net/IocpSocket.cpp:555-561` at the same SHA), `WSAEventSelect` plus the first bridge for writability -- the per-arm `Operation` node that is stood down rather than reused (fastcached#710, #884), and the refcounted `Slot` every `lpOverlapped` points into Task B7b: an OWNER's operation is routed rather than dropped -- recognised by the record `ICompletionPort::beginOperation` made, marked completed, reported to the `HandleKind::Completion` park naming it (level-triggered until the park is taken), and handed to its dequeue hook last; the teardown drain waits for these too. | | `src/core/net/windows/IocpBackend.hpp` | LASTRADA-Software/fastcached | `src/FastCache/Async/IocpReactor.hpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B7a. `IocpReactor` becomes an `IoBackend`: what survives is the one-port-one-thread rule (guarantee G1), the association rule (G4) and the completion-key discipline. `IocpStatus`, `IocpCompletion`, the timer heap and the `_posted` side table do not -- a backend here owns no work, so there is nothing to abandon, and the NTSTATUS conversion belongs to the socket that has the SOCKET to hand `WSAGetOverlappedResult`. `WaitBridge` is new and is injected rather than probed at the point of use, so the thread-pool fallback is exercised on a machine where the kernel path is available Task B7b: `beginOperation`/`withdrawOperation` and `issuedOperations()`. | | `src/core/net/windows/IocpBackend_test.cpp` | origin: core-cpp | - | - | Task B7a: the properties only a completion-based backend has -- both waitable-handle bridges, `HandleKind::Socket` (which no other backend can be handed), and a completion arriving after its registration is freed. Deliberately NOT fastcached's `Async/IocpReactor_test.cpp`: its two cases ask whether a submission resumes on the reactor thread and whether a scheduled timer fires, which here are `EventLoop`'s and are covered backend-agnostically by `EventLoop_test.cpp` and `Timers_test.cpp`. Its `Net/IocpSocket_test.cpp` is 13 cases about `IocpSocket` and `IocpListener`, which arrive with Task B7b Task B7b: those 13 cases are `windows/IocpSocket_test.cpp` now. | -| `src/core/net/windows/IocpDial.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/IocpDial.hpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B7b: `detail::dialCompletion`, one candidate as an overlapped `ConnectEx`, and the connector's dial wherever the loop lends a completion port. Upstream's `ConnectOp`/`ConnectPark`/`SettleConnect` become `detail::CompletionWait`, shared with the accept; the bind to the family's wildcard, the `ConnectEx` fetch and `SO_UPDATE_CONNECT_CONTEXT` are upstream's (with `Net/IocpConnector.cpp` at the same SHA). The rule upstream stated and this keeps: the completion is the single writer of the outcome, so a deadline or a stop calls `CancelIoEx` and waits. What changed is WHY the wait is safe: upstream's op lived in the dialling frame and was safe only because the frame waited; here it lives on the heap and holds its own share until the port dequeues it, so a frame destroyed mid-dial is as safe as one that waited | +| `src/core/net/windows/IocpDial.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/IocpDial.hpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B7b: `detail::dialCompletion`, one candidate as an overlapped `ConnectEx`, and the connector's dial wherever the loop lends a completion port. Upstream's `ConnectOp`/`ConnectPark`/`SettleConnect` become `detail::CompletionWait`, shared with the accept; the bind to the family's wildcard, the `ConnectEx` fetch and `SO_UPDATE_CONNECT_CONTEXT` are upstream's (with `Net/IocpConnector.cpp` at the same SHA). The rule upstream stated and this keeps: the completion is the single writer of the outcome, so a deadline or a stop calls `CancelIoEx` and waits. What changed is WHY the wait is safe: upstream's op lived in the dialling frame and was safe only because the frame waited; here it lives on the heap and holds its own share until the port dequeues it, so a frame destroyed mid-dial is as safe as one that waited; P13 Task 9: split into `dialCompletion` (makes the socket) and `dialCompletionOn` (takes one, possibly bound, for `ITcpSocket`) | | `src/core/net/windows/IocpDial_test.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/IocpConnector_test.cpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B7b: rewritten rather than ported -- upstream's three cases are about `ParkedWork` ownership inside `IocpReactor`, which here is `EventLoop`'s. What is kept is the first one (a ConnectEx dial connects and moves bytes); added are the IOCP leg of the refused-connect case B8's hand-off asked for (the refusal observed as the completion of an operation the port held), the deadline that cancels and lets the completion report, and the three stop routes `ReadinessDial_test` has | | `src/core/net/windows/IocpOperation.hpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/IocpStatus.hpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B7b: `completionError` is upstream's `Detail::WsaErrorOf` -- the closed-socket judgement, the `WSAGetOverlappedResult` conversion and the warning-severity-is-success rule, each kept with its reason. `IocpOperation` replaces upstream's `IocpCompletion` (`Async/IocpReactor.hpp`), and not by renaming: upstream's carried a dispatch pointer the reactor CALLED, which resumed the waiter from inside the dequeue; here the port only marks the operation completed and reports the `HandleKind::Completion` park naming it, so the loop resumes in turn step 2 (Rule 1). The dequeue hook that remains only lets go. `CompletionWait` is new, from upstream's `ConnectOp`/`ConnectPark` shape | -| `src/core/net/windows/IocpSocket.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/IocpSocket.cpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B7b, rewritten onto `ISocket`'s frame-free awaitables. Kept, each cited where it lives: the operation holds itself and never the socket (fastcached#465, `Op::inFlight`/`Op::self` collapsed into one self share per node), a node the kernel still owns is stood down rather than re-armed (#884), `cancelRead` settles a real read and retires a probe inline, the zero-byte receive plus `MSG_PEEK` (`:327-334`, `:555-561`), `SO_UPDATE_ACCEPT_CONTEXT` after `AcceptEx` (#1556) and `GetAcceptExSockaddrs` for the peer. New: a stop, a receive deadline or a dial deadline cancels the operation and lets the completion report; `close()` resolves a parked operation inline and a listener's `close()` resolves a parked accept; a non-overlapped attempt before each operation, so bytes already there cost no operation and no turn; `setReceiveDeadline`; `shutdownWrite` as an awaitable with its precondition asserted; `SO_EXCLUSIVEADDRUSE` on the listener; 0.6.0: `IocpListener::doClose()`; an AF_UNIX `bind` or `listen` failure goes through `fromWinsockError`; `bindUnix()` and `close()` delete the socket file with `DeleteFileW()` by its UTF-8 name (`core::pathFromUtf8()`), not `DeleteFileA()`; `bindUnix()` converts its path once, through `detail::unixSocketFile()`, and refuses one that is not UTF-8 as `NetErrorCode::AddressError` | +| `src/core/net/windows/IocpSocket.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/IocpSocket.cpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B7b, rewritten onto `ISocket`'s frame-free awaitables. Kept, each cited where it lives: the operation holds itself and never the socket (fastcached#465, `Op::inFlight`/`Op::self` collapsed into one self share per node), a node the kernel still owns is stood down rather than re-armed (#884), `cancelRead` settles a real read and retires a probe inline, the zero-byte receive plus `MSG_PEEK` (`:327-334`, `:555-561`), `SO_UPDATE_ACCEPT_CONTEXT` after `AcceptEx` (#1556) and `GetAcceptExSockaddrs` for the peer. New: a stop, a receive deadline or a dial deadline cancels the operation and lets the completion report; `close()` resolves a parked operation inline and a listener's `close()` resolves a parked accept; a non-overlapped attempt before each operation, so bytes already there cost no operation and no turn; `setReceiveDeadline`; `shutdownWrite` as an awaitable with its precondition asserted; `SO_EXCLUSIVEADDRUSE` on the listener; 0.6.0: `IocpListener::doClose()`; an AF_UNIX `bind` or `listen` failure goes through `fromWinsockError`; `bindUnix()` and `close()` delete the socket file with `DeleteFileW()` by its UTF-8 name (`core::pathFromUtf8()`), not `DeleteFileA()`; `bindUnix()` converts its path once, through `detail::unixSocketFile()`, and refuses one that is not UTF-8 as `NetErrorCode::AddressError`; P13 Task 9: `option()`/`setOption()` on `IocpSocket` and `IocpListener` | | `src/core/net/windows/IocpSocket.hpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/IocpSocket.hpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B7b. `IocpAttachment` becomes `IocpAssociation`; `IsAttached()` goes, because a socket the port would not take answers every operation with the refusal instead (a constructed object is usable); `IocpListener::Bind`/`Adopt` become `bind`/`adopt` answering `std::expected`, and `adopt` adopts rather than refusing, because core-cpp's `adoptListener` is a public verb on every platform; 0.6.0: `IocpListener::doClose()`; `IocpListener::_path` is a `std::filesystem::path`, converted from UTF-8 in `bindUnix()` so the `noexcept` `close()` deletes by it; `bindUnix()` documents `NetErrorCode::AddressError` for a path that is not UTF-8 | | `src/core/net/windows/IocpSocket_test.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/IocpSocket_test.cpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B7b. Upstream's 13 cases, rewritten onto an `EventLoop` and parking real flows, because an operation here is issued when AWAITED rather than in the verb: the round trip, the listener that releases its socket without `close`, the AcceptEx/WSARecv/WSASend in flight at teardown (#465), both `cancelRead` halves and the two #884 races, the abort and the reset each converted rather than tabled. The `Adopt` refusal is dropped (core-cpp's adopt adopts; `windows/AdoptListener_test.cpp` covers it). Added: the default backend and the factories following the loop, `close()` resolving inline, a flow stop that keeps received bytes, the receive-deadline contract, and a completion resuming in the loop's turn rather than inside the backend's walk, the abandoned read that never reaches the caller's buffer, an accept destroyed or stopped while parked leaving the next client to the next accept, the overlapped write's bytes checked across the 256KiB copy bound, and (Release only) a write armed over a parked one keeping it reachable | | `src/core/net/windows/IocpCanary.cpp` | origin: core-cpp | - | - | Task B7a: the two refusals that are assertions and so cannot be provoked from inside a Catch case -- a second thread dequeuing the port (G1) and a handle associated with one port twice (G4). A program per refusal, each judged by its own stderr marker, in the shape `HostDrivenCanary.cpp` established. Upstream asserted neither: fastcached's `IsOnWorkerThread` existed but nothing violated it in a test | @@ -464,12 +481,12 @@ others in notes. | `src/core/net/IConnector.hpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/IConnector.hpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B8. `Connect` is `connect`; `DialOptions` is declared here, which is where upstream keeps it too -- `Net/DialOptions.*` does not exist at the pin. `makeConnector(EventLoop&, IAsyncAddressResolver&)` is new and replaces `Net/PlatformConnector.hpp` | | `src/core/net/KeepAlive.hpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/KeepAlive.hpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B8. The namespace, and the upstream issue links restated as the facts they carried rather than as URLs into another project's tracker | | `src/core/net/ReadinessDial.hpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/ReactorDial.hpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B8. **De-templatised.** Upstream's `DialReadiness` was templated on a `{Reactor, Handler, Socket}` triple PLUS a `Traits::Settle` callback -- four facts, not the three its own comment names -- because `EpollReactor` and `KqueueReactor` had no common base. `EventLoop` is that base, so what is left is one free function, and the platform difference moves to `detail/DialPrimitives.hpp`. The file-wide `#if defined(__linux__) || defined(__APPLE__)` is gone: the dial is portable, Windows included | -| `src/core/net/ReadinessDial.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/ReactorDial.hpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B8. `ReadinessDialOp` is `DialOp` and keeps the property that made it right -- it lives in the dialling coroutine's own frame -- and `SettleDial`/`DialPark` keep their shape over `EventLoop::registerPark`. New: stop-awareness, which upstream's dial has none of. A `StopCallback` routes a stop from any thread through `EventLoop::requestCancel`, and a cancelled dial UNWINDS rather than reporting a value, matching `ResultAwaitable::await_resume`. `Traits::Settle`'s three hooks collapse to one `Interest::Write` registration, because `selectReadinessCallback` gives a watched direction priority on every backend | +| `src/core/net/ReadinessDial.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/ReactorDial.hpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B8. `ReadinessDialOp` is `DialOp` and keeps the property that made it right -- it lives in the dialling coroutine's own frame -- and `SettleDial`/`DialPark` keep their shape over `EventLoop::registerPark`. New: stop-awareness, which upstream's dial has none of. A `StopCallback` routes a stop from any thread through `EventLoop::requestCancel`, and a cancelled dial UNWINDS rather than reporting a value, matching `ResultAwaitable::await_resume`. `Traits::Settle`'s three hooks collapse to one `Interest::Write` registration, because `selectReadinessCallback` gives a watched direction priority on every backend; P13 Task 9: split into `dialReadiness` (makes the socket) and `dialReadinessOn` (takes one, for `ITcpSocket`) | | `src/core/net/ReadinessDial_test.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/EpollConnector_test.cpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B8. ONE suite over `testing::BackendMatrix`, where upstream had an epoll-only file and no kqueue counterpart at all -- which is how the macOS divergence Ruling R101 exists to prevent gets written back in. The refusal case is R101 in its natural habitat. New here: the backlog-saturation arrangement, which SKIPs rather than passing when a stack will not leave a dial outstanding, and a descriptor-leak check that reads the lowest free fd on POSIX | | `src/core/net/SocketAddress.hpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/SocketAddress.hpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B8. camelBack. The BIND half is deliberately NOT imported -- `BindAndListen`, `BoundListener`, `BoundPortOf`, `PeerAddressOf`, `ReusePort`, `ExclusiveBindOption` -- because core-cpp's listeners already own their bind sequence, and a second one would be a second answer to who owns an address. `FormatPeerAddress` is `formatPeerAddress` and delegates to the module's existing `detail::formatPeer`; 0.24.0 (P13): `IAddressResolver::resolveClassified` (defaulted), `ResolverErrorRow`, `resolverErrorTable()`, `detail::endpointOfLiteral`, `detail::classifyResolverError`, `detail::resolverSystemCode` | | `src/core/net/SocketBuffers.hpp` | origin: core-cpp | - | - | v0.2.0: `SocketBufferSizes`, the kernel buffer sizes `ListenOptions` and `DialOptions` ask for; fastcached sized both to 1 MiB in its own socket setup | | `src/core/net/detail/StreamSocketOptions.hpp` | origin: core-cpp | - | - | v0.2.0: the one helper every dial and every accept calls; before it only the dial set `TCP_NODELAY` | -| `src/core/net/posix/StreamSocketOptions.cpp` | origin: core-cpp | - | - | v0.2.0; `armKeepAlive` and `wholeSeconds` moved here unchanged from `posix/DialPrimitives.cpp` | +| `src/core/net/posix/StreamSocketOptions.cpp` | origin: core-cpp | - | - | v0.2.0; `armKeepAlive` and `wholeSeconds` moved here unchanged from `posix/DialPrimitives.cpp`; P13 Task 9: `armKeepAlive` and the keepalive half of the report go through the option table's rows, which own the `TCP_KEEPALIVE`/`TCP_KEEPIDLE` spelling | | `src/core/net/windows/StreamSocketOptions.cpp` | origin: core-cpp | - | - | v0.2.0; `armKeepAlive` moved here unchanged from `windows/DialPrimitives.cpp` | | `src/core/net/testing/RawSockets.hpp` | origin: core-cpp | - | - | v0.2.0: plain OS sockets for a case that must stand outside core-cpp, so the cases carry no `#ifdef`; implemented per platform like `makeSocketPair` | | `src/core/net/testing/posix/RawSockets.cpp` | origin: core-cpp | - | - | v0.2.0 | @@ -502,11 +519,11 @@ others in notes. | `src/core/net/testing/DatagramPayload.hpp` | LASTRADA-Software/fastcached | `src/tests/DatagramPayload.hpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B9. In `core::net::testing`, camelBack | | `src/core/net/testing/FailingListener.hpp` | origin: core-cpp | - | - | graduated from LASTRADA-Software/fastcached `src/tests/FailingAcceptsListener.hpp` at `a11f0c1a37ab317bd1dd7e9c82f2c4a78a5a4b55`, a commit not yet on its master: the row moves to that upstream once it is, [core-cpp#60](https://github.com/contour-terminal/core-cpp/issues/60); 0.6.0: renamed, in `core::net::testing` and public; scripts `NetError`s where upstream scripted codes; one class that owns its listener or not, where upstream had `OwningFailingAcceptsListener` beside it; `repeatedFailures()` is new; a closed one answers no more of its script | | `src/core/net/testing/FailingListener_test.cpp` | origin: core-cpp | - | - | 0.6.0: the fake's own contract; upstream has no test of it | -| `src/core/net/testing/InMemorySocket.hpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/InMemoryTransport.hpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B9. Renamed, because `testing/InMemoryTransport.hpp` here is contour's REAL socket pair. Over `ResultAwaitable`'s arm and retire hooks; `waitReadable` parks, a bounded write waits instead of failing `WouldBlock`, the slots are claimed through `core::net::contract`, and the EOF latch is kept. `InMemoryListener::accept` is a coroutine over a parked awaitable; 0.6.0: `InMemoryListener::doClose()` | +| `src/core/net/testing/InMemorySocket.hpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/InMemoryTransport.hpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B9. Renamed, because `testing/InMemoryTransport.hpp` here is contour's REAL socket pair. Over `ResultAwaitable`'s arm and retire hooks; `waitReadable` parks, a bounded write waits instead of failing `WouldBlock`, the slots are claimed through `core::net::contract`, and the EOF latch is kept. `InMemoryListener::accept` is a coroutine over a parked awaitable; 0.6.0: `InMemoryListener::doClose()`; 0.24.0 (P13 Task 8): `InMemoryEndpoints`/`InMemoryPairEndpoints`, the addresses a socket or pair was created with | | `src/core/net/testing/InMemorySocket.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/InMemoryTransport.cpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B9. The pipe no longer wakes anyone from `push` or `pull`: the socket wakes its peer LAST, after recording what it needs, because the peer may own and destroy it. The destructor abandons a parked operation rather than completing it; 0.6.0: `InMemoryListener::doClose()` | | `src/core/net/testing/InMemorySocket_test.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/InMemoryTransport_test.cpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B9. camelBack. New: a parked `waitReadable`, `cancelRead`, the EOF latch, and a bounded write that waits, fails with the reset, and is retired by `close` | | `src/core/net/SocketClosedStates_test.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/SocketClosedStates_test.cpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B9. The parity property kept: one table over the fake and over a real pair. The real pair is two loop sockets run a step at a time, rather than a reactor socket against a blocking one on a thread; `EnumTable` is replaced by arrays checked against their enums at compile time. New: the zero-deadline case and its control, which since Task B7b runs on Windows too: the platform loop's socket there is `IocpSocket`, which has a receive deadline | -| `src/core/net/testing/SocketDecorator.hpp` | LASTRADA-Software/fastcached | `src/tests/SocketDecorator.hpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B9: `SocketDecorator` alone, forwarding every virtual `ISocket` now has, `readWithFd` and `setReceiveDeadline` included | +| `src/core/net/testing/SocketDecorator.hpp` | LASTRADA-Software/fastcached | `src/tests/SocketDecorator.hpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B9: `SocketDecorator` alone, forwarding every virtual `ISocket` now has, `readWithFd` and `setReceiveDeadline` included; P13 Task 9: forwards `option()`/`setOption()` | | `src/core/net/testing/ParkingReadableSocket.hpp` | LASTRADA-Software/fastcached | `src/tests/SocketDecorator.hpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B9: `ParkingReadableSocket`, `ParkingWritableSocket`, and `CompleteCancelled` as `completeCancelled`; `FailingReadSocket` not imported. The destructors abandon rather than complete | | `src/core/net/testing/ParkingReadableSocket_test.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/SocketDecorator_test.cpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B9: the fake-contract case. New: the counters, and `SocketDecorator` forwarding a zero deadline and the defaulted verbs | | `src/core/net/BlockingSocket.hpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/BlockingSocket.hpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B9: `BlockingSocket` alone; `BlockingListener` and the `Detail` helper layer are not imported. `waitReadable` BLOCKS rather than inheriting the answer-`1` default, a non-positive `setReceiveDeadline` removes the bound, and `setSendDeadline` is new | @@ -532,9 +549,9 @@ others in notes. | `src/core/net/HealthProbe.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/HealthProbe.cpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B9. Rewritten over `BlockingConnector` and `BlockingSocket` rather than raw socket calls of its own; the three status digits must be followed by a space or the line end | | `src/core/net/HealthProbe_test.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/HealthProbe_test.cpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B9. Rewritten against `core::net::serve` on a loop thread; assertions on the returned status replace upstream's reached and answered flags | | `src/core/net/testing/InMemorySocketCanary.cpp` | origin: core-cpp | - | - | Task B9: the fake refusing a second read and a second write over a parked one, judged on a marker as `SocketContractCanary.cpp` is | -| `src/core/net/detail/DialPrimitives.hpp` | origin: core-cpp | - | - | Task B8: the handful of OS calls a dial needs, declared once so `ReadinessDial.cpp` is written once. `DialHandles` carries a socket AND a readiness handle because they are the same value on POSIX and different on Windows, where readiness for a socket arrives through an associated `WSAEVENT` Task B7b: `dialCompletion` is declared here, implemented in `windows/IocpDial.cpp` and answered `Unsupported` in `posix/DialPrimitives.cpp`. | -| `src/core/net/posix/DialPrimitives.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/SocketAddress.cpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B8: the POSIX half. `ArmKeepAlive`'s body is upstream's, intervals-before-flag order included; the socket/connect/SO_ERROR sequence around it is lifted from `Net/ReactorDial.hpp`. `fromDialErrno` is new, and is what makes `ConnRefused` and `HostUnreach` reach a caller instead of `SystemError` Task B7b: `dialCompletion` answers `Unsupported`, because no POSIX loop lends a completion port. | -| `src/core/net/windows/DialPrimitives.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/SocketAddress.cpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B8: the Windows half, and deliberately NOT `Net/IocpDial.hpp` -- that one issues `ConnectEx` against an `IocpSocket` this tree does not have yet (Task B7b). This dials through `WSAEventSelect` readiness, which is what `WindowsSocket` already is, and closes the dial's own event before handing the socket over because Winsock allows exactly one event object per socket. `ArmKeepAlive`'s `SIO_KEEPALIVE_VALS` body is upstream's Task B7b: `fromDialError` becomes `detail::fromWinsockError` (`windows/WinsockError.hpp`), shared with the completion socket, listener and dial. | +| `src/core/net/detail/DialPrimitives.hpp` | origin: core-cpp | - | - | Task B8: the handful of OS calls a dial needs, declared once so `ReadinessDial.cpp` is written once. `DialHandles` carries a socket AND a readiness handle because they are the same value on POSIX and different on Windows, where readiness for a socket arrives through an associated `WSAEVENT` Task B7b: `dialCompletion` is declared here, implemented in `windows/IocpDial.cpp` and answered `Unsupported` in `posix/DialPrimitives.cpp`.; P13 Task 9: `DialSocket`, the owner a lazy dial takes its socket in, and the `dialReadinessOn`/`dialCompletionOn` declarations | +| `src/core/net/posix/DialPrimitives.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/SocketAddress.cpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B8: the POSIX half. `ArmKeepAlive`'s body is upstream's, intervals-before-flag order included; the socket/connect/SO_ERROR sequence around it is lifted from `Net/ReactorDial.hpp`. `fromDialErrno` is new, and is what makes `ConnRefused` and `HostUnreach` reach a caller instead of `SystemError` Task B7b: `dialCompletion` answers `Unsupported`, because no POSIX loop lends a completion port.; P13 Task 9: the `dialCompletionOn` stub | +| `src/core/net/windows/DialPrimitives.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/SocketAddress.cpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B8: the Windows half, and deliberately NOT `Net/IocpDial.hpp` -- that one issues `ConnectEx` against an `IocpSocket` this tree does not have yet (Task B7b). This dials through `WSAEventSelect` readiness, which is what `WindowsSocket` already is, and closes the dial's own event before handing the socket over because Winsock allows exactly one event object per socket. `ArmKeepAlive`'s `SIO_KEEPALIVE_VALS` body is upstream's Task B7b: `fromDialError` becomes `detail::fromWinsockError` (`windows/WinsockError.hpp`), shared with the completion socket, listener and dial.; P13 Task 9: `closeDialSocket` leaves alone the readiness event a completion-port socket does not have | | `src/core/net/posix/AdoptListener_test.cpp` | origin: core-cpp | - | - | Task B8: `adoptListener` over a listening descriptor made with the platform's OWN API rather than with `core::net::listen` -- which is the only arrangement that tests what the function is for, a handle this library did not make. POSIX-only as an ARRANGEMENT, not as a behaviour; `windows/AdoptListener_test.cpp` asserts the same three things in the Winsock spelling | | `src/core/net/windows/AdoptListener_test.cpp` | origin: core-cpp | - | - | Task B8: the Winsock half of `posix/AdoptListener_test.cpp`, and the only coverage the Windows `adoptListener` has (`IocpListener::adopt` since 0.5.0) | | `src/core/platform/CMakeLists.txt` | origin: core-cpp | - | - | - | diff --git a/src/core/net/BlockingSocket.cpp b/src/core/net/BlockingSocket.cpp index 1cf08a47..a639b6a8 100644 --- a/src/core/net/BlockingSocket.cpp +++ b/src/core/net/BlockingSocket.cpp @@ -3,6 +3,7 @@ #include #include +#include #include #include @@ -116,6 +117,20 @@ std::expected BlockingSocket::armKeepAlive(KeepAliveSettings con return detail::armKeepAlive(_socket, settings); } +std::expected BlockingSocket::localEndpoint() const +{ + if (_closed) + return std::unexpected(closedSocket("localEndpoint")); + return detail::socketEndpoint(_socket, detail::SocketSide::Local); +} + +std::expected BlockingSocket::remoteEndpoint() const +{ + if (_closed) + return std::unexpected(closedSocket("remoteEndpoint")); + return detail::socketEndpoint(_socket, detail::SocketSide::Remote); +} + void BlockingSocket::setSendDeadline(std::chrono::milliseconds deadline) const noexcept { if (!_closed) diff --git a/src/core/net/BlockingSocket.hpp b/src/core/net/BlockingSocket.hpp index 5e1ed542..3826ba1f 100644 --- a/src/core/net/BlockingSocket.hpp +++ b/src/core/net/BlockingSocket.hpp @@ -88,6 +88,8 @@ class CORE_NET_API BlockingSocket final: public ISocket void setSendDeadline(std::chrono::milliseconds deadline) const noexcept; [[nodiscard]] std::string peerAddress() const override { return _peerAddress; } + [[nodiscard]] std::expected localEndpoint() const override; + [[nodiscard]] std::expected remoteEndpoint() const override; void close() noexcept override; diff --git a/src/core/net/BlockingSocket_test.cpp b/src/core/net/BlockingSocket_test.cpp index 1621e502..a9157308 100644 --- a/src/core/net/BlockingSocket_test.cpp +++ b/src/core/net/BlockingSocket_test.cpp @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -328,4 +329,37 @@ TEST_CASE("Every verb on a closed blocking socket answers BadHandle", "[net][soc // And a half-close after a close is a successful no-op, as on every socket here. CHECK(syncRun(shutOnce(pair.client.get())).has_value()); + + // Refused by the socket itself, so no system code: a call that reached the OS with the closed + // handle would carry its EBADF/WSAENOTSOCK. + auto const local = pair.client->localEndpoint(); + REQUIRE_FALSE(local.has_value()); + CHECK(local.error().code == NetErrorCode::BadHandle); + CHECK(local.error().systemCode == 0); + auto const remote = pair.client->remoteEndpoint(); + REQUIRE_FALSE(remote.has_value()); + CHECK(remote.error().code == NetErrorCode::BadHandle); + CHECK(remote.error().systemCode == 0); +} + +TEST_CASE("A blocking socket reports its own port and its peer's", "[net][socket][blocking][endpoints]") +{ + auto pair = Connected(); + connectPair(pair); + + // Ports, because both ends are 127.0.0.1: only the ephemeral port tells the two ends apart, so a + // socket that asked `getpeername` for its own address would be caught here and nowhere else. + auto const portOf = [](std::expected const& endpoint) { + REQUIRE(endpoint.has_value()); + auto const address = core::net::toIpSocketAddress(*endpoint); + REQUIRE(address.has_value()); + return address->port; + }; + auto const clientLocal = portOf(pair.client->localEndpoint()); + auto const clientRemote = portOf(pair.client->remoteEndpoint()); + + CHECK(clientRemote == pair.listener->boundPort()); + CHECK(clientLocal != 0); + CHECK(clientLocal != clientRemote); + CHECK(clientLocal == portOf(pair.accepted->remoteEndpoint())); } diff --git a/src/core/net/CMakeLists.txt b/src/core/net/CMakeLists.txt index 20032f25..3d44001b 100644 --- a/src/core/net/CMakeLists.txt +++ b/src/core/net/CMakeLists.txt @@ -141,7 +141,9 @@ core_cpp_add_module(net KIND STATIC InterruptibleSleep.hpp IoAwaitable.hpp IoBackend.hpp + IpSocketAddress.hpp ISocket.hpp + ITcpSocket.hpp ITlsContext.hpp ITlsSession.hpp KeepAlive.hpp @@ -153,6 +155,7 @@ core_cpp_add_module(net KIND STATIC SocketBuffers.hpp SocketContract.hpp SocketDeadline.hpp + SocketOption.hpp SleepUntil.hpp Sockets.hpp SplitSocket.hpp @@ -200,14 +203,17 @@ core_cpp_add_module(net KIND STATIC ExecutorAddressResolver.cpp HealthProbe.cpp HttpServer.cpp + IpSocketAddress.cpp ISocket.cpp LingeringClose.cpp ReadinessDial.cpp SharedPortDatagram.cpp SocketAddress.cpp SocketContract.cpp + SocketOption.cpp Sockets.cpp TcpClient.cpp + TcpSocket.cpp ThreadedAddressResolver.cpp WriteQueue.cpp testing/InMemoryDatagram.cpp @@ -218,8 +224,11 @@ core_cpp_add_module(net KIND STATIC detail/DatagramReceiveBuffer.hpp detail/DialPrimitives.hpp detail/PeerAddress.hpp + detail/SocketEndpoint.hpp detail/SocketErrors.hpp + detail/SocketOptionAccess.hpp detail/SshAgentEndpoint.hpp + detail/TcpSocketPrimitives.hpp detail/WakeupChannel.hpp SOURCES_POSIX detail/WouldBlock.hpp @@ -234,7 +243,9 @@ core_cpp_add_module(net KIND STATIC posix/PosixListener.hpp posix/PosixSocket.cpp posix/PosixSocket.hpp + posix/PosixTcpSocket.cpp posix/SocketErrors.cpp + posix/SocketOptionTable.cpp posix/SocketsPosix.cpp posix/SshAgentEndpoint.cpp posix/StreamSocketOptions.cpp @@ -261,11 +272,13 @@ core_cpp_add_module(net KIND STATIC windows/IocpOperation.hpp windows/IocpSocket.cpp windows/IocpSocket.hpp + windows/IocpTcpSocket.cpp windows/NamedPipe.cpp windows/NamedPipe.hpp windows/NetworkEvents.cpp windows/NetworkEvents.hpp windows/SocketErrors.cpp + windows/SocketOptionTable.cpp windows/SocketsWin32.cpp windows/SshAgentEndpoint.cpp windows/StreamSocketOptions.cpp @@ -368,6 +381,7 @@ core_cpp_add_test(net HttpServer_test.cpp IAdmissionControl_test.cpp IoAwaitable_test.cpp + IpSocketAddress_test.cpp LingeringClose_test.cpp LoopTeardown_test.cpp ReadinessDial_test.cpp @@ -375,9 +389,11 @@ core_cpp_add_test(net SocketAddress_test.cpp SocketClosedStates_test.cpp SocketDeadline_test.cpp + SocketEndpoints_test.cpp Socket_test.cpp StreamSocketOptions_test.cpp TcpClient_test.cpp + TcpSocket_test.cpp ThreadedAddressResolver_test.cpp UdpSocket_test.cpp WaitReadable_test.cpp @@ -424,6 +440,8 @@ core_cpp_add_test(net posix/SshAgentEndpoint_test.cpp posix/UnixSocket_test.cpp posix/WaitReadableClose_test.cpp + SOURCES_LINUX + linux/AcceptedSocketOptions_test.cpp SOURCES_WINDOWS windows/AdoptListener_test.cpp windows/IocpBackend_test.cpp diff --git a/src/core/net/IListener.hpp b/src/core/net/IListener.hpp index a255e0fb..3d17f7e7 100644 --- a/src/core/net/IListener.hpp +++ b/src/core/net/IListener.hpp @@ -9,8 +9,12 @@ #include #include #include +#include +#include +#include #include +#include #include #include @@ -76,6 +80,45 @@ class IListener return platform::InvalidHandle; } + /// The address and port this listener is bound to -- `getsockname` -- as a raw endpoint + /// (@c toIpSocketAddress reads it): @c boundPort with the address beside it. + /// + /// Not pure, so a listener with no socket of its own (a test double, a decorator) need not + /// answer; **the default is @c NetErrorCode::Unsupported**, for @c ISocket::localEndpoint's reason. + /// @return The endpoint; @c NetErrorCode::BadHandle once closed; otherwise the classified OS error. + [[nodiscard]] virtual std::expected localEndpoint() const + { + return std::unexpected( + makeNetError(NetErrorCode::Unsupported, 0, "this listener has no local address")); + } + + /// Reads @p option of the listening socket, through the option's row (@c socketOptionTable). + /// What a listener carries, the connections it accepts inherit: the buffer sizes, keepalive. + /// + /// Not pure, so a listener with no socket of its own need not answer; **the default is + /// @c NetErrorCode::Unsupported**, for @c ISocket::option's reason. + /// @param option The option. + /// @return Its value in the row's unit; @c NetErrorCode::BadHandle once closed; otherwise the + /// classified OS error. + [[nodiscard]] virtual std::expected option( + [[maybe_unused]] SocketOption option) const + { + return std::unexpected( + makeNetError(NetErrorCode::Unsupported, 0, "this listener has no socket options")); + } + + /// Sets @p option to @p value, in the unit of the option's row; otherwise as @c option, default + /// included. + /// @param option The option. + /// @param value The value. + /// @return Nothing, or as @c option. + [[nodiscard]] virtual std::expected setOption([[maybe_unused]] SocketOption option, + [[maybe_unused]] std::uint64_t value) + { + return std::unexpected( + makeNetError(NetErrorCode::Unsupported, 0, "this listener has no socket options")); + } + /// Stops accepting. A pending @c accept() resolves with @c NetErrorCode::Cancelled. /// /// Fires @c closeToken(), then runs @c doClose() -- once: a second call does nothing. diff --git a/src/core/net/ISocket.cpp b/src/core/net/ISocket.cpp index 1c3763c4..2c7884e1 100644 --- a/src/core/net/ISocket.cpp +++ b/src/core/net/ISocket.cpp @@ -103,4 +103,27 @@ std::expected ISocket::armKeepAlive(KeepAliveSettings const& /*s makeNetError(NetErrorCode::Unsupported, 0, "this transport cannot arm TCP keepalive")); } +std::expected ISocket::localEndpoint() const +{ + return std::unexpected(makeNetError(NetErrorCode::Unsupported, 0, "this transport has no local address")); +} + +std::expected ISocket::remoteEndpoint() const +{ + return std::unexpected( + makeNetError(NetErrorCode::Unsupported, 0, "this transport has no remote address")); +} + +std::expected ISocket::option(SocketOption /*option*/) const +{ + return std::unexpected( + makeNetError(NetErrorCode::Unsupported, 0, "this transport has no socket options")); +} + +std::expected ISocket::setOption(SocketOption /*option*/, std::uint64_t /*value*/) +{ + return std::unexpected( + makeNetError(NetErrorCode::Unsupported, 0, "this transport has no socket options")); +} + } // namespace core::net diff --git a/src/core/net/ISocket.hpp b/src/core/net/ISocket.hpp index 2f945086..528be82c 100644 --- a/src/core/net/ISocket.hpp +++ b/src/core/net/ISocket.hpp @@ -24,10 +24,13 @@ #include #include #include +#include #include +#include #include #include +#include #include #include #include @@ -329,6 +332,42 @@ class CORE_NET_API ISocket /// in-memory transport). [[nodiscard]] virtual std::string peerAddress() const { return {}; } + /// This end's own address and port -- `getsockname` -- as a raw endpoint (@c toIpSocketAddress + /// reads it). For a dialled socket, the port is the ephemeral one the kernel chose; for an + /// accepted one, the listener's. + /// + /// **The default answers @c NetErrorCode::Unsupported**, for @c armKeepAlive's reason: a transport + /// with no socket under it has no address to give, and an empty endpoint would read as one. Every + /// decorator in this library forwards it; the TLS layer and @c SplitSocket answer from the + /// transport they read from. Call it on the socket's loop thread, as every other member. + /// @return The endpoint; @c NetErrorCode::BadHandle on a closed socket; otherwise the classified + /// OS error. An AF_UNIX socket answers an AF_UNIX endpoint, which is no IP address. + [[nodiscard]] virtual std::expected localEndpoint() const; + + /// @return The peer's address and port -- `getpeername` -- as a raw endpoint; the port + /// @c peerAddress leaves out. Otherwise as @c localEndpoint, default included: a socket + /// whose peer has reset the connection may answer the OS's error rather than the address. + [[nodiscard]] virtual std::expected remoteEndpoint() const; + + /// Reads @p option -- `getsockopt` through the option's row (@c socketOptionTable). + /// + /// **The default answers @c NetErrorCode::Unsupported**, for @c armKeepAlive's reason: a + /// transport with no socket under it has no option to give. Every decorator in this library + /// forwards it; the TLS layer and @c SplitSocket answer from the transport they read from. Call + /// it on the socket's loop thread, as every other member. + /// @param option The option. + /// @return Its value in the row's unit; @c NetErrorCode::BadHandle on a closed socket; + /// otherwise the classified OS error. An AF_UNIX socket answers + /// @c NetErrorCode::Unsupported: the rows are IP ones. + [[nodiscard]] virtual std::expected option(SocketOption option) const; + + /// Sets @p option to @p value, in the unit of the option's row; otherwise as @c option, default + /// included. A value above the row's maximum is clamped to it, as @c ITcpSocket::setOption. + /// @param option The option. + /// @param value The value. + /// @return Nothing, or as @c option. + [[nodiscard]] virtual std::expected setOption(SocketOption option, std::uint64_t value); + /// Closes the socket. Idempotent; a subsequent read or write resolves with /// @c NetErrorCode::BadHandle. /// diff --git a/src/core/net/ITcpSocket.hpp b/src/core/net/ITcpSocket.hpp new file mode 100644 index 00000000..06c22086 --- /dev/null +++ b/src/core/net/ITcpSocket.hpp @@ -0,0 +1,127 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// `ITcpSocket` -- a TCP socket before it is connected or listening -- and `openTcpSocket`. +/// +/// The lifecycle the other transports skip: a dial (`connect`, @c IConnector) and a listener +/// (`listen`) create, bind and connect or listen in one call, so nothing can be asked of the socket +/// in between. Here each step is its own call, and options can be set before the connection exists: +/// a socket binds to a chosen local address and port, then either connects, becoming an @c ISocket, +/// or listens, becoming an @c IListener. Either consumes it. + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace core::net +{ + +class EventLoop; + +/// An unconnected TCP socket: open, possibly bound, neither connected nor listening. +/// +/// **`connect` and `listen` consume it.** The socket's handle moves into the connection or the +/// listener, and every call afterwards answers @c NetErrorCode::BadHandle with no system code -- +/// a second `connect` included, whatever the first one's outcome. A `listen` that fails does not +/// consume it; a `connect` does, at the call rather than when its task first runs, so a task that +/// is dropped unstarted closes the socket it took. +/// +/// Destroying it closes the socket. Call every member on the thread of the loop it was opened on. +class ITcpSocket +{ + public: + ITcpSocket() = default; + virtual ~ITcpSocket() = default; + + ITcpSocket(ITcpSocket const&) = delete; + ITcpSocket& operator=(ITcpSocket const&) = delete; + ITcpSocket(ITcpSocket&&) = delete; + ITcpSocket& operator=(ITcpSocket&&) = delete; + + /// Binds the socket to @p local, which may name port 0 for an ephemeral one. + /// + /// **The platform's reuse-address options are set first**, so a port whose last connection is + /// still in TIME_WAIT can be bound again: `SO_REUSEADDR` on POSIX, and nothing on Windows, whose + /// default already allows that, and whose `SO_REUSEADDR` would let this socket take over a port + /// another one is listening on. A port a live listener holds stays @c NetErrorCode::AddressInUse + /// everywhere. + /// @param local The address and port to bind; of the family the socket was opened with. + /// @return Nothing; @c NetErrorCode::AddressInUse for a port in use; @c NetErrorCode::BadHandle, + /// with no system code, once consumed or already bound; otherwise the classified OS + /// error (an address of the other family). + [[nodiscard]] virtual std::expected bind(ResolvedEndpoint const& local) = 0; + + /// Connects to @p remote, consuming the socket. + /// + /// An unbound socket is bound to its family's wildcard address and an ephemeral port first, by + /// the kernel where its connect does so (POSIX) and explicitly where it does not (Windows' + /// `ConnectEx`). The options set on the socket carry over to the connection, and + /// `TCP_NODELAY` is set as on every connection this library makes. + /// @param remote The address to connect to. By value: the task is lazy. + /// @return A task resolving to the connected socket, the classified failure + /// (@c NetErrorCode::ConnRefused, ...), or @c NetErrorCode::BadHandle once consumed. + /// @throws async::OperationCancelled when the awaiting flow is stopped while the connect is + /// outstanding; the socket is closed. + [[nodiscard]] virtual async::Task connect(ResolvedEndpoint remote) = 0; + + /// Listens for connections, consuming the socket on success. + /// + /// An unbound socket is bound to its family's wildcard address and an ephemeral port first, on + /// every platform. The options set on the socket carry over to the listener, and the + /// connections it accepts inherit the kernel's share of them (buffer sizes, keepalive). + /// @param backlog The listen backlog; the kernel caps it at its own maximum. + /// @return The listener; @c NetErrorCode::BadHandle once consumed; otherwise the classified OS + /// error. A failed bind or `listen` leaves the socket as it was; a failure after the + /// socket is listening (adopting it on the loop) consumes it, because it can no longer + /// connect. + [[nodiscard]] virtual std::expected, NetError> listen( + std::uint32_t backlog) = 0; + + /// @return The address and port the socket is bound to -- `getsockname` -- as a raw endpoint; + /// @c NetErrorCode::BadHandle, with no system code, once consumed or while unbound: the + /// same answer on every platform, where the OS itself says the wildcard at port 0 + /// (POSIX) or refuses (Windows). + [[nodiscard]] virtual std::expected localEndpoint() const = 0; + + /// @param option The option to read. + /// @return Its value in the unit its row states (@c socketOptionTable); + /// @c NetErrorCode::BadHandle once consumed; otherwise the classified OS error. + [[nodiscard]] virtual std::expected option(SocketOption option) const = 0; + + /// Sets @p option to @p value, in the unit its row states. + /// + /// A value above the row's maximum (@c SocketOptionRow::maximum) is clamped to it, so a value + /// is never refused for being too large; the kernel may cap it further (Linux caps a buffer at + /// `rmem_max`), and it then reads back capped. A value the kernel refuses for another reason is + /// its classified error. + /// @param option The option to set. + /// @param value The value. + /// @return Nothing; @c NetErrorCode::BadHandle once consumed; otherwise the classified OS error. + [[nodiscard]] virtual std::expected setOption(SocketOption option, + std::uint64_t value) = 0; +}; + +/// Opens an unconnected, unbound TCP socket of @p family on @p loop. +/// +/// Non-blocking and not inherited by child processes, as every socket here is. **An IPv6 socket is +/// IPv6-only** (`IPV6_V6ONLY`) on every platform, whatever the system default: an IPv6 wildcard +/// bind then takes no IPv4 connections, and the two families can bind the same port side by side. +/// @param loop The loop the socket, and the connection or listener it becomes, is pinned to. +/// @param family The address family. +/// @return The socket; @c NetErrorCode::Unsupported where the loop cannot serve one (on Windows, a +/// loop that lends no completion port) or the host lacks the family; otherwise the +/// classified OS error. +[[nodiscard]] CORE_NET_API std::expected, NetError> openTcpSocket( + EventLoop& loop, AddressFamily family); + +} // namespace core::net diff --git a/src/core/net/IpSocketAddress.cpp b/src/core/net/IpSocketAddress.cpp new file mode 100644 index 00000000..710852f6 --- /dev/null +++ b/src/core/net/IpSocketAddress.cpp @@ -0,0 +1,141 @@ +// SPDX-License-Identifier: Apache-2.0 + +// winsock2.h MUST precede any windows.h a later include pulls in, so this block leads the file. +// clang-format off +#ifdef _WIN32 + #include + #include +#else + #include + + #include + #include +#endif +// clang-format on + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace core::net +{ + +namespace +{ + /// @param v4 The typed address. + /// @param port The port, in host byte order. + /// @return The `sockaddr_in` they spell. + [[nodiscard]] sockaddr_in sockaddrOf(Ipv4Address const& v4, std::uint16_t port) noexcept + { + auto raw = sockaddr_in {}; + raw.sin_family = AF_INET; + raw.sin_port = htons(port); + static_assert(sizeof(raw.sin_addr) == sizeof(v4.octets)); + // The octets are already in the order they travel: network order is the written order. + std::memcpy(&raw.sin_addr, v4.octets.data(), v4.octets.size()); + return raw; + } + + /// @param v6 The typed IPv6 address. + /// @param address The socket address it came from, for its port, flow label and scope. + /// @return The `sockaddr_in6` they spell. + [[nodiscard]] sockaddr_in6 sockaddrOf(Ipv6Address const& v6, IpSocketAddress const& address) noexcept + { + auto raw = sockaddr_in6 {}; + raw.sin6_family = AF_INET6; + raw.sin6_port = htons(address.port); + raw.sin6_flowinfo = htonl(address.flowInfo); + raw.sin6_scope_id = address.scopeId; + auto bytes = std::array {}; + for (auto const [index, segment]: core::views::enumerate(v6.segments)) + { + bytes.at(2 * index) = static_cast(segment >> 8U); + bytes.at((2 * index) + 1) = static_cast(segment & 0xffU); + } + static_assert(sizeof(raw.sin6_addr) == bytes.size()); + std::memcpy(&raw.sin6_addr, bytes.data(), bytes.size()); + return raw; + } + + /// @param raw A `sockaddr_in` read out of an endpoint. + /// @return Its typed form. + [[nodiscard]] IpSocketAddress addressOf(sockaddr_in const& raw) noexcept + { + auto v4 = Ipv4Address {}; + std::memcpy(v4.octets.data(), &raw.sin_addr, v4.octets.size()); + return IpSocketAddress { .address = v4, .port = ntohs(raw.sin_port) }; + } + + /// @param raw A `sockaddr_in6` read out of an endpoint. + /// @return Its typed form. + [[nodiscard]] IpSocketAddress addressOf(sockaddr_in6 const& raw) noexcept + { + auto bytes = std::array {}; + std::memcpy(bytes.data(), &raw.sin6_addr, bytes.size()); + auto v6 = Ipv6Address {}; + for (auto [index, segment]: core::views::enumerate(v6.segments)) + segment = static_cast((bytes.at(2 * index) << 8U) | bytes.at((2 * index) + 1)); + return IpSocketAddress { .address = v6, + .port = ntohs(raw.sin6_port), + .flowInfo = ntohl(raw.sin6_flowinfo), + .scopeId = raw.sin6_scope_id }; + } + + /// Reads a @p Sockaddr out of @p endpoint, refusing one too short to hold it. + /// @param endpoint An endpoint whose family is @p Sockaddr's. + /// @return The typed address, or @c NetErrorCode::AddressError. + template + [[nodiscard]] std::expected readSockaddr(ResolvedEndpoint const& endpoint) + { + if (endpoint.length < sizeof(Sockaddr)) + return std::unexpected(makeNetError( + NetErrorCode::AddressError, + 0, + std::format("an endpoint of family {} holds {} bytes, short of its sockaddr's {}", + endpoint.family, + endpoint.length, + sizeof(Sockaddr)))); + auto raw = Sockaddr {}; + std::memcpy(&raw, endpoint.storage.data(), sizeof(raw)); + return addressOf(raw); + } + +} // namespace + +ResolvedEndpoint toEndpoint(IpSocketAddress const& address) noexcept +{ + return std::visit(core::Overloaded { + [&](Ipv4Address const& v4) { + auto const raw = sockaddrOf(v4, address.port); + return detail::endpointFromSockaddr(&raw, sizeof(raw)); + }, + [&](Ipv6Address const& v6) { + auto const raw = sockaddrOf(v6, address); + return detail::endpointFromSockaddr(&raw, sizeof(raw)); + }, + }, + address.address); +} + +std::expected toIpSocketAddress(ResolvedEndpoint const& endpoint) +{ + if (endpoint.length > 0 && endpoint.family == AF_INET) + return readSockaddr(endpoint); + if (endpoint.length > 0 && endpoint.family == AF_INET6) + return readSockaddr(endpoint); + return std::unexpected( + makeNetError(NetErrorCode::Unsupported, + 0, + std::format("an endpoint of family {} is no IP address", endpoint.family))); +} + +} // namespace core::net diff --git a/src/core/net/IpSocketAddress.hpp b/src/core/net/IpSocketAddress.hpp new file mode 100644 index 00000000..141a756b --- /dev/null +++ b/src/core/net/IpSocketAddress.hpp @@ -0,0 +1,89 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// `IpSocketAddress` -- an IPv4 or IPv6 socket address as typed values, and its conversions to and +/// from the raw @c ResolvedEndpoint every socket call takes. +/// +/// **A value, not a sockaddr.** @c ResolvedEndpoint carries the platform's own bytes, which is what +/// `connect`, `bind` and `getsockname` speak, but nothing a caller can read: the port sits at a +/// family-dependent offset in network byte order, and an IPv6 flow label likewise. This is the form +/// a caller inspects and builds, with every field in host order, and the two conversions below are +/// the only code that knows the layouts (`IpSocketAddress.cpp`, pure over `sockaddr_in` and +/// `sockaddr_in6`). Like @c ResolvedEndpoint, this header names no platform type. + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace core::net +{ + +/// An IPv4 address, most significant octet first: 127.0.0.1 is `{ 127, 0, 0, 1 }`. +struct Ipv4Address +{ + std::array octets {}; ///< The four octets, in the order they are written. + + auto operator<=>(Ipv4Address const&) const = default; +}; + +/// An IPv6 address as eight 16-bit segments in host byte order, most significant first: +/// `fe80::1` is `{ 0xfe80, 0, 0, 0, 0, 0, 0, 1 }`. An IPv4-mapped address (`::ffff:192.0.2.1`) +/// stays an IPv6 one; nothing here unmaps it. +struct Ipv6Address +{ + std::array segments {}; ///< The eight segments, in the order they are written. + + auto operator<=>(Ipv6Address const&) const = default; +}; + +/// Which IP version an address or a socket speaks. +enum class AddressFamily : std::uint8_t +{ + Ipv4, ///< IPv4: `AF_INET`. + Ipv6, ///< IPv6: `AF_INET6`. +}; + +/// An IP address with the port and, for IPv6, the flow label and scope that a socket address carries. +struct IpSocketAddress +{ + std::variant address; ///< The host; its alternative is the family. + std::uint16_t port = 0; ///< The port, in host byte order. + std::uint32_t flowInfo = 0; ///< IPv6 only: `sin6_flowinfo`, in host byte order. Zero for IPv4. + std::uint32_t scopeId = 0; ///< IPv6 only: `sin6_scope_id`, the zone's interface index. Zero for IPv4. + + /// @return The family @c address holds. + [[nodiscard]] AddressFamily family() const noexcept + { + return std::holds_alternative(address) ? AddressFamily::Ipv6 : AddressFamily::Ipv4; + } + + bool operator==(IpSocketAddress const&) const = default; +}; + +/// Converts @p address into the `sockaddr_in` or `sockaddr_in6` bytes a socket call takes. +/// +/// For an IPv4 address @c IpSocketAddress::flowInfo and @c IpSocketAddress::scopeId have nowhere to +/// go and are not written. The endpoint's protocol is 0, which `socket()` reads as the family's +/// default for the socket type -- TCP for a stream, UDP for a datagram -- so the one endpoint serves +/// both. +/// @param address The address to convert. +/// @return The endpoint; its family is the platform's `AF_INET` or `AF_INET6`. +[[nodiscard]] CORE_NET_API ResolvedEndpoint toEndpoint(IpSocketAddress const& address) noexcept; + +/// Reads an IPv4 or IPv6 endpoint -- what a resolver, `getsockname` or `getpeername` produced -- as +/// typed values. +/// @param endpoint The endpoint to read. +/// @return The address; @c NetErrorCode::Unsupported for an endpoint of any other family (an +/// AF_UNIX one, an empty one), and @c NetErrorCode::AddressError for one shorter than its +/// family's sockaddr, whose missing bytes would otherwise be read as an address. +[[nodiscard]] CORE_NET_API std::expected toIpSocketAddress( + ResolvedEndpoint const& endpoint); + +} // namespace core::net diff --git a/src/core/net/IpSocketAddress_test.cpp b/src/core/net/IpSocketAddress_test.cpp new file mode 100644 index 00000000..10b364ee --- /dev/null +++ b/src/core/net/IpSocketAddress_test.cpp @@ -0,0 +1,230 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// `IpSocketAddress` against the sockaddr bytes it stands for. +// +// A round trip alone agrees with itself: a conversion that stored the port or the flow label in the +// wrong byte order in BOTH directions would pass one. So the cases below also build the sockaddr by +// hand, the way `getsockname` hands one over, and read what `toEndpoint` wrote back through the +// platform's own structure. +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include + +#ifdef _WIN32 +// clang-format off + #include + #include +// clang-format on +#else + #include + + #include + #include +#endif + +using core::net::AddressFamily; +using core::net::IpSocketAddress; +using core::net::Ipv4Address; +using core::net::Ipv6Address; +using core::net::NetErrorCode; +using core::net::ResolvedEndpoint; + +namespace +{ + +/// One row of the round-trip table. +struct RoundTripRow +{ + char const* name = nullptr; ///< What the row is, for the failure message. + IpSocketAddress address; ///< The address that must come back unchanged. +}; + +/// IPv4, IPv6, an IPv4-mapped IPv6 address (which stays IPv6: nothing unmaps it), and a scoped +/// link-local address with a flow label -- the two fields only `sockaddr_in6` carries. +[[nodiscard]] std::array const& roundTripRows() +{ + static auto const rows = std::array { + RoundTripRow { .name = "IPv4 loopback", + .address = + IpSocketAddress { .address = Ipv4Address { { 127, 0, 0, 1 } }, .port = 8080 } }, + RoundTripRow { .name = "IPv4 with every octet distinct", + .address = + IpSocketAddress { .address = Ipv4Address { { 203, 0, 113, 7 } }, .port = 65535 } }, + RoundTripRow { + .name = "IPv6 with every segment distinct", + .address = + IpSocketAddress { + .address = + Ipv6Address { { 0x2001, 0x0db8, 0x0102, 0x0304, 0x0506, 0x0708, 0x090a, 0x0b0c } }, + .port = 443 } }, + RoundTripRow { + .name = "IPv4-mapped IPv6", + .address = IpSocketAddress { .address = Ipv6Address { { 0, 0, 0, 0, 0, 0xffff, 0xc000, 0x0201 } }, + .port = 1 } }, + RoundTripRow { .name = "fe80::1%scope with a flow label", + .address = + IpSocketAddress { .address = Ipv6Address { { 0xfe80, 0, 0, 0, 0, 0, 0, 1 } }, + .port = 5353, + .flowInfo = 0x000a'bcde, + .scopeId = 7 } }, + }; + return rows; +} + +/// @return @p endpoint's storage read back as a @c sockaddr_in6. +[[nodiscard]] sockaddr_in6 asV6(ResolvedEndpoint const& endpoint) +{ + auto v6 = sockaddr_in6 {}; + std::memcpy(&v6, endpoint.storage.data(), sizeof(v6)); + return v6; +} + +} // namespace + +TEST_CASE("An IP socket address survives a round trip through ResolvedEndpoint", "[net][ip-socket-address]") +{ + for (auto const& row: roundTripRows()) + { + DYNAMIC_SECTION(row.name) + { + auto const endpoint = core::net::toEndpoint(row.address); + auto const back = core::net::toIpSocketAddress(endpoint); + REQUIRE(back.has_value()); + CHECK(*back == row.address); + CHECK(core::net::detail::portOfSockaddr(endpoint.storage.data(), endpoint.length) + == row.address.port); + } + } +} + +TEST_CASE("toEndpoint writes the sockaddr the platform reads", "[net][ip-socket-address]") +{ + SECTION("IPv4: family, network-order port and address") + { + auto const endpoint = core::net::toEndpoint( + IpSocketAddress { .address = Ipv4Address { { 192, 0, 2, 33 } }, .port = 0x1234 }); + CHECK(endpoint.family == AF_INET); + CHECK(endpoint.length == sizeof(sockaddr_in)); + CHECK(endpoint.protocol == 0); + CHECK(core::net::formatPeerAddress(endpoint) == "192.0.2.33"); + + auto v4 = sockaddr_in {}; + std::memcpy(&v4, endpoint.storage.data(), sizeof(v4)); + CHECK(ntohs(v4.sin_port) == 0x1234); + } + + SECTION("IPv6: segments in network order, the flow label in network order, the scope as is") + { + auto const endpoint = core::net::toEndpoint( + IpSocketAddress { .address = Ipv6Address { { 0xfe80, 0, 0, 0, 0, 0, 0, 0x0102 } }, + .port = 0x1234, + .flowInfo = 0x0001'2345, + .scopeId = 0x0102'0304 }); + CHECK(endpoint.family == AF_INET6); + CHECK(endpoint.length == sizeof(sockaddr_in6)); + CHECK(core::net::formatPeerAddress(endpoint) == "fe80::102"); + + auto const v6 = asV6(endpoint); + CHECK(ntohs(v6.sin6_port) == 0x1234); + CHECK(ntohl(v6.sin6_flowinfo) == 0x0001'2345U); + CHECK(v6.sin6_scope_id == 0x0102'0304U); + } +} + +TEST_CASE("toIpSocketAddress reads a sockaddr built the way the kernel builds one", + "[net][ip-socket-address]") +{ + SECTION("IPv4") + { + auto v4 = sockaddr_in {}; + v4.sin_family = AF_INET; + v4.sin_port = htons(0xbeef); + REQUIRE(::inet_pton(AF_INET, "10.20.30.40", &v4.sin_addr) == 1); + auto const endpoint = core::net::detail::endpointFromSockaddr(&v4, sizeof(v4)); + + auto const address = core::net::toIpSocketAddress(endpoint); + REQUIRE(address.has_value()); + CHECK(address->family() == AddressFamily::Ipv4); + CHECK(address->address + == std::variant { Ipv4Address { { 10, 20, 30, 40 } } }); + CHECK(address->port == 0xbeef); + CHECK(address->flowInfo == 0); + CHECK(address->scopeId == 0); + } + + SECTION("IPv6, with a flow label and a scope") + { + auto v6 = sockaddr_in6 {}; + v6.sin6_family = AF_INET6; + v6.sin6_port = htons(0xbeef); + v6.sin6_flowinfo = htonl(0x000f'0001); + v6.sin6_scope_id = 3; + REQUIRE(::inet_pton(AF_INET6, "2001:db8::a:b", &v6.sin6_addr) == 1); + auto const endpoint = core::net::detail::endpointFromSockaddr(&v6, sizeof(v6)); + + auto const address = core::net::toIpSocketAddress(endpoint); + REQUIRE(address.has_value()); + CHECK(address->family() == AddressFamily::Ipv6); + CHECK(address->address + == std::variant { + Ipv6Address { { 0x2001, 0x0db8, 0, 0, 0, 0, 0xa, 0xb } } }); + CHECK(address->port == 0xbeef); + CHECK(address->flowInfo == 0x000f'0001U); + CHECK(address->scopeId == 3U); + } + + SECTION("A literal the resolver path produced") + { + auto const endpoint = core::net::detail::endpointOfLiteral("::ffff:192.0.2.1", 99); + REQUIRE(endpoint.has_value()); + auto const address = core::net::toIpSocketAddress(*endpoint); + REQUIRE(address.has_value()); + CHECK(address->address + == std::variant { + Ipv6Address { { 0, 0, 0, 0, 0, 0xffff, 0xc000, 0x0201 } } }); + CHECK(address->port == 99); + } +} + +TEST_CASE("toIpSocketAddress refuses what is not an IP endpoint", "[net][ip-socket-address]") +{ + SECTION("An empty endpoint is Unsupported") + { + auto const address = core::net::toIpSocketAddress(ResolvedEndpoint {}); + REQUIRE_FALSE(address.has_value()); + CHECK(address.error().code == NetErrorCode::Unsupported); + } + + SECTION("A non-IP family is Unsupported") + { + auto other = sockaddr_in {}; + other.sin_family = AF_UNSPEC; + auto const endpoint = core::net::detail::endpointFromSockaddr(&other, sizeof(other)); + auto const address = core::net::toIpSocketAddress(endpoint); + REQUIRE_FALSE(address.has_value()); + CHECK(address.error().code == NetErrorCode::Unsupported); + } + + SECTION("An IP family shorter than its sockaddr is an AddressError") + { + auto const family = GENERATE(as {}, AF_INET, AF_INET6); + auto v6 = sockaddr_in6 {}; + v6.sin6_family = static_cast(family); + // One byte short of the family's own structure: a kernel never hands such a thing over, and + // reading the missing bytes would invent an address. + auto const size = family == AF_INET ? sizeof(sockaddr_in) - 1 : sizeof(sockaddr_in6) - 1; + auto const endpoint = core::net::detail::endpointFromSockaddr(&v6, static_cast(size)); + auto const address = core::net::toIpSocketAddress(endpoint); + REQUIRE_FALSE(address.has_value()); + CHECK(address.error().code == NetErrorCode::AddressError); + } +} diff --git a/src/core/net/ReadinessDial.cpp b/src/core/net/ReadinessDial.cpp index baa324a6..ab849c09 100644 --- a/src/core/net/ReadinessDial.cpp +++ b/src/core/net/ReadinessDial.cpp @@ -212,11 +212,24 @@ async::Task dialReadiness(EventLoop* loop, if (!opened.has_value()) co_return std::unexpected(opened.error()); - auto handles = *opened; - // Closes whatever is LEFT when this frame goes — an `OperationCancelled` thrown out of the - // park included, which is the path that would otherwise leak a descriptor per cancelled dial. + // The task is made in a statement of its own, so the `DialSocket` temporary is gone before the + // `co_await`: MSVC at /O2 cannot emit a symmetric transfer's tail call with a destructor still + // pending in the awaiting full-expression (C4737; see `ReadinessDial_test.cpp`). + auto dial = dialReadinessOn(loop, DialSocket { loop, *opened }, endpoint, deadline, options); + co_return co_await std::move(dial); +} + +async::Task dialReadinessOn(EventLoop* loop, + DialSocket socket, + ResolvedEndpoint endpoint, + platform::SteadyTimePoint deadline, + StreamSocketOptions options) +{ + // Closes whatever is LEFT when this frame goes — an `OperationCancelled` thrown out of the park + // included, which is the path that would otherwise leak a descriptor per cancelled dial. // `adoptDialled` empties `handles`, so the success path disarms this by having nothing to // close rather than by a flag somebody can forget to set. + auto handles = socket.release(); auto const discard = ScopeGuard { [&]() noexcept { closeDialSocket(loop, handles); } }; // Before the connect, while the window scale can still take the receive buffer into account. diff --git a/src/core/net/SocketEndpoints_test.cpp b/src/core/net/SocketEndpoints_test.cpp new file mode 100644 index 00000000..d713b3ff --- /dev/null +++ b/src/core/net/SocketEndpoints_test.cpp @@ -0,0 +1,244 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// `ISocket::localEndpoint`/`remoteEndpoint` and `IListener::localEndpoint`: the ports a connection +// actually has, on every transport this library hands out. +// +// **The ports are what distinguish.** Every address here is a loopback, so an implementation that +// answered the listener's address for both ends, or swapped `getsockname` for `getpeername`, would +// still report the right host. The ephemeral port the kernel gave the dialling end is the one value +// only the right call on the right socket can produce, so each assertion is about a port seen from +// two sides. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include + +using core::async::Task; +using core::net::AddressFamily; +using core::net::EventLoop; +using core::net::IListener; +using core::net::IpSocketAddress; +using core::net::Ipv4Address; +using core::net::ISocket; +using core::net::NetError; +using core::net::NetErrorCode; +using core::net::ResolvedEndpoint; +using core::net::testing::InMemoryEndpoints; +using core::net::testing::InMemoryPairEndpoints; +using core::net::testing::InMemoryPipe; +using core::net::testing::InMemorySocket; +using core::net::testing::InMemorySocketPair; + +namespace +{ + +/// The two ends of one loopback connection, or nothing where a step failed. +struct Connection +{ + std::unique_ptr client; ///< The dialling end. + std::unique_ptr accepted; ///< The end the listener handed out. +}; + +/// Dials the listener and accepts the connection. The dial completes out of the kernel's backlog +/// before anything accepts, so the two steps run in sequence on one loop and neither can hang the +/// other. +/// @param loop The loop both ends live on. +/// @param host The listener's host, unbracketed. +/// @param listener The bound listener. +/// @param out Where the two ends go. +Task dialAndAccept(EventLoop* loop, std::string host, IListener* listener, Connection* out) +{ + auto connected = co_await core::net::connect(loop, std::move(host), listener->boundPort()); + if (!connected.has_value()) + co_return; + out->client = std::move(*connected); + auto accepted = co_await listener->accept(); + if (accepted.has_value()) + out->accepted = std::move(*accepted); +} + +/// @return The IP form of @p endpoint, which the case has already required to exist. +[[nodiscard]] IpSocketAddress ipOf(std::expected const& endpoint) +{ + REQUIRE(endpoint.has_value()); + auto address = core::net::toIpSocketAddress(*endpoint); + REQUIRE(address.has_value()); + return *address; +} + +/// @return An endpoint for 192.0.2.@p last : @p port, standing for an address an in-memory pair +/// was created with. +[[nodiscard]] ResolvedEndpoint documentationEndpoint(std::uint8_t last, std::uint16_t port) +{ + return core::net::toEndpoint( + IpSocketAddress { .address = Ipv4Address { { 192, 0, 2, last } }, .port = port }); +} + +/// @return Whether @p result failed with @p code. +[[nodiscard]] bool failedWith(std::expected const& result, NetErrorCode code) +{ + return !result.has_value() && result.error().code == code; +} + +/// @return Whether @p result is the socket's own refusal of a closed handle: @c BadHandle with no +/// system code, which a call that reached the OS would carry. +[[nodiscard]] bool refusedAsClosed(std::expected const& result) +{ + return failedWith(result, NetErrorCode::BadHandle) && result.error().systemCode == 0; +} + +} // namespace + +TEST_CASE("A loopback connection reports each end's port from both sides", "[net][endpoints][loopback]") +{ + auto const host = GENERATE(std::string { "127.0.0.1" }, std::string { "::1" }); + auto const family = host == "::1" ? AddressFamily::Ipv6 : AddressFamily::Ipv4; + + auto backend = core::net::makeDefaultBackend(); + auto loop = EventLoop { *backend }; + auto listener = core::net::listen(loop, host, 0); + if (!listener.has_value() && family == AddressFamily::Ipv6) + SKIP("this host has no IPv6 loopback: " << listener.error().toString()); + REQUIRE(listener.has_value()); + + // The listener's own answer agrees with the port it reports it got. + auto const listening = ipOf((*listener)->localEndpoint()); + CHECK(listening.family() == family); + CHECK(listening.port == (*listener)->boundPort()); + CHECK(listening.port != 0); + + auto connection = Connection {}; + loop.blockOn(dialAndAccept(&loop, host, listener->get(), &connection)); + REQUIRE(connection.client != nullptr); + REQUIRE(connection.accepted != nullptr); + + auto const clientLocal = ipOf(connection.client->localEndpoint()); + auto const clientRemote = ipOf(connection.client->remoteEndpoint()); + auto const acceptedLocal = ipOf(connection.accepted->localEndpoint()); + auto const acceptedRemote = ipOf(connection.accepted->remoteEndpoint()); + + // The client dialled the listener's port, and the accepted end sits on it. + CHECK(clientRemote.port == listening.port); + CHECK(acceptedLocal.port == listening.port); + + // The client's own port is an ephemeral one the kernel chose, and the accepted end sees it. + CHECK(clientLocal.port != 0); + CHECK(clientLocal.port != listening.port); + CHECK(acceptedRemote.port == clientLocal.port); + + // Every end speaks the family it was opened with, and the two sides agree on the hosts. + CHECK(clientLocal.family() == family); + CHECK(clientRemote.family() == family); + CHECK(acceptedLocal.family() == family); + CHECK(acceptedRemote.family() == family); + CHECK(acceptedRemote.address == clientLocal.address); + CHECK(clientRemote.address == acceptedLocal.address); + + SECTION("A closed socket and a closed listener answer BadHandle, without asking the OS") + { + // The socket refuses on its own (system code 0) rather than handing a closed descriptor to + // `getsockname`: a descriptor number may already belong to someone else by then, and this + // is the one assertion that tells the socket's refusal from the kernel's EBADF. + connection.client->close(); + CHECK(refusedAsClosed(connection.client->localEndpoint())); + CHECK(refusedAsClosed(connection.client->remoteEndpoint())); + (*listener)->close(); + CHECK(refusedAsClosed((*listener)->localEndpoint())); + } + + SECTION("A decorator and a split socket forward both") + { + auto decorator = core::net::testing::SocketDecorator { *connection.client }; + CHECK(ipOf(decorator.localEndpoint()) == clientLocal); + CHECK(ipOf(decorator.remoteEndpoint()) == clientRemote); + + // The duplex socket reports its READ half's endpoints, as it reports its peer address. + auto pair = InMemorySocketPair::create(); + auto split = core::net::combineHalves(std::move(connection.client), std::move(pair.client)); + CHECK(ipOf(split->localEndpoint()) == clientLocal); + CHECK(ipOf(split->remoteEndpoint()) == clientRemote); + } +} + +TEST_CASE("An in-memory pair reports the endpoints it was created with", "[net][endpoints][inmemory]") +{ + auto const clientAddress = documentationEndpoint(1, 50'000); + auto const serverAddress = documentationEndpoint(2, 443); + auto pair = InMemorySocketPair::create( + 0, {}, InMemoryPairEndpoints { .client = clientAddress, .server = serverAddress }); + + CHECK(ipOf(pair.client->localEndpoint()) == ipOf(clientAddress)); + CHECK(ipOf(pair.client->remoteEndpoint()) == ipOf(serverAddress)); + CHECK(ipOf(pair.server->localEndpoint()) == ipOf(serverAddress)); + CHECK(ipOf(pair.server->remoteEndpoint()) == ipOf(clientAddress)); + + SECTION("A decorator forwards both") + { + auto decorator = core::net::testing::SocketDecorator { *pair.server }; + CHECK(ipOf(decorator.localEndpoint()) == ipOf(serverAddress)); + CHECK(ipOf(decorator.remoteEndpoint()) == ipOf(clientAddress)); + } + + SECTION("After close it answers BadHandle, as the platform sockets do") + { + pair.client->close(); + CHECK(failedWith(pair.client->localEndpoint(), NetErrorCode::BadHandle)); + CHECK(failedWith(pair.client->remoteEndpoint(), NetErrorCode::BadHandle)); + } +} + +TEST_CASE("A transport with no address answers Unsupported", "[net][endpoints][inmemory]") +{ + SECTION("An in-memory pair created without endpoints") + { + auto pair = InMemorySocketPair::create(); + CHECK(failedWith(pair.client->localEndpoint(), NetErrorCode::Unsupported)); + CHECK(failedWith(pair.server->remoteEndpoint(), NetErrorCode::Unsupported)); + } + + SECTION("An in-memory socket given only one of the two") + { + auto pair = InMemorySocketPair::create( + 0, {}, InMemoryPairEndpoints { .client = documentationEndpoint(3, 1), .server = std::nullopt }); + CHECK(pair.client->localEndpoint().has_value()); + CHECK(failedWith(pair.client->remoteEndpoint(), NetErrorCode::Unsupported)); + CHECK(failedWith(pair.server->localEndpoint(), NetErrorCode::Unsupported)); + CHECK(pair.server->remoteEndpoint().has_value()); + } + + SECTION("A listener that does not override the default") + { + auto listener = core::net::testing::InMemoryListener {}; + CHECK(failedWith(listener.localEndpoint(), NetErrorCode::Unsupported)); + } + + SECTION("Endpoints given to one InMemorySocket directly") + { + auto const local = documentationEndpoint(4, 4); + auto inbound = std::make_shared(0); + auto outbound = std::make_shared(0); + auto socket = InMemorySocket { + inbound, outbound, {}, InMemoryEndpoints { .local = local, .remote = std::nullopt } + }; + CHECK(ipOf(socket.localEndpoint()) == ipOf(local)); + CHECK(failedWith(socket.remoteEndpoint(), NetErrorCode::Unsupported)); + } +} diff --git a/src/core/net/SocketOption.cpp b/src/core/net/SocketOption.cpp new file mode 100644 index 00000000..528b7c86 --- /dev/null +++ b/src/core/net/SocketOption.cpp @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: Apache-2.0 +#include + +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace core::net::detail +{ + +namespace +{ + /// @return The row for @p option on a socket of @p family, or nothing where the platform has none. + [[nodiscard]] std::optional rowFor(SocketOption option, AddressFamily family) noexcept + { + auto const table = socketOptionTable(); + auto const row = std::ranges::find_if(table, [&](SocketOptionRow const& candidate) noexcept { + return candidate.option == option && candidate.family == family; + }); + if (row == table.end()) + return std::nullopt; + return *row; + } + + /// @return The refusal for an option the platform has no row for. + [[nodiscard]] NetError noRow() + { + return makeNetError(NetErrorCode::Unsupported, 0, "this platform has no such socket option"); + } + + /// @return The family of the bound socket @p socket, as the kernel reports it. + [[nodiscard]] std::expected familyOf(platform::NativeHandle socket) + { + return socketEndpoint(socket, SocketSide::Local) + .and_then([](ResolvedEndpoint const& local) { return toIpSocketAddress(local); }) + .transform([](IpSocketAddress const& address) { return address.family(); }); + } +} // namespace + +std::expected readSocketOption(platform::NativeHandle socket, + AddressFamily family, + SocketOption option) +{ + auto const row = rowFor(option, family); + if (!row.has_value()) + return std::unexpected(noRow()); + return getIntOption(socket, NativeOption { .level = row->level, .name = row->name }) + .transform([scale = row->scale](int kernel) { return fromKernel(scale, kernel); }); +} + +std::expected writeSocketOption(platform::NativeHandle socket, + AddressFamily family, + SocketOption option, + std::uint64_t value) +{ + auto const row = rowFor(option, family); + if (!row.has_value()) + return std::unexpected(noRow()); + return setIntOption( + socket, NativeOption { .level = row->level, .name = row->name }, toKernel(*row, value)); +} + +std::expected readSocketOption(platform::NativeHandle socket, SocketOption option) +{ + return familyOf(socket).and_then( + [&](AddressFamily family) { return readSocketOption(socket, family, option); }); +} + +std::expected writeSocketOption(platform::NativeHandle socket, + SocketOption option, + std::uint64_t value) +{ + return familyOf(socket).and_then( + [&](AddressFamily family) { return writeSocketOption(socket, family, option, value); }); +} + +} // namespace core::net::detail diff --git a/src/core/net/SocketOption.hpp b/src/core/net/SocketOption.hpp new file mode 100644 index 00000000..f47d1f3b --- /dev/null +++ b/src/core/net/SocketOption.hpp @@ -0,0 +1,70 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// `SocketOption` -- the options a TCP socket, a connection and a listener set and read back -- and +/// the per-platform table that says which `getsockopt`/`setsockopt` each one is. +/// +/// **Behaviour is the table, and the code interprets it.** Each row names one option for one +/// address family: its level, its name, and how the kernel's number relates to the caller's. A +/// platform difference is a different row in that platform's `SocketOptionTable.cpp`, never a +/// branch: Linux's doubled buffer sizes are a row's @c OptionScale::KernelDoubles, the hop limit is +/// `IP_TTL` in one family's row and `IPV6_UNICAST_HOPS` in the other's. + +#include +#include + +#include +#include + +namespace core::net +{ + +/// An option of a TCP socket that a caller sets and reads back. +/// +/// Values are unsigned integers in the unit the option's row states: bytes for the buffers, hops +/// for the hop limit, whole seconds for the keepalive intervals, a count of probes, and 0 or 1 for +/// the keepalive flag. +enum class SocketOption : std::uint8_t +{ + ReceiveBufferSize, ///< The kernel receive buffer, in bytes, as the caller asked for it. + SendBufferSize, ///< The kernel send buffer, in bytes, likewise. + UnicastHopLimit, ///< `IP_TTL` for IPv4, `IPV6_UNICAST_HOPS` for IPv6. + KeepAliveEnabled, ///< Whether the socket probes a silent peer: 0 or 1. + KeepAliveIdleTime, ///< Idle time before the first probe, in whole seconds. + KeepAliveInterval, ///< Time between probes, in whole seconds. + KeepAliveCount, ///< Unanswered probes before the connection is declared dead. + Last, ///< The number of options; not an option. +}; + +/// How a row's kernel value relates to the caller's. +enum class OptionScale : std::uint8_t +{ + Identity, ///< The kernel reports what was set. + KernelDoubles, ///< The kernel stores and reports twice what was set (Linux's `SO_RCVBUF`, `SO_SNDBUF`). + Seconds, ///< Whole seconds, the kernel's unit on every platform; a caller converts to it. + Flag, ///< A boolean: any non-zero value sets it, and it reads back as 0 or 1, whatever bit + ///< the kernel reports it with (macOS answers `SO_KEEPALIVE` with the option's own value). +}; + +/// One option, for one address family, on one platform. +struct SocketOptionRow +{ + SocketOption option = SocketOption::Last; ///< The option this row implements. + AddressFamily family = AddressFamily::Ipv4; ///< The family of socket it applies to. + int level = 0; ///< The `getsockopt`/`setsockopt` level. + int name = 0; ///< The option name at that level. + OptionScale scale = OptionScale::Identity; ///< How the kernel's value relates to the caller's. + + /// The largest value, in the caller's unit, the kernel takes without refusing it. A larger one + /// is clamped to this before it reaches the kernel, so setting an option never fails for being + /// too large: Linux refuses a keepalive count above 127 and macOS a buffer above its + /// `kern.ipc.maxsockbuf`, where WASI asks for a silent clamp. + std::uint64_t maximum = 0; +}; + +/// The platform's option rows: exactly one per option and family. +/// @return The rows, in static storage. +[[nodiscard]] CORE_NET_API std::span socketOptionTable() noexcept; + +} // namespace core::net diff --git a/src/core/net/SplitSocket.hpp b/src/core/net/SplitSocket.hpp index 164c70a3..cedf3d7f 100644 --- a/src/core/net/SplitSocket.hpp +++ b/src/core/net/SplitSocket.hpp @@ -10,9 +10,13 @@ /// other, closing both together. #include +#include +#include +#include #include #include +#include #include #include #include @@ -111,6 +115,31 @@ class SplitSocket final: public ISocket /// report the real peer address instead of the ISocket default (empty). [[nodiscard]] std::string peerAddress() const override { return _readHalf->peerAddress(); } + /// The read half's, for @c peerAddress's reason: it is the half that came from the peer. + [[nodiscard]] std::expected localEndpoint() const override + { + return _readHalf->localEndpoint(); + } + + /// The read half's, as @c localEndpoint is. + [[nodiscard]] std::expected remoteEndpoint() const override + { + return _readHalf->remoteEndpoint(); + } + + /// The read half's, as @c localEndpoint is: the half that came from the peer is the one with a + /// connection to configure. + [[nodiscard]] std::expected option(SocketOption option) const override + { + return _readHalf->option(option); + } + + /// Set on the read half, as @c option reads it. + [[nodiscard]] std::expected setOption(SocketOption option, std::uint64_t value) override + { + return _readHalf->setOption(option, value); + } + private: std::unique_ptr _readHalf; std::unique_ptr _writeHalf; diff --git a/src/core/net/TcpSocket.cpp b/src/core/net/TcpSocket.cpp new file mode 100644 index 00000000..b5c77855 --- /dev/null +++ b/src/core/net/TcpSocket.cpp @@ -0,0 +1,169 @@ +// SPDX-License-Identifier: Apache-2.0 + +/// @file +/// `openTcpSocket` and the one `ITcpSocket` implementation: the lifecycle, written once over the +/// platform's three primitives (`detail/TcpSocketPrimitives.hpp`) and the two dials. + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace core::net +{ + +namespace +{ + /// @return The refusal of a socket that `connect` or `listen` consumed. + [[nodiscard]] NetError consumed(char const* operation) + { + return makeNetError(NetErrorCode::BadHandle, 0, operation); + } + + /// @return A task that answers @p error without touching any socket. + async::Task refuse(NetError error) + { + co_return std::unexpected(std::move(error)); + } + + /// @return @p family's wildcard address at port 0. + [[nodiscard]] ResolvedEndpoint wildcardOf(AddressFamily family) noexcept + { + if (family == AddressFamily::Ipv6) + return toEndpoint(IpSocketAddress { .address = Ipv6Address {} }); + return toEndpoint(IpSocketAddress { .address = Ipv4Address {} }); + } + + /// An unconnected TCP socket. It owns its handle until `connect` or a successful `listen` hands + /// it on; from then on @c _socket is empty, which is the whole of the consumed state. + class TcpSocket final: public ITcpSocket + { + public: + /// @param loop The loop the socket is pinned to. + /// @param family The family it was opened with: it picks the option rows and the wildcard. + /// @param socket The open, unbound socket. + TcpSocket(EventLoop& loop, AddressFamily family, detail::DialSocket socket): + _loop { loop }, _family { family }, _socket { std::in_place, std::move(socket) } + { + } + + [[nodiscard]] std::expected bind(ResolvedEndpoint const& local) override + { + if (!_socket.has_value()) + return std::unexpected(consumed("bind on a consumed TCP socket")); + // Refused here rather than by the kernel, whose second bind is an `EINVAL` that reads + // like a bad address. + if (_binding == detail::LocalBinding::Bound) + return std::unexpected(consumed("bind on a TCP socket that is already bound")); + auto const handle = _socket->handles().socket; + for (auto const option: detail::reuseAddressOptions()) + if (auto set = detail::setIntOption(handle, option, 1); !set.has_value()) + return std::unexpected(std::move(set.error())); + return detail::bindTcpHandle(handle, local).transform([this] { + _binding = detail::LocalBinding::Bound; + }); + } + + [[nodiscard]] async::Task connect(ResolvedEndpoint remote) override + { + if (!_socket.has_value()) + return refuse(consumed("connect on a consumed TCP socket")); + + // Taken NOW, not when the task first runs: the task owns the socket from here, and closes + // it if it is dropped unstarted. + auto socket = std::move(*_socket); + _socket.reset(); + auto const max = platform::SteadyTimePoint::max(); + + // The loop decides, as it does for a connector: a completion port where it lends one + // (Windows, where every loop that can serve a socket does), readiness everywhere else. + if (_loop.completionPort() != nullptr) + return detail::dialCompletionOn( + &_loop, std::move(socket), _binding, remote, max, detail::StreamSocketOptions {}); + return detail::dialReadinessOn( + &_loop, std::move(socket), remote, max, detail::StreamSocketOptions {}); + } + + [[nodiscard]] std::expected, NetError> listen( + std::uint32_t backlog) override + { + if (!_socket.has_value()) + return std::unexpected(consumed("listen on a consumed TCP socket")); + + // Explicitly, on every platform: Windows refuses to listen on an unbound socket. + if (_binding == detail::LocalBinding::Unbound) + if (auto bound = bind(wildcardOf(_family)); !bound.has_value()) + return std::unexpected(std::move(bound.error())); + + auto const handle = _socket->handles().socket; + auto const clamped = static_cast(std::min(backlog, INT_MAX)); + if (auto listening = detail::listenTcpHandle(handle, clamped); !listening.has_value()) + return std::unexpected(std::move(listening.error())); + + // Listening from here, so it can never connect: a failure to adopt it consumes it too, + // rather than leaving a socket whose next `connect` the kernel refuses. + auto adopted = adoptListener(_loop, handle); + if (adopted.has_value()) + std::ignore = _socket->release(); // the listener closes the handle now + _socket.reset(); + return adopted; + } + + [[nodiscard]] std::expected localEndpoint() const override + { + if (!_socket.has_value()) + return std::unexpected(consumed("localEndpoint on a consumed TCP socket")); + // Not asked of the OS: an unbound socket is the wildcard at port 0 on POSIX and an error + // on Windows, and one answer on every platform is the point. + if (_binding == detail::LocalBinding::Unbound) + return std::unexpected(consumed("localEndpoint on an unbound TCP socket")); + return detail::socketEndpoint(_socket->handles().socket, detail::SocketSide::Local); + } + + [[nodiscard]] std::expected option(SocketOption option) const override + { + if (!_socket.has_value()) + return std::unexpected(consumed("option on a consumed TCP socket")); + return detail::readSocketOption(_socket->handles().socket, _family, option); + } + + [[nodiscard]] std::expected setOption(SocketOption option, + std::uint64_t value) override + { + if (!_socket.has_value()) + return std::unexpected(consumed("setOption on a consumed TCP socket")); + return detail::writeSocketOption(_socket->handles().socket, _family, option, value); + } + + private: + EventLoop& _loop; + AddressFamily _family; + std::optional _socket; + detail::LocalBinding _binding = detail::LocalBinding::Unbound; + }; +} // namespace + +std::expected, NetError> openTcpSocket(EventLoop& loop, AddressFamily family) +{ + // Before the socket exists, as a dial asks: a loop that could not adopt the connection or the + // listener this socket becomes refuses it now, not at the connect. + return detail::dialableOn(loop) + .and_then([family] { return detail::openTcpHandles(family); }) + .transform([&loop, family](detail::DialHandles handles) -> std::unique_ptr { + return std::make_unique(loop, family, detail::DialSocket { &loop, handles }); + }); +} + +} // namespace core::net diff --git a/src/core/net/TcpSocket_test.cpp b/src/core/net/TcpSocket_test.cpp new file mode 100644 index 00000000..f45eaedd --- /dev/null +++ b/src/core/net/TcpSocket_test.cpp @@ -0,0 +1,828 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// `ITcpSocket`: an unconnected TCP socket that binds, then connects or listens, and the +// `SocketOption`s it, a connected `ISocket` and an `IListener` set and read back. +// +// **Every case runs over the platform's real sockets**, because each property is the kernel's: which +// port a bind got, whether a port in TIME_WAIT may be bound again, what a buffer size reads back as. +// A double could only agree with itself. +#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 +#include +#include +#include +#include +#include +#include + +using core::async::Task; +using core::net::AddressFamily; +using core::net::EventLoop; +using core::net::IListener; +using core::net::IpSocketAddress; +using core::net::Ipv4Address; +using core::net::Ipv6Address; +using core::net::ISocket; +using core::net::ITcpSocket; +using core::net::NetError; +using core::net::NetErrorCode; +using core::net::OptionScale; +using core::net::ResolvedEndpoint; +using core::net::SocketOption; +using core::net::SocketResult; + +namespace +{ + +/// Which handle a platform hands out next. +enum class HandleOrder : std::uint8_t +{ + Unordered, ///< Any (Windows' socket handles). + LowestFirst, ///< The lowest free one, as POSIX requires of a descriptor. +}; + +#ifdef _WIN32 +constexpr auto NativeHandleOrder = HandleOrder::Unordered; +#else +constexpr auto NativeHandleOrder = HandleOrder::LowestFirst; +#endif + +/// @return The loopback address of @p family, at @p port. +[[nodiscard]] ResolvedEndpoint loopback(AddressFamily family, std::uint16_t port) +{ + if (family == AddressFamily::Ipv6) + return core::net::toEndpoint( + IpSocketAddress { .address = Ipv6Address { { 0, 0, 0, 0, 0, 0, 0, 1 } }, .port = port }); + return core::net::toEndpoint( + IpSocketAddress { .address = Ipv4Address { { 127, 0, 0, 1 } }, .port = port }); +} + +/// @return The IP form of @p endpoint, which the case requires to exist. +[[nodiscard]] IpSocketAddress ipOf(std::expected const& endpoint) +{ + REQUIRE(endpoint.has_value()); + auto address = core::net::toIpSocketAddress(*endpoint); + REQUIRE(address.has_value()); + return *address; +} + +/// @return Whether @p result failed with @p code. +template +[[nodiscard]] bool failedWith(std::expected const& result, NetErrorCode code) +{ + return !result.has_value() && result.error().code == code; +} + +/// @return Whether @p result is the socket's own refusal of a consumed or closed handle: +/// @c BadHandle with no system code, which a call that reached the OS would carry. +template +[[nodiscard]] bool refusedAsConsumed(std::expected const& result) +{ + return failedWith(result, NetErrorCode::BadHandle) && result.error().systemCode == 0; +} + +/// A loop over the platform's default backend, kept alive with it. +struct Loop +{ + std::unique_ptr backend = core::net::makeDefaultBackend(); + EventLoop loop { *backend }; +}; + +/// Runs @p task on @p loop, and fails the case -- naming it -- if the task has not finished within +/// @p limit: every kernel wait in this file is bounded here, so a socket that never becomes ready +/// fails one case rather than hanging the binary into its TIMEOUT. +/// @param loop The loop. +/// @param task The flow to run; stopped if it runs out of time. +/// @param limit How long it may take. +void blockOnWithin(EventLoop& loop, + Task task, + std::chrono::milliseconds limit = std::chrono::seconds { 5 }) +{ + auto finished = false; + auto run = [](Task inner, bool* done) -> Task { + co_await std::move(inner); + *done = true; + }; + loop.blockOn(core::net::testing::anyOf(run(std::move(task), &finished), + core::net::testing::sleepFor(&loop, limit))); + if (!finished) + FAIL("a socket wait in \"" << Catch::getResultCapture().getCurrentTestName() << "\" took longer than " + << limit.count() << " ms"); +} + +/// @return An open, unbound TCP socket of @p family, or a SKIP where the host has no such family. +[[nodiscard]] std::unique_ptr openOrSkip(EventLoop& loop, AddressFamily family) +{ + auto opened = core::net::openTcpSocket(loop, family); + if (!opened.has_value() && family == AddressFamily::Ipv6) + SKIP("this host has no IPv6: " << opened.error().toString()); + REQUIRE(opened.has_value()); + return std::move(*opened); +} + +/// @return A listener on @p family's loopback at an ephemeral port, made through @c ITcpSocket, +/// or a SKIP where the host has no IPv6 loopback. +[[nodiscard]] std::unique_ptr listenOnLoopback(EventLoop& loop, AddressFamily family) +{ + auto socket = openOrSkip(loop, family); + auto const bound = socket->bind(loopback(family, 0)); + if (!bound.has_value() && family == AddressFamily::Ipv6) + SKIP("this host has no IPv6 loopback: " << bound.error().toString()); + REQUIRE(bound.has_value()); + auto listener = socket->listen(16); + REQUIRE(listener.has_value()); + return std::move(*listener); +} + +/// Connects @p socket to @p remote, then accepts on @p listener: the connect completes out of the +/// kernel's backlog before anything accepts, so the two run in sequence on one loop. +Task connectAndAccept(ITcpSocket* socket, + ResolvedEndpoint remote, + IListener* listener, + SocketResult* connected, + SocketResult* accepted) +{ + *connected = co_await socket->connect(remote); + if (!connected->has_value()) + co_return; + *accepted = co_await listener->accept(); +} + +/// The two ends of one loopback connection. +struct Connection +{ + std::unique_ptr client; ///< The end an @c ITcpSocket connected. + std::unique_ptr accepted; ///< The end the listener handed out. +}; + +/// @return A connection from a fresh @c ITcpSocket of @p family to @p listener. +[[nodiscard]] Connection connectTo(EventLoop& loop, AddressFamily family, IListener& listener) +{ + auto socket = openOrSkip(loop, family); + auto connected = SocketResult {}; + auto accepted = SocketResult {}; + blockOnWithin( + loop, + connectAndAccept( + socket.get(), loopback(family, listener.boundPort()), &listener, &connected, &accepted)); + REQUIRE(connected.has_value()); + REQUIRE(accepted.has_value()); + return Connection { .client = std::move(*connected), .accepted = std::move(*accepted) }; +} + +/// What one option is set to, and what it must read back as. +struct OptionCase +{ + SocketOption option; + std::uint64_t value; +}; + +/// **One row per option, and the case below requires one for EVERY option**, so an option added to +/// the enum without a value to test it with fails here rather than going untested. +/// +/// The values are ones every platform keeps exactly: buffer sizes well inside Linux's default +/// `rmem_max`/`wmem_max` and above every minimum, a hop limit no stack rounds, keepalive intervals +/// in whole seconds. +constexpr auto OptionCases = std::array { + OptionCase { .option = SocketOption::ReceiveBufferSize, .value = 65'536 }, + OptionCase { .option = SocketOption::SendBufferSize, .value = 65'536 }, + OptionCase { .option = SocketOption::UnicastHopLimit, .value = 42 }, + OptionCase { .option = SocketOption::KeepAliveEnabled, .value = 1 }, + OptionCase { .option = SocketOption::KeepAliveIdleTime, .value = 30 }, + OptionCase { .option = SocketOption::KeepAliveInterval, .value = 7 }, + OptionCase { .option = SocketOption::KeepAliveCount, .value = 5 }, +}; + +/// @return Every option the enum names, in order. +[[nodiscard]] auto allOptions() +{ + return std::views::iota(0, static_cast(SocketOption::Last)) + | std::views::transform([](int index) { return static_cast(index); }); +} + +/// Sets every option through @p set and reads it back through @p get, which are one object's. +template +void requireEveryOptionReadsBack(Set set, Get get) +{ + for (auto const option: allOptions()) + { + auto const row = std::ranges::find(OptionCases, option, &OptionCase::option); + INFO("option " << static_cast(option)); + REQUIRE(row != OptionCases.end()); + auto const written = set(option, row->value); + INFO((written.has_value() ? std::string {} : written.error().toString())); + REQUIRE(written.has_value()); + auto const read = get(option); + INFO((read.has_value() ? std::string {} : read.error().toString())); + REQUIRE(read.has_value()); + CHECK(*read == row->value); + } +} + +/// @return The family a case runs over, from a generator. +[[nodiscard]] AddressFamily generatedFamily() +{ + return GENERATE(AddressFamily::Ipv4, AddressFamily::Ipv6); +} + +/// A socket that answers every option with a fixed value and records what it was asked to set: +/// the one way to tell a forwarded option from the base class's @c Unsupported default. +class OptionRecordingSocket final: public core::net::testing::SocketDecorator +{ + public: + using SocketDecorator::SocketDecorator; + + [[nodiscard]] std::expected option(SocketOption option) const override + { + return static_cast(option) + 100; + } + + [[nodiscard]] std::expected setOption(SocketOption option, std::uint64_t value) override + { + lastSet = std::pair { option, value }; + return {}; + } + + std::optional> lastSet; ///< What @c setOption last saw. +}; + +/// Whether an arranged connect stays outstanding, and to where. +struct PendingTarget +{ + std::unique_ptr listener; ///< A listener whose backlog is full, if that is the arrangement. + std::vector> fill; ///< The connections that filled it. + std::optional endpoint; ///< Where a connect stays outstanding; unset if nowhere. +}; + +/// Fills a backlog-1 listener with bounded dials until one runs out of time, which is the proof the +/// next connect to it stays outstanding. Bounded per dial, so the arrangement cannot become the hang +/// it is arranging; a stack that over-accepts leaves @c PendingTarget::endpoint unset. +Task arrangePendingTarget(EventLoop* loop, PendingTarget* out) +{ + auto socket = core::net::openTcpSocket(*loop, AddressFamily::Ipv4); + if (!socket.has_value() || !(*socket)->bind(loopback(AddressFamily::Ipv4, 0)).has_value()) + co_return; + auto listener = (*socket)->listen(1); + if (!listener.has_value()) + co_return; + out->listener = std::move(*listener); + auto const port = out->listener->boundPort(); + + constexpr auto Fill = 32; + auto resolver = core::net::InlineAddressResolver {}; + for ([[maybe_unused]] auto const attempt: std::views::iota(0, Fill)) + { + auto dialled = co_await core::net::connect( + loop, + "127.0.0.1", + port, + &resolver, + core::net::DialOptions { .connectTimeout = std::chrono::milliseconds { 300 } }); + if (!dialled.has_value()) + { + if (dialled.error().code == NetErrorCode::Timeout) + out->endpoint = loopback(AddressFamily::Ipv4, port); + co_return; + } + out->fill.push_back(std::move(*dialled)); + } +} + +} // namespace + +TEST_CASE("A TCP socket bound to port 0 reports the port the kernel chose", "[net][tcp-socket][loopback]") +{ + auto const family = generatedFamily(); + auto context = Loop {}; + auto socket = openOrSkip(context.loop, family); + + // Unbound, the answer is the socket's own, on every platform: no wildcard-at-port-0 here and an + // error there. + CHECK(refusedAsConsumed(socket->localEndpoint())); + + auto const bound = socket->bind(loopback(family, 0)); + if (!bound.has_value() && family == AddressFamily::Ipv6) + SKIP("this host has no IPv6 loopback: " << bound.error().toString()); + REQUIRE(bound.has_value()); + + // A second bind is refused before the kernel, which would answer an `EINVAL` that reads like a + // bad address. + CHECK(refusedAsConsumed(socket->bind(loopback(family, 0)))); + + auto const local = ipOf(socket->localEndpoint()); + CHECK(local.family() == family); + CHECK(local.port != 0); + CHECK(local.address == ipOf(loopback(family, 0)).address); +} + +TEST_CASE("A TCP socket bound to a chosen port connects from it", "[net][tcp-socket][loopback]") +{ + auto const family = generatedFamily(); + auto context = Loop {}; + auto listener = listenOnLoopback(context.loop, family); + + // A port the kernel just handed out, then gave back: free, and chosen by this case rather than + // by the connect. + auto const chosen = [&] { + auto probe = openOrSkip(context.loop, family); + REQUIRE(probe->bind(loopback(family, 0)).has_value()); + return ipOf(probe->localEndpoint()).port; + }(); + REQUIRE(chosen != 0); + + auto socket = openOrSkip(context.loop, family); + REQUIRE(socket->bind(loopback(family, chosen)).has_value()); + auto connected = SocketResult {}; + auto accepted = SocketResult {}; + blockOnWithin( + context.loop, + connectAndAccept( + socket.get(), loopback(family, listener->boundPort()), listener.get(), &connected, &accepted)); + REQUIRE(connected.has_value()); + REQUIRE(accepted.has_value()); + + // The server sees the port the client chose, and so does the client. + CHECK(ipOf((*accepted)->remoteEndpoint()).port == chosen); + CHECK(ipOf((*connected)->localEndpoint()).port == chosen); + CHECK(ipOf((*connected)->remoteEndpoint()).port == listener->boundPort()); +} + +TEST_CASE("A TCP socket rebinds a port in TIME_WAIT, and not one a listener holds", + "[net][tcp-socket][loopback]") +{ + auto context = Loop {}; + auto& loop = context.loop; + auto listener = listenOnLoopback(loop, AddressFamily::Ipv4); + auto const port = listener->boundPort(); + + SECTION("a second bind while the listener is live is AddressInUse") + { + auto second = openOrSkip(loop, AddressFamily::Ipv4); + CHECK(failedWith(second->bind(loopback(AddressFamily::Ipv4, port)), NetErrorCode::AddressInUse)); + } + + SECTION("a fresh socket binds and listens once the server closed first") + { + auto connection = connectTo(loop, AddressFamily::Ipv4, *listener); + + // The server closes first, which leaves ITS end in TIME_WAIT once the client's FIN arrives: + // the client reads the EOF, then closes too. + connection.accepted->close(); + auto drain = [](ISocket* client) -> Task { + auto buffer = std::array {}; + std::ignore = co_await client->read(buffer); + }; + blockOnWithin(loop, drain(connection.client.get())); + connection.client->close(); + loop.blockOn(core::net::testing::sleepFor(&loop, std::chrono::milliseconds { 50 })); + listener->close(); + listener.reset(); + connection = Connection {}; + + auto fresh = openOrSkip(loop, AddressFamily::Ipv4); + auto const rebound = fresh->bind(loopback(AddressFamily::Ipv4, port)); + INFO((rebound.has_value() ? std::string {} : rebound.error().toString())); + REQUIRE(rebound.has_value()); + auto relistened = fresh->listen(16); + REQUIRE(relistened.has_value()); + CHECK((*relistened)->boundPort() == port); + } +} + +TEST_CASE("Every socket option sets and reads back on an unconnected socket, a connection and a listener", + "[net][tcp-socket][socket-option][loopback]") +{ + auto const family = generatedFamily(); + auto context = Loop {}; + + SECTION("an unconnected socket") + { + auto socket = openOrSkip(context.loop, family); + requireEveryOptionReadsBack( + [&](SocketOption option, std::uint64_t value) { return socket->setOption(option, value); }, + [&](SocketOption option) { return socket->option(option); }); + } + SECTION("a listener") + { + auto listener = listenOnLoopback(context.loop, family); + requireEveryOptionReadsBack( + [&](SocketOption option, std::uint64_t value) { return listener->setOption(option, value); }, + [&](SocketOption option) { return listener->option(option); }); + } + SECTION("both ends of a connection") + { + auto listener = listenOnLoopback(context.loop, family); + auto connection = connectTo(context.loop, family, *listener); + for (auto* const end: { connection.client.get(), connection.accepted.get() }) + requireEveryOptionReadsBack( + [end](SocketOption option, std::uint64_t value) { return end->setOption(option, value); }, + [end](SocketOption option) { return end->option(option); }); + } +} + +TEST_CASE("Options set before a connect carry over to the connection", + "[net][tcp-socket][socket-option][loopback]") +{ + auto const family = generatedFamily(); + auto context = Loop {}; + auto listener = listenOnLoopback(context.loop, family); + auto socket = openOrSkip(context.loop, family); + + // Values no platform defaults to, so a connection that merely kept its defaults fails here. The + // connection is asked through its own route -- the family from `getsockname` -- and the socket + // through the family it was opened with: an IPv6 connection that read the IPv4 hop limit row + // would answer `IP_TTL`'s default rather than this. + auto const values = std::array { + OptionCase { .option = SocketOption::UnicastHopLimit, .value = 23 }, + OptionCase { .option = SocketOption::KeepAliveEnabled, .value = 1 }, + OptionCase { .option = SocketOption::KeepAliveIdleTime, .value = 41 }, + OptionCase { .option = SocketOption::KeepAliveInterval, .value = 11 }, + OptionCase { .option = SocketOption::KeepAliveCount, .value = 6 }, + }; + for (auto const& [option, value]: values) + REQUIRE(socket->setOption(option, value).has_value()); + + auto connected = SocketResult {}; + auto accepted = SocketResult {}; + blockOnWithin( + context.loop, + connectAndAccept( + socket.get(), loopback(family, listener->boundPort()), listener.get(), &connected, &accepted)); + REQUIRE(connected.has_value()); + for (auto const& [option, value]: values) + { + INFO("option " << static_cast(option)); + CHECK((*connected)->option(option) == value); + } +} + +TEST_CASE("A keepalive flag reads back as 0 or 1, the hop limit as set, and every option clamps a huge value", + "[net][tcp-socket][socket-option]") +{ + auto const family = generatedFamily(); + auto context = Loop {}; + auto socket = openOrSkip(context.loop, family); + + // A kernel that reports the flag's own bit (macOS answers `SO_KEEPALIVE`'s value, 8) still reads + // back as 1: the value is a flag, not a bit pattern. + REQUIRE(socket->setOption(SocketOption::KeepAliveEnabled, 7).has_value()); + CHECK(socket->option(SocketOption::KeepAliveEnabled) == std::uint64_t { 1 }); + REQUIRE(socket->setOption(SocketOption::KeepAliveEnabled, 0).has_value()); + CHECK(socket->option(SocketOption::KeepAliveEnabled) == std::uint64_t { 0 }); + + REQUIRE(socket->setOption(SocketOption::UnicastHopLimit, 1).has_value()); + CHECK(socket->option(SocketOption::UnicastHopLimit) == std::uint64_t { 1 }); + REQUIRE(socket->setOption(SocketOption::UnicastHopLimit, 255).has_value()); + CHECK(socket->option(SocketOption::UnicastHopLimit) == std::uint64_t { 255 }); + + // Every option takes any value: one above the row's maximum is clamped to it, never refused + // and never truncated (2^64 - 1 would truncate to -1). Beyond the buffers, which the kernel caps + // further on its own, it reads back as exactly the row's maximum. + for (auto const& row: core::net::socketOptionTable()) + { + if (row.family != family) + continue; + INFO("option " << static_cast(row.option)); + auto const set = socket->setOption(row.option, std::numeric_limits::max()); + INFO((set.has_value() ? std::string {} : set.error().toString())); + REQUIRE(set.has_value()); + auto const read = socket->option(row.option); + REQUIRE(read.has_value()); + if (row.option == SocketOption::ReceiveBufferSize || row.option == SocketOption::SendBufferSize) + CHECK(*read > 0); + else + CHECK(*read == row.maximum); + } +} + +TEST_CASE("Kernel values convert by the row's scale, and values to the kernel clamp to the row", + "[net][socket-option]") +{ + using core::net::detail::fromKernel; + using core::net::detail::toKernel; + + struct FromCase + { + OptionScale scale; + int kernel; + std::uint64_t expected; + }; + // macOS answers SO_KEEPALIVE with the option's own bit, 8; Linux doubles a buffer. + constexpr auto FromCases = std::array { + FromCase { .scale = OptionScale::Flag, .kernel = 8, .expected = 1 }, + FromCase { .scale = OptionScale::Flag, .kernel = 0, .expected = 0 }, + FromCase { .scale = OptionScale::KernelDoubles, .kernel = 4096, .expected = 2048 }, + FromCase { .scale = OptionScale::Identity, .kernel = 4096, .expected = 4096 }, + FromCase { .scale = OptionScale::Seconds, .kernel = 30, .expected = 30 }, + FromCase { .scale = OptionScale::Identity, .kernel = -1, .expected = 0 }, + FromCase { .scale = OptionScale::KernelDoubles, .kernel = -4096, .expected = 0 }, + }; + for (auto const& [scale, kernel, expected]: FromCases) + { + INFO("scale " << static_cast(scale) << " kernel " << kernel); + CHECK(fromKernel(scale, kernel) == expected); + } + + auto const row = core::net::SocketOptionRow { .option = SocketOption::KeepAliveCount, + .family = AddressFamily::Ipv4, + .scale = OptionScale::Identity, + .maximum = 127 }; + CHECK(toKernel(row, 5) == 5); + CHECK(toKernel(row, 127) == 127); + CHECK(toKernel(row, 128) == 127); + CHECK(toKernel(row, (std::uint64_t { 1 } << 32U) + 5U) == 127); + auto const wide = core::net::SocketOptionRow { .maximum = std::numeric_limits::max() }; + CHECK(toKernel(wide, std::numeric_limits::max()) == std::numeric_limits::max()); +} + +TEST_CASE("Option rows cover every option for both families, once", "[net][socket-option]") +{ + auto const table = core::net::socketOptionTable(); + for (auto const option: allOptions()) + for (auto const family: { AddressFamily::Ipv4, AddressFamily::Ipv6 }) + { + INFO("option " << static_cast(option) << " family " << static_cast(family)); + CHECK(std::ranges::count_if(table, + [&](core::net::SocketOptionRow const& row) { + return row.option == option && row.family == family; + }) + == 1); + } + + // The keepalive intervals are whole seconds on every platform, which is what a caller converts to; + // every row has a maximum to clamp to, inside `int`; a flag's is 1. + for (auto const& row: table) + { + INFO("option " << static_cast(row.option)); + if (row.option == SocketOption::KeepAliveIdleTime || row.option == SocketOption::KeepAliveInterval) + CHECK(row.scale == OptionScale::Seconds); + CHECK(row.maximum > 0); + CHECK(row.maximum <= static_cast(std::numeric_limits::max())); + if (row.scale == OptionScale::Flag) + CHECK(row.maximum == 1); + } +} + +TEST_CASE("A connected TCP socket is consumed: every later call is BadHandle", "[net][tcp-socket][loopback]") +{ + auto context = Loop {}; + auto listener = listenOnLoopback(context.loop, AddressFamily::Ipv4); + auto socket = openOrSkip(context.loop, AddressFamily::Ipv4); + auto const remote = loopback(AddressFamily::Ipv4, listener->boundPort()); + + auto connected = SocketResult {}; + auto accepted = SocketResult {}; + blockOnWithin(context.loop, + connectAndAccept(socket.get(), remote, listener.get(), &connected, &accepted)); + REQUIRE(connected.has_value()); + + auto again = SocketResult {}; + auto connectAgain = [](ITcpSocket* tcp, ResolvedEndpoint to, SocketResult* out) -> Task { + *out = co_await tcp->connect(to); + }; + blockOnWithin(context.loop, connectAgain(socket.get(), remote, &again)); + CHECK(refusedAsConsumed(again)); + CHECK(refusedAsConsumed(socket->listen(1))); + CHECK(refusedAsConsumed(socket->bind(loopback(AddressFamily::Ipv4, 0)))); + CHECK(refusedAsConsumed(socket->localEndpoint())); + CHECK(refusedAsConsumed(socket->option(SocketOption::KeepAliveEnabled))); + CHECK(refusedAsConsumed(socket->setOption(SocketOption::KeepAliveEnabled, 1))); +} + +TEST_CASE("A listening TCP socket is consumed too", "[net][tcp-socket][loopback]") +{ + auto context = Loop {}; + auto socket = openOrSkip(context.loop, AddressFamily::Ipv4); + REQUIRE(socket->bind(loopback(AddressFamily::Ipv4, 0)).has_value()); + auto listener = socket->listen(4); + REQUIRE(listener.has_value()); + + auto again = SocketResult {}; + auto connectAfterListen = [](ITcpSocket* tcp, ResolvedEndpoint to, SocketResult* out) -> Task { + *out = co_await tcp->connect(to); + }; + blockOnWithin( + context.loop, + connectAfterListen(socket.get(), loopback(AddressFamily::Ipv4, (*listener)->boundPort()), &again)); + CHECK(refusedAsConsumed(again)); + CHECK(refusedAsConsumed(socket->listen(4))); +} + +TEST_CASE("A connect task that never runs still closes its socket", "[net][tcp-socket]") +{ + auto context = Loop {}; + + // The handle the platform hands out next. Where it hands out the lowest free one (POSIX), a + // socket that was not closed makes the next one differ; a platform that does not is not asked. + // Windows is not asked even where the probe below happens to agree: its handle values follow no + // order, and the loop's own threads open handles between two probes (CI: 0x238 after 0x1e4). + auto const nextHandle = [] { + return core::net::testing::RawSocket { core::net::testing::openRawTcpSocket() }.get(); + }; + auto const lowestFirst = [&] { + auto first = core::net::testing::RawSocket { core::net::testing::openRawTcpSocket() }; + // Held open across the probe, so the freed handle is not merely the highest one. + auto const second = core::net::testing::RawSocket { core::net::testing::openRawTcpSocket() }; + auto const held = first.get(); + core::net::testing::closeRawSocket(first.release()); + return NativeHandleOrder == HandleOrder::LowestFirst && held != core::platform::InvalidHandle + && second.get() != held && nextHandle() == held; + }(); + auto const before = nextHandle(); + + auto socket = openOrSkip(context.loop, AddressFamily::Ipv4); + { + // Consumed at the call, not at the first resumption: the task holds the handle, and + // dropping the task unstarted closes it. + [[maybe_unused]] auto const unstarted = socket->connect(loopback(AddressFamily::Ipv4, 9)); + CHECK(refusedAsConsumed(socket->localEndpoint())); + } + CHECK(refusedAsConsumed(socket->listen(1))); + if (lowestFirst) + CHECK(nextHandle() == before); +} + +TEST_CASE("Listening on an unbound TCP socket binds the wildcard address", "[net][tcp-socket][loopback]") +{ + auto const family = generatedFamily(); + auto context = Loop {}; + auto socket = openOrSkip(context.loop, family); + auto listener = socket->listen(8); + if (!listener.has_value() && family == AddressFamily::Ipv6) + SKIP("this host cannot listen on IPv6: " << listener.error().toString()); + REQUIRE(listener.has_value()); + + auto const local = ipOf((*listener)->localEndpoint()); + CHECK(local.family() == family); + CHECK(local.port != 0); + CHECK(local.port == (*listener)->boundPort()); + auto const wildcard = family == AddressFamily::Ipv6 + ? std::variant { Ipv6Address {} } + : std::variant { Ipv4Address {} }; + CHECK(local.address == wildcard); + + // The wildcard bind is this library's, not the kernel's implicit one at `listen`: it set the + // platform's reuse-address options first, as every bind here does. + for (auto const option: core::net::detail::reuseAddressOptions()) + { + auto const value = core::net::detail::getIntOption((*listener)->nativeHandle(), option); + REQUIRE(value.has_value()); + CHECK(*value != 0); // macOS reports the option's own bit rather than 1 + } + + // Wildcard, so the loopback reaches it. + auto connection = connectTo(context.loop, family, **listener); + CHECK(ipOf(connection.accepted->localEndpoint()).port == local.port); +} + +TEST_CASE("An IPv6 TCP socket is IPv6-only", "[net][tcp-socket][loopback]") +{ + auto context = Loop {}; + auto socket = openOrSkip(context.loop, AddressFamily::Ipv6); + auto listener = socket->listen(8); + if (!listener.has_value()) + SKIP("this host cannot listen on IPv6: " << listener.error().toString()); + REQUIRE(listener.has_value()); + + // An IPv4 dial to the IPv6 wildcard's port finds nothing there: the socket does not take IPv4 + // on every platform alike, whatever the system's `bindv6only` default. + auto client = openOrSkip(context.loop, AddressFamily::Ipv4); + auto answer = SocketResult {}; + auto dial = [](ITcpSocket* tcp, ResolvedEndpoint to, SocketResult* out) -> Task { + *out = co_await tcp->connect(to); + }; + blockOnWithin(context.loop, + dial(client.get(), loopback(AddressFamily::Ipv4, (*listener)->boundPort()), &answer)); + CHECK(failedWith(answer, NetErrorCode::ConnRefused)); +} + +TEST_CASE("A stop during a TCP connect throws, and closing a listener ends its accept with Cancelled", + "[net][tcp-socket][stop][loopback]") +{ + auto context = Loop {}; + auto& loop = context.loop; + + SECTION("a stop of the flow unwinds a connect left outstanding") + { + auto target = PendingTarget {}; + blockOnWithin(loop, arrangePendingTarget(&loop, &target), std::chrono::seconds { 20 }); + if (!target.endpoint.has_value()) + SKIP("this stack completes a connect whose listener never accepts, so none could be left " + "outstanding to stop"); + + auto socket = openOrSkip(loop, AddressFamily::Ipv4); + auto answer = SocketResult {}; + auto threw = false; + auto dial = [](ITcpSocket* tcp, ResolvedEndpoint to, SocketResult* out, bool* unwound) -> Task { + try + { + *out = co_await tcp->connect(to); + } + catch (core::async::OperationCancelled const&) + { + *unwound = true; + } + }; + // The loser of an `anyOf` is stopped through its token and nothing else, so only the + // connect's own stop handling can end it; without it this case hangs into the binary's + // TIMEOUT rather than passing. + loop.blockOn(core::net::testing::anyOf( + dial(socket.get(), *target.endpoint, &answer, &threw), + core::net::testing::sleepFor(&loop, std::chrono::milliseconds { 100 }))); + CHECK(threw); + CHECK(loop.parkedWaiterCount() == 0); + } + + SECTION("closing the listener resolves a pending accept with Cancelled, as a value") + { + auto listener = listenOnLoopback(loop, AddressFamily::Ipv4); + auto accepted = SocketResult {}; + auto accept = [](IListener* from, SocketResult* out) -> Task { + *out = co_await from->accept(); + }; + auto closeAfter = [](EventLoop* lp, IListener* target) -> Task { + co_await lp->delay(std::chrono::milliseconds { 50 }); + target->close(); + }; + blockOnWithin( + loop, + core::net::testing::allOf(accept(listener.get(), &accepted), closeAfter(&loop, listener.get()))); + CHECK(failedWith(accepted, NetErrorCode::Cancelled)); + } +} + +TEST_CASE("Options default to Unsupported, and every decorator forwards them", "[net][socket-option]") +{ + auto pair = core::net::testing::InMemorySocketPair::create(); + auto& plain = *pair.client; + + CHECK(failedWith(plain.option(SocketOption::KeepAliveEnabled), NetErrorCode::Unsupported)); + CHECK(failedWith(plain.setOption(SocketOption::KeepAliveEnabled, 1), NetErrorCode::Unsupported)); + + auto recording = OptionRecordingSocket { plain }; + + SECTION("SocketDecorator") + { + // Named as an ISocket, or the braces would pick the decorator's deleted copy constructor. + auto& inner = static_cast(recording); + auto decorator = core::net::testing::SocketDecorator { inner }; + CHECK(decorator.option(SocketOption::KeepAliveCount) + == std::uint64_t { static_cast(SocketOption::KeepAliveCount) + 100 }); + REQUIRE(decorator.setOption(SocketOption::SendBufferSize, 4096).has_value()); + CHECK(recording.lastSet == std::pair { SocketOption::SendBufferSize, std::uint64_t { 4096 } }); + } + SECTION("SplitSocket, from its read half") + { + auto owned = std::make_unique(plain); + auto* const readHalf = owned.get(); + auto split = core::net::SplitSocket { std::move(owned), std::move(pair.server) }; + CHECK(split.option(SocketOption::UnicastHopLimit) + == std::uint64_t { static_cast(SocketOption::UnicastHopLimit) + 100 }); + REQUIRE(split.setOption(SocketOption::KeepAliveIdleTime, 9).has_value()); + CHECK(readHalf->lastSet == std::pair { SocketOption::KeepAliveIdleTime, std::uint64_t { 9 } }); + } + SECTION("a closed socket refuses without the OS") + { + auto context = Loop {}; + auto listener = listenOnLoopback(context.loop, AddressFamily::Ipv4); + auto connection = connectTo(context.loop, AddressFamily::Ipv4, *listener); + connection.client->close(); + listener->close(); + CHECK(refusedAsConsumed(connection.client->option(SocketOption::KeepAliveEnabled))); + CHECK(refusedAsConsumed(connection.client->setOption(SocketOption::KeepAliveEnabled, 1))); + CHECK(refusedAsConsumed(listener->option(SocketOption::KeepAliveEnabled))); + CHECK(refusedAsConsumed(listener->setOption(SocketOption::KeepAliveEnabled, 1))); + } +} diff --git a/src/core/net/Tls.cpp b/src/core/net/Tls.cpp index 61e93f89..52503505 100644 --- a/src/core/net/Tls.cpp +++ b/src/core/net/Tls.cpp @@ -8,7 +8,9 @@ #include #include #include +#include #include +#include #include #include @@ -28,6 +30,7 @@ #include #include #include +#include #include #include #include @@ -611,6 +614,31 @@ namespace [[nodiscard]] std::string peerAddress() const override { return _inner->peerAddress(); } + /// The INNER transport's: TLS records ride on its connection, which is what has an address. + [[nodiscard]] std::expected localEndpoint() const override + { + return _inner->localEndpoint(); + } + + /// The INNER transport's, as @c localEndpoint is. + [[nodiscard]] std::expected remoteEndpoint() const override + { + return _inner->remoteEndpoint(); + } + + /// The INNER transport's: the options are the TCP connection's, which TLS records ride on. + [[nodiscard]] std::expected option(SocketOption option) const override + { + return _inner->option(option); + } + + /// Set on the INNER transport, as @c option reads it. + [[nodiscard]] std::expected setOption(SocketOption option, + std::uint64_t value) override + { + return _inner->setOption(option, value); + } + /// Closes the inner transport, WITHOUT a `close_notify`: a synchronous `noexcept` close /// cannot await the write an alert needs. A caller that wants its peer to see an orderly /// end awaits @c shutdownWrite first. diff --git a/src/core/net/TlsSocket_test.cpp b/src/core/net/TlsSocket_test.cpp index bc719324..efea0eb9 100644 --- a/src/core/net/TlsSocket_test.cpp +++ b/src/core/net/TlsSocket_test.cpp @@ -18,11 +18,15 @@ #include #include #include +#include +#include +#include #include #include #include #include #include +#include #include #include @@ -31,6 +35,7 @@ #include #include #include +#include #include #include #include @@ -597,3 +602,90 @@ TEST_CASE("A TLS socket forwards armKeepAlive to its inner transport", "[net][tl CHECK(inner->keepAliveRequests().front().interval == settings.interval); CHECK(inner->keepAliveRequests().front().count == settings.count); } + +TEST_CASE("A TLS socket forwards its local and remote endpoints to its inner transport", + "[net][tls][endpoints]") +{ + auto loopBackend = core::net::makeDefaultBackend(); + auto loop = EventLoop { *loopBackend }; + auto context = core::net::makeSelfSignedServerContext(); + REQUIRE(context.has_value()); + + auto const clientAddress = core::net::IpSocketAddress { + .address = core::net::Ipv6Address { { 0x2001, 0x0db8, 0, 0, 0, 0, 0, 1 } }, .port = 50'001 + }; + auto const serverAddress = core::net::IpSocketAddress { + .address = core::net::Ipv6Address { { 0x2001, 0x0db8, 0, 0, 0, 0, 0, 2 } }, .port = 443 + }; + auto pair = core::net::testing::InMemorySocketPair::create( + 0, + {}, + core::net::testing::InMemoryPairEndpoints { .client = core::net::toEndpoint(clientAddress), + .server = core::net::toEndpoint(serverAddress) }); + auto tls = (*context)->wrap(std::move(pair.server), loop); + REQUIRE(tls != nullptr); + + // Through the IP form, so a TLS layer that answered from the base -- Unsupported -- fails here + // rather than comparing two errors equal. + auto const local = tls->localEndpoint().and_then(core::net::toIpSocketAddress); + auto const remote = tls->remoteEndpoint().and_then(core::net::toIpSocketAddress); + REQUIRE(local.has_value()); + REQUIRE(remote.has_value()); + CHECK(*local == serverAddress); + CHECK(*remote == clientAddress); +} + +namespace +{ + +/// An in-memory end that answers every option with a value of its own and records what it was +/// asked to set: the one way to tell a forwarded option from the base class's @c Unsupported. +class OptionRecordingSocket final: public core::net::testing::SocketDecorator +{ + public: + /// @param inner The end it wraps, owned. + explicit OptionRecordingSocket(std::unique_ptr inner): + SocketDecorator { *inner }, _inner { std::move(inner) } + { + } + + [[nodiscard]] std::expected option( + core::net::SocketOption option) const override + { + return static_cast(option) + 100; + } + + [[nodiscard]] std::expected setOption(core::net::SocketOption option, + std::uint64_t value) override + { + lastSet = std::pair { option, value }; + return {}; + } + + std::optional> lastSet; ///< What @c setOption last saw. + + private: + std::unique_ptr _inner; +}; + +} // namespace + +TEST_CASE("A TLS socket forwards socket options to its inner transport", "[net][tls][socket-option]") +{ + auto loopBackend = core::net::makeDefaultBackend(); + auto loop = EventLoop { *loopBackend }; + auto context = core::net::makeSelfSignedServerContext(); + REQUIRE(context.has_value()); + + auto pair = core::net::testing::InMemorySocketPair::create(); + auto recording = std::make_unique(std::move(pair.server)); + auto* const inner = recording.get(); + auto tls = (*context)->wrap(std::move(recording), loop); + REQUIRE(tls != nullptr); + + using core::net::SocketOption; + CHECK(tls->option(SocketOption::SendBufferSize) + == std::uint64_t { static_cast(SocketOption::SendBufferSize) + 100 }); + REQUIRE(tls->setOption(SocketOption::KeepAliveCount, 6).has_value()); + CHECK(inner->lastSet == std::pair { SocketOption::KeepAliveCount, std::uint64_t { 6 } }); +} diff --git a/src/core/net/detail/DialPrimitives.hpp b/src/core/net/detail/DialPrimitives.hpp index 09aee773..b2e58d01 100644 --- a/src/core/net/detail/DialPrimitives.hpp +++ b/src/core/net/detail/DialPrimitives.hpp @@ -25,6 +25,7 @@ #include #include #include +#include namespace core::net { @@ -80,6 +81,40 @@ namespace detail /// @param handles What to close; left invalid. CORE_NET_API void closeDialSocket(EventLoop* loop, DialHandles& handles) noexcept; + /// Owns what @c openDialSocket made, or a socket an @c ITcpSocket opened: closes it through + /// @c closeDialSocket unless it is released first. + /// + /// **What lets a dial take a socket by value into a lazy coroutine.** A task that is dropped + /// before it first runs destroys its parameters and nothing else, so a dial handed bare + /// @c DialHandles would leak them; handed this, it closes them. + class DialSocket + { + public: + /// @param loop The loop the readiness handle may be registered with; may be null. + /// @param handles The handles to own. + DialSocket(EventLoop* loop, DialHandles handles) noexcept: _loop { loop }, _handles { handles } {} + + ~DialSocket() { closeDialSocket(_loop, _handles); } + + DialSocket(DialSocket const&) = delete; + DialSocket& operator=(DialSocket const&) = delete; + DialSocket(DialSocket&& other) noexcept: + _loop { other._loop }, _handles { std::exchange(other._handles, DialHandles {}) } + { + } + DialSocket& operator=(DialSocket&&) = delete; + + /// @return The handles, still owned. + [[nodiscard]] DialHandles const& handles() const noexcept { return _handles; } + + /// @return The handles, no longer owned: the caller closes them. + [[nodiscard]] DialHandles release() noexcept { return std::exchange(_handles, DialHandles {}); } + + private: + EventLoop* _loop; + DialHandles _handles; + }; + /// Issues the non-blocking `::connect`. /// @param handles What @c openDialSocket produced. /// @param endpoint The address to dial. @@ -148,6 +183,49 @@ namespace detail platform::SteadyTimePoint deadline, StreamSocketOptions options); + /// `detail::dialReadiness` (`ReadinessDial.hpp`) on a socket the caller opened -- with + /// @c openDialSocket, or an @c ITcpSocket's, possibly bound: everything after the socket exists. + /// @param loop The loop the resulting socket is pinned to and whose backend watches the dial. + /// @param socket The socket; closed on every way out but the connected socket. + /// @param endpoint The address to dial; by value, for the coroutine-frame reason. + /// @param deadline When to give up; `SteadyTimePoint::max()` for never. + /// @param options As `dialReadiness`'s. + /// @return As `dialReadiness`. + /// @throws async::OperationCancelled as `dialReadiness`. + [[nodiscard]] CORE_NET_API async::Task dialReadinessOn(EventLoop* loop, + DialSocket socket, + ResolvedEndpoint endpoint, + platform::SteadyTimePoint deadline, + StreamSocketOptions options); + + /// Whether a socket handed to @c dialCompletionOn is already bound. + enum class LocalBinding : std::uint8_t + { + Unbound, ///< Bound to the family's wildcard address first, which `ConnectEx` requires. + Bound, ///< Bound by the caller; connected from that address. + }; + + /// @c dialCompletion on a socket the caller opened: an overlapped stream socket, not yet + /// associated with any completion port, possibly bound. + /// + /// For an @c ITcpSocket, which binds before it connects. @c dialCompletion is this on a socket + /// of its own. + /// @param loop The loop whose port completes the dial; not owned. + /// @param owned The socket; its readiness handle is unused. Closed on every way out but the + /// connected socket. + /// @param binding Whether @p owned is already bound. + /// @param endpoint The address to dial; by value, for the coroutine-frame reason. + /// @param deadline When to give up; `SteadyTimePoint::max()` for never. + /// @param options As @c dialCompletion's. + /// @return As @c dialCompletion. + /// @throws async::OperationCancelled as @c dialCompletion. + [[nodiscard]] CORE_NET_API async::Task dialCompletionOn(EventLoop* loop, + DialSocket owned, + LocalBinding binding, + ResolvedEndpoint endpoint, + platform::SteadyTimePoint deadline, + StreamSocketOptions options); + } // namespace detail } // namespace core::net diff --git a/src/core/net/detail/SocketEndpoint.hpp b/src/core/net/detail/SocketEndpoint.hpp new file mode 100644 index 00000000..41672817 --- /dev/null +++ b/src/core/net/detail/SocketEndpoint.hpp @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// `detail::socketEndpoint` -- `getsockname` and `getpeername` into a @c ResolvedEndpoint, the one +/// place each platform asks a socket for an address. Defined per platform, beside the platform's +/// other socket calls (`posix/SocketsPosix.cpp`, `windows/SocketsWin32.cpp`). Private to `core::net`. + +#include +#include +#include + +#include +#include + +namespace core::net::detail +{ + +/// Which end of a socket an address is asked of. +enum class SocketSide : std::uint8_t +{ + Local, ///< This end: `getsockname`. + Remote, ///< The peer: `getpeername`. +}; + +/// Asks @p socket for the address of its @p side. +/// @param socket An open socket; the caller has already refused a closed one. +/// @param side Which end's address. +/// @return The endpoint, or the classified OS error of the call. +[[nodiscard]] std::expected socketEndpoint(platform::NativeHandle socket, + SocketSide side); + +} // namespace core::net::detail diff --git a/src/core/net/detail/SocketOptionAccess.hpp b/src/core/net/detail/SocketOptionAccess.hpp new file mode 100644 index 00000000..8f901f6e --- /dev/null +++ b/src/core/net/detail/SocketOptionAccess.hpp @@ -0,0 +1,120 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// `detail::readSocketOption` and `detail::writeSocketOption` -- the one interpreter of +/// @c socketOptionTable, used by every socket, listener and unconnected TCP socket that answers +/// @c SocketOption -- and the two OS calls beneath it, defined per platform beside the table. + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace core::net::detail +{ + +/// One `getsockopt`/`setsockopt` address, for an option outside the @c SocketOption vocabulary. +struct NativeOption +{ + int level = 0; ///< The option level. + int name = 0; ///< The option name at that level. +}; + +/// The options a TCP bind sets to 1 first, so that a port whose last connection is in TIME_WAIT +/// can be bound again. +/// +/// `SO_REUSEADDR` on POSIX. **None on Windows** (P13 ruling R17, following WASI's `bind` and +/// wasmtime): Windows already allows that bind by default, and its `SO_REUSEADDR` would let the +/// socket take over a port another socket is listening on. +/// @return The rows, in static storage; possibly empty. +[[nodiscard]] CORE_NET_API std::span reuseAddressOptions() noexcept; + +/// The kernel's value as the caller's, by the row's scale. A negative kernel value, which no option +/// here has, reads as 0 rather than wrapping. +/// @param scale The row's scale. +/// @param kernel What `getsockopt` answered. +/// @return The value in the row's unit. +[[nodiscard]] constexpr std::uint64_t fromKernel(OptionScale scale, int kernel) noexcept +{ + auto const value = static_cast(std::max(kernel, 0)); + switch (scale) + { + case OptionScale::KernelDoubles: return value / 2; + case OptionScale::Flag: return value != 0 ? 1 : 0; + case OptionScale::Identity: + case OptionScale::Seconds: break; + } + return value; +} + +/// The caller's value as the kernel takes it: clamped to the row's maximum (and to `int`), whatever +/// the scale. A doubling kernel does the doubling itself, and a flag is set by any non-zero value, +/// which the clamp keeps non-zero. +/// @param row The option's row. +/// @param value The value in the row's unit. +/// @return What `setsockopt` is given. +[[nodiscard]] constexpr int toKernel(SocketOptionRow const& row, std::uint64_t value) noexcept +{ + return static_cast(std::min({ value, row.maximum, std::uint64_t { INT_MAX } })); +} + +/// `getsockopt` of an `int`-sized option. +/// @param socket The socket. +/// @param option Its level and name. +/// @return The value, or the classified OS error. +[[nodiscard]] CORE_NET_API std::expected getIntOption(platform::NativeHandle socket, + NativeOption option); + +/// `setsockopt` of an `int`-sized option. +/// @param socket The socket. +/// @param option Its level and name. +/// @param value The value. +/// @return Nothing, or the classified OS error. +[[nodiscard]] std::expected setIntOption(platform::NativeHandle socket, + NativeOption option, + int value); + +/// Reads @p option from @p socket, a socket of @p family, through its row. +/// @param socket The socket. +/// @param family The socket's address family, which picks the row. +/// @param option The option. +/// @return The value in the row's unit; @c NetErrorCode::Unsupported where the platform has no +/// row; otherwise the classified OS error. +[[nodiscard]] std::expected readSocketOption(platform::NativeHandle socket, + AddressFamily family, + SocketOption option); + +/// Sets @p option on @p socket, a socket of @p family, through its row; a @p value above the +/// platform's `int` range is clamped to it. +/// @param socket The socket. +/// @param family The socket's address family, which picks the row. +/// @param option The option. +/// @param value The value in the row's unit. +/// @return Nothing; @c NetErrorCode::Unsupported where the platform has no row; otherwise the +/// classified OS error. +[[nodiscard]] std::expected writeSocketOption(platform::NativeHandle socket, + AddressFamily family, + SocketOption option, + std::uint64_t value); + +/// @c readSocketOption for a bound socket, whose family is asked of the kernel (`getsockname`): +/// a connection or a listener, which do not keep it. +/// @return As @c readSocketOption; @c NetErrorCode::Unsupported for a socket that is no IP one. +[[nodiscard]] std::expected readSocketOption(platform::NativeHandle socket, + SocketOption option); + +/// @c writeSocketOption for a bound socket, as the overload above. +/// @return As @c writeSocketOption; @c NetErrorCode::Unsupported for a socket that is no IP one. +[[nodiscard]] std::expected writeSocketOption(platform::NativeHandle socket, + SocketOption option, + std::uint64_t value); + +} // namespace core::net::detail diff --git a/src/core/net/detail/TcpSocketPrimitives.hpp b/src/core/net/detail/TcpSocketPrimitives.hpp new file mode 100644 index 00000000..3f8193e0 --- /dev/null +++ b/src/core/net/detail/TcpSocketPrimitives.hpp @@ -0,0 +1,42 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// The three OS calls an @c ITcpSocket makes that differ by platform in more than a constant: +/// creating the socket, `bind` and `listen`. Defined in `posix/PosixTcpSocket.cpp` and +/// `windows/IocpTcpSocket.cpp`; the socket's lifecycle itself is written once, in `TcpSocket.cpp`. + +#include +#include +#include +#include +#include + +#include + +namespace core::net::detail +{ + +/// Creates an unbound TCP socket of @p family, of the kind the platform's dial takes: non-blocking +/// and close-on-exec on POSIX (what @c openDialSocket makes), overlapped and not inheritable on +/// Windows (what `ConnectEx` and `AcceptEx` need). An IPv6 socket is made IPv6-only. +/// @param family The address family. +/// @return The handles -- on Windows with no readiness event, which a completion-port socket does +/// not use -- or the classified OS error. +[[nodiscard]] std::expected openTcpHandles(AddressFamily family); + +/// `bind`, and nothing else: the reuse-address options are the caller's, from +/// @c reuseAddressOptions. +/// @param socket The socket. +/// @param local The address and port. +/// @return Nothing, or the classified OS error (@c NetErrorCode::AddressInUse for a port in use). +[[nodiscard]] std::expected bindTcpHandle(platform::NativeHandle socket, + ResolvedEndpoint const& local); + +/// `listen`. +/// @param socket A bound socket. +/// @param backlog The backlog, already clamped to `int`. +/// @return Nothing, or the classified OS error. +[[nodiscard]] std::expected listenTcpHandle(platform::NativeHandle socket, int backlog); + +} // namespace core::net::detail diff --git a/src/core/net/linux/AcceptedSocketOptions_test.cpp b/src/core/net/linux/AcceptedSocketOptions_test.cpp new file mode 100644 index 00000000..90b69536 --- /dev/null +++ b/src/core/net/linux/AcceptedSocketOptions_test.cpp @@ -0,0 +1,109 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// What a Linux listener's accepted connections inherit from it: every `SocketOption` set on the +// listening socket. Linux copies the listener's socket (`sk_clone_lock`) into each one it accepts, +// so this is a kernel property this library relies on, not one it implements. +// +// Linux only, by its source list. macOS does not carry the TCP keepalive intervals over to an +// accepted socket, and wasmtime re-applies some options to accepted sockets by hand for that reason; +// whether the WASI host must do the same is a P14 question. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include + +using core::async::Task; +using core::net::AddressFamily; +using core::net::IpSocketAddress; +using core::net::SocketOption; +using core::net::SocketResult; + +namespace +{ + +/// One option and the value the listener is given; none is a Linux default. +struct Inherited +{ + SocketOption option; + std::uint64_t value; +}; + +constexpr auto InheritedOptions = std::array { + Inherited { .option = SocketOption::ReceiveBufferSize, .value = 48'000 }, + Inherited { .option = SocketOption::SendBufferSize, .value = 40'000 }, + Inherited { .option = SocketOption::UnicastHopLimit, .value = 17 }, + Inherited { .option = SocketOption::KeepAliveEnabled, .value = 1 }, + Inherited { .option = SocketOption::KeepAliveIdleTime, .value = 43 }, + Inherited { .option = SocketOption::KeepAliveInterval, .value = 13 }, + Inherited { .option = SocketOption::KeepAliveCount, .value = 4 }, +}; + +/// Connects @p client to @p remote and accepts it on @p listener. +Task connectAndAccept(core::net::ITcpSocket* client, + core::net::ResolvedEndpoint remote, + core::net::IListener* listener, + SocketResult* connected, + SocketResult* accepted) +{ + *connected = co_await client->connect(remote); + if (connected->has_value()) + *accepted = co_await listener->accept(); +} + +} // namespace + +TEST_CASE("A Linux listener's accepted connections inherit its socket options", + "[net][tcp-socket][socket-option][loopback]") +{ + auto const family = GENERATE(AddressFamily::Ipv4, AddressFamily::Ipv6); + auto backend = core::net::makeDefaultBackend(); + auto loop = core::net::EventLoop { *backend }; + auto const loopback = + family == AddressFamily::Ipv6 + ? IpSocketAddress { .address = core::net::Ipv6Address { { 0, 0, 0, 0, 0, 0, 0, 1 } } } + : IpSocketAddress { .address = core::net::Ipv4Address { { 127, 0, 0, 1 } } }; + + auto server = core::net::openTcpSocket(loop, family); + REQUIRE(server.has_value()); + auto const bound = (*server)->bind(core::net::toEndpoint(loopback)); + if (!bound.has_value() && family == AddressFamily::Ipv6) + SKIP("this host has no IPv6 loopback: " << bound.error().toString()); + REQUIRE(bound.has_value()); + for (auto const& [option, value]: InheritedOptions) + REQUIRE((*server)->setOption(option, value).has_value()); + auto listener = (*server)->listen(4); + REQUIRE(listener.has_value()); + + auto client = core::net::openTcpSocket(loop, family); + REQUIRE(client.has_value()); + auto remote = loopback; + remote.port = (*listener)->boundPort(); + auto connected = SocketResult {}; + auto accepted = SocketResult {}; + loop.blockOn(core::net::testing::anyOf( + connectAndAccept( + client->get(), core::net::toEndpoint(remote), listener->get(), &connected, &accepted), + core::net::testing::sleepFor(&loop, std::chrono::seconds { 5 }))); + REQUIRE(accepted.has_value()); + + for (auto const& [option, value]: InheritedOptions) + { + INFO("option " << static_cast(option)); + CHECK((*accepted)->option(option) == value); + } +} diff --git a/src/core/net/posix/DialPrimitives.cpp b/src/core/net/posix/DialPrimitives.cpp index 8a93cebb..eeff1d1e 100644 --- a/src/core/net/posix/DialPrimitives.cpp +++ b/src/core/net/posix/DialPrimitives.cpp @@ -93,4 +93,16 @@ async::Task dialCompletion(EventLoop* /*loop*/, makeNetError(NetErrorCode::Unsupported, 0, "a completion-port dial on a platform without one")); } +async::Task dialCompletionOn(EventLoop* /*loop*/, + DialSocket /*socket*/, + LocalBinding /*binding*/, + ResolvedEndpoint /*endpoint*/, + platform::SteadyTimePoint /*deadline*/, + StreamSocketOptions /*options*/) +{ + // As `dialCompletion`; the socket closes with the frame. + co_return std::unexpected( + makeNetError(NetErrorCode::Unsupported, 0, "a completion-port dial on a platform without one")); +} + } // namespace core::net::detail diff --git a/src/core/net/posix/PosixListener.cpp b/src/core/net/posix/PosixListener.cpp index 47c27ae7..34324b46 100644 --- a/src/core/net/posix/PosixListener.cpp +++ b/src/core/net/posix/PosixListener.cpp @@ -2,7 +2,9 @@ #include #include +#include #include +#include #include #include #include @@ -212,6 +214,28 @@ std::expected, NetError> PosixListener::adopt(Eve return std::unique_ptr(new PosixListener(loop, fd, port)); } +std::expected PosixListener::localEndpoint() const +{ + if (_closed || _fd < 0) + return std::unexpected( + makeNetError(NetErrorCode::BadHandle, 0, "localEndpoint on a closed listener")); + return detail::socketEndpoint(_fd, detail::SocketSide::Local); +} + +std::expected PosixListener::option(SocketOption option) const +{ + if (_closed || _fd < 0) + return std::unexpected(makeNetError(NetErrorCode::BadHandle, 0, "option on a closed listener")); + return detail::readSocketOption(_fd, option); +} + +std::expected PosixListener::setOption(SocketOption option, std::uint64_t value) +{ + if (_closed || _fd < 0) + return std::unexpected(makeNetError(NetErrorCode::BadHandle, 0, "setOption on a closed listener")); + return detail::writeSocketOption(_fd, option, value); +} + async::Task PosixListener::accept() { // The shared loop records the TCP peer's printable host via formatPeer. diff --git a/src/core/net/posix/PosixListener.hpp b/src/core/net/posix/PosixListener.hpp index 345d970d..de2d431e 100644 --- a/src/core/net/posix/PosixListener.hpp +++ b/src/core/net/posix/PosixListener.hpp @@ -61,6 +61,15 @@ class PosixListener final: public IListener [[nodiscard]] std::uint16_t boundPort() const noexcept override { return _boundPort; } + /// @copydoc IListener::localEndpoint + [[nodiscard]] std::expected localEndpoint() const override; + + /// @copydoc IListener::option + [[nodiscard]] std::expected option(SocketOption option) const override; + + /// @copydoc IListener::setOption + [[nodiscard]] std::expected setOption(SocketOption option, std::uint64_t value) override; + /// @return The listening descriptor, or -1 once closed; for diagnostics and tests. [[nodiscard]] int native() const noexcept { return _fd; } diff --git a/src/core/net/posix/PosixSocket.cpp b/src/core/net/posix/PosixSocket.cpp index 4bcbdf63..02162156 100644 --- a/src/core/net/posix/PosixSocket.cpp +++ b/src/core/net/posix/PosixSocket.cpp @@ -2,7 +2,9 @@ #include #include +#include #include +#include #include #include #include // MSG_NOSIGNAL fallback, makeNonBlockingCloexec @@ -170,6 +172,34 @@ std::expected PosixSocket::armKeepAlive(KeepAliveSettings const& return detail::armKeepAlive(_fd, settings); } +std::expected PosixSocket::localEndpoint() const +{ + if (_closed || _fd < 0) + return std::unexpected(closedSocket("localEndpoint")); + return detail::socketEndpoint(_fd, detail::SocketSide::Local); +} + +std::expected PosixSocket::remoteEndpoint() const +{ + if (_closed || _fd < 0) + return std::unexpected(closedSocket("remoteEndpoint")); + return detail::socketEndpoint(_fd, detail::SocketSide::Remote); +} + +std::expected PosixSocket::option(SocketOption option) const +{ + if (_closed || _fd < 0) + return std::unexpected(closedSocket("option")); + return detail::readSocketOption(_fd, option); +} + +std::expected PosixSocket::setOption(SocketOption option, std::uint64_t value) +{ + if (_closed || _fd < 0) + return std::unexpected(closedSocket("setOption")); + return detail::writeSocketOption(_fd, option, value); +} + // ---- The read side ---------------------------------------------------------------------------- std::optional PosixSocket::tryRead(std::span buffer) diff --git a/src/core/net/posix/PosixSocket.hpp b/src/core/net/posix/PosixSocket.hpp index 0ae6c074..d8841ed9 100644 --- a/src/core/net/posix/PosixSocket.hpp +++ b/src/core/net/posix/PosixSocket.hpp @@ -68,6 +68,10 @@ class CORE_NET_API PosixSocket final: public ISocket [[nodiscard]] std::expected armKeepAlive(KeepAliveSettings const& settings) override; [[nodiscard]] std::string peerAddress() const override { return _peerAddress; } + [[nodiscard]] std::expected localEndpoint() const override; + [[nodiscard]] std::expected remoteEndpoint() const override; + [[nodiscard]] std::expected option(SocketOption option) const override; + [[nodiscard]] std::expected setOption(SocketOption option, std::uint64_t value) override; void close() noexcept override; diff --git a/src/core/net/posix/PosixTcpSocket.cpp b/src/core/net/posix/PosixTcpSocket.cpp new file mode 100644 index 00000000..2598a1fa --- /dev/null +++ b/src/core/net/posix/PosixTcpSocket.cpp @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: Apache-2.0 + +/// @file +/// The POSIX halves of an `ITcpSocket`: a non-blocking, close-on-exec socket, and plain `bind` and +/// `listen`. What it becomes is the readiness dial's `PosixSocket` or `adoptListener`'s +/// `PosixListener`. + +#include +#include +#include +#include + +#include + +#include +#include +#include + +#include + +#include + +namespace core::net::detail +{ + +std::expected openTcpHandles(AddressFamily family) +{ + auto const fd = makeStreamSocket(family == AddressFamily::Ipv6 ? AF_INET6 : AF_INET, 0); + if (fd < 0) + return std::unexpected(socketError(errno, "socket")); + + if (family == AddressFamily::Ipv6) + if (auto only = setIntOption(fd, NativeOption { .level = IPPROTO_IPV6, .name = IPV6_V6ONLY }, 1); + !only.has_value()) + { + ::close(fd); + return std::unexpected(std::move(only.error())); + } + + return DialHandles { .socket = fd, .readiness = fd, .kind = DefaultHandleKind }; +} + +std::expected bindTcpHandle(platform::NativeHandle socket, ResolvedEndpoint const& local) +{ + auto const* const address = reinterpret_cast(local.storage.data()); + if (::bind(socket, address, static_cast(local.length)) != 0) + return std::unexpected(socketError(errno, "bind")); + return {}; +} + +std::expected listenTcpHandle(platform::NativeHandle socket, int backlog) +{ + if (::listen(socket, backlog) != 0) + return std::unexpected(socketError(errno, "listen")); + return {}; +} + +} // namespace core::net::detail diff --git a/src/core/net/posix/SocketOptionTable.cpp b/src/core/net/posix/SocketOptionTable.cpp new file mode 100644 index 00000000..e824e054 --- /dev/null +++ b/src/core/net/posix/SocketOptionTable.cpp @@ -0,0 +1,122 @@ +// SPDX-License-Identifier: Apache-2.0 + +/// @file +/// The POSIX socket-option rows, and the two `int`-option calls beneath them. +/// +/// **The `#if`s below choose constants inside the data, never a branch in logic** (P13 ruling R11): +/// Linux doubles a buffer size it is given and reports the doubled value, the BSDs and macOS do +/// not, and macOS spells the keepalive idle time `TCP_KEEPALIVE` where the others say +/// `TCP_KEEPIDLE`. + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace core::net +{ + +namespace +{ +#ifdef __linux__ + /// Linux stores twice the buffer size it is given, and `getsockopt` reports the doubled value + /// (socket(7)). + constexpr auto BufferScale = OptionScale::KernelDoubles; + + /// Linux caps a buffer at `rmem_max`/`wmem_max` itself, silently, so any `int` is taken. + constexpr std::uint64_t BufferMaximum = INT_MAX; +#elifdef __APPLE__ + constexpr auto BufferScale = OptionScale::Identity; + + /// macOS refuses (`ENOBUFS`) a buffer above `kern.ipc.maxsockbuf` scaled by + /// `MCLBYTES / (MSIZE + MCLBYTES)`: 7456540 bytes at the default 8 MiB. A documented row value + /// rather than a runtime query, and conservative: 4 MiB stays under the default with room, at + /// the price of clamping below a limit an administrator raised. + constexpr std::uint64_t BufferMaximum = 4U * 1024U * 1024U; +#else + constexpr auto BufferScale = OptionScale::Identity; + + /// FreeBSD and the other BSDs refuse above the same scaled `kern.ipc.maxsockbuf`, whose default + /// is 2 MiB (1864135 bytes after scaling); 1 MiB stays under it, as macOS's row does. + constexpr std::uint64_t BufferMaximum = 1024U * 1024U; +#endif + + /// The keepalive limits Linux enforces (`MAX_TCP_KEEPIDLE`, `MAX_TCP_KEEPINTVL`, + /// `MAX_TCP_KEEPCNT`), which the BSDs and macOS take too: one bound for every POSIX system. + constexpr std::uint64_t KeepAliveTimeMaximum = 32'767; + constexpr std::uint64_t KeepAliveCountMaximum = 127; + + /// A hop limit is one octet on the wire. + constexpr std::uint64_t HopLimitMaximum = 255; + +#ifdef TCP_KEEPIDLE + constexpr int KeepAliveIdle = TCP_KEEPIDLE; +#else + constexpr int KeepAliveIdle = TCP_KEEPALIVE; // macOS: the same option, under its older name +#endif + + /// One row per option and family; the families differ only in the hop limit. + constexpr auto Rows = std::array { + // clang-format off + SocketOptionRow { SocketOption::ReceiveBufferSize, AddressFamily::Ipv4, SOL_SOCKET, SO_RCVBUF, BufferScale, BufferMaximum }, + SocketOptionRow { SocketOption::SendBufferSize, AddressFamily::Ipv4, SOL_SOCKET, SO_SNDBUF, BufferScale, BufferMaximum }, + SocketOptionRow { SocketOption::UnicastHopLimit, AddressFamily::Ipv4, IPPROTO_IP, IP_TTL, OptionScale::Identity, HopLimitMaximum }, + SocketOptionRow { SocketOption::KeepAliveEnabled, AddressFamily::Ipv4, SOL_SOCKET, SO_KEEPALIVE, OptionScale::Flag, 1 }, + SocketOptionRow { SocketOption::KeepAliveIdleTime, AddressFamily::Ipv4, IPPROTO_TCP, KeepAliveIdle, OptionScale::Seconds, KeepAliveTimeMaximum }, + SocketOptionRow { SocketOption::KeepAliveInterval, AddressFamily::Ipv4, IPPROTO_TCP, TCP_KEEPINTVL, OptionScale::Seconds, KeepAliveTimeMaximum }, + SocketOptionRow { SocketOption::KeepAliveCount, AddressFamily::Ipv4, IPPROTO_TCP, TCP_KEEPCNT, OptionScale::Identity, KeepAliveCountMaximum }, + SocketOptionRow { SocketOption::ReceiveBufferSize, AddressFamily::Ipv6, SOL_SOCKET, SO_RCVBUF, BufferScale, BufferMaximum }, + SocketOptionRow { SocketOption::SendBufferSize, AddressFamily::Ipv6, SOL_SOCKET, SO_SNDBUF, BufferScale, BufferMaximum }, + SocketOptionRow { SocketOption::UnicastHopLimit, AddressFamily::Ipv6, IPPROTO_IPV6, IPV6_UNICAST_HOPS, OptionScale::Identity, HopLimitMaximum }, + SocketOptionRow { SocketOption::KeepAliveEnabled, AddressFamily::Ipv6, SOL_SOCKET, SO_KEEPALIVE, OptionScale::Flag, 1 }, + SocketOptionRow { SocketOption::KeepAliveIdleTime, AddressFamily::Ipv6, IPPROTO_TCP, KeepAliveIdle, OptionScale::Seconds, KeepAliveTimeMaximum }, + SocketOptionRow { SocketOption::KeepAliveInterval, AddressFamily::Ipv6, IPPROTO_TCP, TCP_KEEPINTVL, OptionScale::Seconds, KeepAliveTimeMaximum }, + SocketOptionRow { SocketOption::KeepAliveCount, AddressFamily::Ipv6, IPPROTO_TCP, TCP_KEEPCNT, OptionScale::Identity, KeepAliveCountMaximum }, + // clang-format on + }; + + constexpr auto ReuseAddress = + std::array { detail::NativeOption { .level = SOL_SOCKET, .name = SO_REUSEADDR } }; +} // namespace + +std::span socketOptionTable() noexcept +{ + return Rows; +} + +namespace detail +{ + std::span reuseAddressOptions() noexcept + { + return ReuseAddress; + } + + std::expected getIntOption(platform::NativeHandle socket, NativeOption option) + { + auto value = 0; + auto length = static_cast(sizeof(value)); + if (::getsockopt(socket, option.level, option.name, &value, &length) != 0) + return std::unexpected(socketError(errno, "getsockopt")); + return value; + } + + std::expected setIntOption(platform::NativeHandle socket, NativeOption option, int value) + { + if (::setsockopt(socket, option.level, option.name, &value, sizeof(value)) != 0) + return std::unexpected(socketError(errno, "setsockopt")); + return {}; + } +} // namespace detail + +} // namespace core::net diff --git a/src/core/net/posix/SocketsPosix.cpp b/src/core/net/posix/SocketsPosix.cpp index 567a178f..1f9b62fd 100644 --- a/src/core/net/posix/SocketsPosix.cpp +++ b/src/core/net/posix/SocketsPosix.cpp @@ -1,6 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 #include #include +#include #include #include #include @@ -14,7 +15,10 @@ #include #include #include +#include +#include #include +#include #include #include #include @@ -260,6 +264,27 @@ namespace detail { return gaiCode == EAI_SYSTEM ? errno : 0; } + + std::expected socketEndpoint(platform::NativeHandle socket, SocketSide side) + { + /// The call each side is asked with, indexed by @c SocketSide. + struct EndpointCall + { + decltype(&::getsockname) call; ///< `getsockname` or `getpeername`. + char const* name; ///< Its name, for the error's context. + }; + static constexpr auto Calls = std::array { + EndpointCall { .call = &::getsockname, .name = "getsockname" }, + EndpointCall { .call = &::getpeername, .name = "getpeername" }, + }; + auto const& [call, name] = Calls.at(static_cast(side)); + + auto storage = sockaddr_storage {}; + auto length = static_cast(sizeof(storage)); + if (call(socket, reinterpret_cast(&storage), &length) != 0) + return std::unexpected(socketError(errno, name)); + return endpointFromSockaddr(&storage, static_cast(length)); + } } // namespace detail } // namespace core::net diff --git a/src/core/net/posix/StreamSocketOptions.cpp b/src/core/net/posix/StreamSocketOptions.cpp index d90a83b6..698dbdd8 100644 --- a/src/core/net/posix/StreamSocketOptions.cpp +++ b/src/core/net/posix/StreamSocketOptions.cpp @@ -1,7 +1,10 @@ // SPDX-License-Identifier: Apache-2.0 #include +#include +#include #include +#include #include @@ -9,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -23,15 +27,6 @@ namespace core::net::detail namespace { - /// macOS spells the idle time `TCP_KEEPALIVE`; it is `TCP_KEEPIDLE` everywhere else. -#ifdef __APPLE__ - constexpr int KeepAliveIdleOption = TCP_KEEPALIVE; - constexpr char const* KeepAliveIdleName = "setsockopt(TCP_KEEPALIVE)"; -#else - constexpr int KeepAliveIdleOption = TCP_KEEPIDLE; - constexpr char const* KeepAliveIdleName = "setsockopt(TCP_KEEPIDLE)"; -#endif - /// Whole seconds, and never zero. /// /// The keepalive options take seconds, and a zero is not "immediately" — it is rejected, or @@ -59,16 +54,17 @@ std::expected armKeepAlive(platform::NativeHandle socket, KeepAl // not be applied would be left probing on the system default -- two hours on Linux -- // which is indistinguishable from no keepalive at all for every deadline this protects, // while reading back as armed to anything that checks the flag. - auto const apply = - [socket](int level, int option, int value, char const* what) -> std::expected { - if (::setsockopt(socket, level, option, &value, sizeof(value)) != 0) - return std::unexpected(socketError(lastSocketError(), what)); - return {}; + // + // Through the option table's rows, which name the platform's spelling of each (macOS calls the + // idle time `TCP_KEEPALIVE`). They are TCP-level and the same for both families, so the IPv4 + // rows serve an IPv6 socket too. + auto const apply = [socket](SocketOption option, int value) { + return writeSocketOption(socket, AddressFamily::Ipv4, option, static_cast(value)); }; - return apply(IPPROTO_TCP, KeepAliveIdleOption, idle, KeepAliveIdleName) - .and_then([&] { return apply(IPPROTO_TCP, TCP_KEEPINTVL, interval, "setsockopt(TCP_KEEPINTVL)"); }) - .and_then([&] { return apply(IPPROTO_TCP, TCP_KEEPCNT, count, "setsockopt(TCP_KEEPCNT)"); }) - .and_then([&] { return apply(SOL_SOCKET, SO_KEEPALIVE, 1, "setsockopt(SO_KEEPALIVE)"); }); + return apply(SocketOption::KeepAliveIdleTime, idle) + .and_then([&] { return apply(SocketOption::KeepAliveInterval, interval); }) + .and_then([&] { return apply(SocketOption::KeepAliveCount, count); }) + .and_then([&] { return apply(SocketOption::KeepAliveEnabled, 1); }); } namespace @@ -97,6 +93,12 @@ namespace return 0; return value; } + + /// @return A keepalive option through its row, as @c armKeepAlive sets it; 0 if unreadable. + [[nodiscard]] int keepAliveRow(int fd, SocketOption option) noexcept + { + return static_cast(readSocketOption(fd, AddressFamily::Ipv4, option).value_or(0)); + } } // namespace void applyStreamSocketOptions(platform::NativeHandle socket, KeepAlive keepAlive) noexcept @@ -135,9 +137,9 @@ StreamSocketReport reportStreamSocketOptions(platform::NativeHandle socket) noex .sendBuffer = clampedSize(readOption(socket, SOL_SOCKET, SO_SNDBUF)), .receiveBuffer = clampedSize(readOption(socket, SOL_SOCKET, SO_RCVBUF)), .keepAlive = readOption(socket, SOL_SOCKET, SO_KEEPALIVE) != 0, - .keepAliveIdleSeconds = readOption(socket, IPPROTO_TCP, KeepAliveIdleOption), - .keepAliveIntervalSeconds = readOption(socket, IPPROTO_TCP, TCP_KEEPINTVL), - .keepAliveCount = readOption(socket, IPPROTO_TCP, TCP_KEEPCNT), + .keepAliveIdleSeconds = keepAliveRow(socket, SocketOption::KeepAliveIdleTime), + .keepAliveIntervalSeconds = keepAliveRow(socket, SocketOption::KeepAliveInterval), + .keepAliveCount = keepAliveRow(socket, SocketOption::KeepAliveCount), }; } diff --git a/src/core/net/testing/InMemorySocket.cpp b/src/core/net/testing/InMemorySocket.cpp index 08408bdd..7b8d19a4 100644 --- a/src/core/net/testing/InMemorySocket.cpp +++ b/src/core/net/testing/InMemorySocket.cpp @@ -134,10 +134,12 @@ namespace InMemorySocket::InMemorySocket(std::shared_ptr inbound, std::shared_ptr outbound, - std::string peerAddress) noexcept: + std::string peerAddress, + InMemoryEndpoints endpoints) noexcept: _inbound { std::move(inbound) }, _outbound { std::move(outbound) }, - _peerAddress { std::move(peerAddress) } + _peerAddress { std::move(peerAddress) }, + _endpoints { endpoints } { _inbound->onReadable(&InMemorySocket::onInboundProgress, this); _outbound->onWritable(&InMemorySocket::onOutboundProgress, this); @@ -215,6 +217,24 @@ std::expected InMemorySocket::armKeepAlive(KeepAliveSettings con return {}; } +std::expected InMemorySocket::localEndpoint() const +{ + if (_closed) + return std::unexpected(closedSocket("localEndpoint")); + if (!_endpoints.local.has_value()) + return ISocket::localEndpoint(); + return *_endpoints.local; +} + +std::expected InMemorySocket::remoteEndpoint() const +{ + if (_closed) + return std::unexpected(closedSocket("remoteEndpoint")); + if (!_endpoints.remote.has_value()) + return ISocket::remoteEndpoint(); + return *_endpoints.remote; +} + ResultAwaitable InMemorySocket::shutdownWrite() { // After `close` there is no write side left to shut, and each platform socket answers success @@ -496,14 +516,23 @@ void InMemorySocket::retireWrite(void* owner, void* awaitable) noexcept // -- InMemorySocketPair --------------------------------------------------------------------------- -InMemorySocketPair InMemorySocketPair::create(std::size_t maxBytesInFlight, std::string serverPeerAddress) +InMemorySocketPair InMemorySocketPair::create(std::size_t maxBytesInFlight, + std::string serverPeerAddress, + InMemoryPairEndpoints endpoints) { auto clientToServer = std::make_shared(maxBytesInFlight); auto serverToClient = std::make_shared(maxBytesInFlight); return InMemorySocketPair { - .client = std::make_unique(serverToClient, clientToServer), - .server = - std::make_unique(clientToServer, serverToClient, std::move(serverPeerAddress)), + .client = std::make_unique( + serverToClient, + clientToServer, + std::string {}, + InMemoryEndpoints { .local = endpoints.client, .remote = endpoints.server }), + .server = std::make_unique( + clientToServer, + serverToClient, + std::move(serverPeerAddress), + InMemoryEndpoints { .local = endpoints.server, .remote = endpoints.client }), }; } diff --git a/src/core/net/testing/InMemorySocket.hpp b/src/core/net/testing/InMemorySocket.hpp index b37b64f1..c2c97d73 100644 --- a/src/core/net/testing/InMemorySocket.hpp +++ b/src/core/net/testing/InMemorySocket.hpp @@ -31,6 +31,7 @@ #include #include #include +#include #include #include @@ -146,6 +147,24 @@ class CORE_NET_API InMemoryPipe void* _writableState { nullptr }; }; +/// The addresses an @c InMemorySocket reports as its own and its peer's. +/// +/// An in-process pipe has none of its own, so a test that needs a server to see a client's address +/// and port -- as one served over TCP would -- states them. An unset one answers +/// @c NetErrorCode::Unsupported, as the interface's default does. +struct InMemoryEndpoints +{ + std::optional local; ///< What @c InMemorySocket::localEndpoint answers. + std::optional remote; ///< What @c InMemorySocket::remoteEndpoint answers. +}; + +/// The addresses of the two ends of an @c InMemorySocketPair, each end's own. +struct InMemoryPairEndpoints +{ + std::optional client; ///< The dialling end's address: the server's remote one. + std::optional server; ///< The accepted end's address: the client's remote one. +}; + /// One end of an in-memory connection: reads drain one @c InMemoryPipe, writes fill the other. /// /// **In every closed state it answers the way a loopback TCP socket does**, which @@ -200,9 +219,11 @@ class CORE_NET_API InMemorySocket final: public ISocket /// @param outbound The pipe this end writes into — the peer's inbound. /// @param peerAddress What @c peerAddress reports; "" (the default) means none, as a real /// in-process transport has. + /// @param endpoints What @c localEndpoint and @c remoteEndpoint report; none by default. InMemorySocket(std::shared_ptr inbound, std::shared_ptr outbound, - std::string peerAddress = {}) noexcept; + std::string peerAddress = {}, + InMemoryEndpoints endpoints = {}) noexcept; /// Abandons any parked operation rather than completing it — see @c ISocket::close and the /// socket contract's *a destructor abandons, close resolves* — and closes both directions. @@ -254,6 +275,13 @@ class CORE_NET_API InMemorySocket final: public ISocket [[nodiscard]] std::string peerAddress() const override { return _peerAddress; } + /// @return The local endpoint this socket was created with; @c NetErrorCode::Unsupported if it + /// was given none, and @c NetErrorCode::BadHandle after @c close, as the platform sockets do. + [[nodiscard]] std::expected localEndpoint() const override; + + /// @return The remote endpoint this socket was created with; otherwise as @c localEndpoint. + [[nodiscard]] std::expected remoteEndpoint() const override; + void close() noexcept override; /// @return True once @c close was called or a read observed the peer's EOF — @see @@ -337,6 +365,7 @@ class CORE_NET_API InMemorySocket final: public ISocket std::shared_ptr _inbound; std::shared_ptr _outbound; std::string _peerAddress; + InMemoryEndpoints _endpoints; /// What a verb recorded for the arm that follows it: the kind and buffer are known at the verb /// and the awaitable's final address only at the arm. @@ -360,9 +389,12 @@ struct CORE_NET_API InMemorySocketPair /// @param maxBytesInFlight Per-direction bound on buffered bytes; zero means none. /// @param serverPeerAddress What the SERVER end reports as its peer — the client's apparent /// address. "" (the default) means none. + /// @param endpoints Each end's own address; each end's remote endpoint is the other's. None by + /// default. Independent of @p serverPeerAddress, which a test sets apart. /// @return Two connected ends. [[nodiscard]] static InMemorySocketPair create(std::size_t maxBytesInFlight = 0, - std::string serverPeerAddress = {}); + std::string serverPeerAddress = {}, + InMemoryPairEndpoints endpoints = {}); }; /// A listener whose connections a test makes with @c connectClient. diff --git a/src/core/net/testing/SocketDecorator.hpp b/src/core/net/testing/SocketDecorator.hpp index 924c505d..817ffe55 100644 --- a/src/core/net/testing/SocketDecorator.hpp +++ b/src/core/net/testing/SocketDecorator.hpp @@ -9,9 +9,13 @@ #include #include +#include +#include +#include #include #include +#include #include #include #include @@ -30,12 +34,14 @@ namespace core::net::testing /// /// **What hand-written copies get wrong is the part they did not write.** @c ISocket has virtuals /// with default implementations -- @c readWithFd, @c handshakeIfNeeded, @c waitReadable, -/// @c cancelRead, @c shutdownWrite, @c setReceiveDeadline, @c armKeepAlive, @c peerAddress -- and a decorator -/// that overrides none of them silently answers from the BASE rather than from the socket it decorates: a +/// @c cancelRead, @c shutdownWrite, @c setReceiveDeadline, @c armKeepAlive, @c peerAddress, +/// @c localEndpoint, @c remoteEndpoint, @c option, @c setOption -- and a decorator that overrides +/// none of them silently answers from the BASE rather than from the socket it decorates: a /// decorated peer has no address, a half-close reaches nothing, a deadline bounds nothing. None of that is -/// visible at a call site, because every one of those defaults succeeds. Forwarding them is a property of -/// this type, so a double cannot omit it -- and when @c ISocket grows a virtual, this is the one place that -/// must grow with it. +/// visible at a call site, because every one of those defaults succeeds, or answers @c +/// NetErrorCode::Unsupported as though the socket had nothing to give. Forwarding them is a property of this +/// type, so a double cannot omit it -- and when @c ISocket grows a virtual, this is the one place that must +/// grow with it. class SocketDecorator: public ISocket { public: @@ -86,6 +92,31 @@ class SocketDecorator: public ISocket [[nodiscard]] std::string peerAddress() const override { return _inner.peerAddress(); } + /// Forwarded, so a decorated socket keeps its address; the base default answers + /// @c NetErrorCode::Unsupported. + [[nodiscard]] std::expected localEndpoint() const override + { + return _inner.localEndpoint(); + } + + /// Forwarded, as @c localEndpoint is. + [[nodiscard]] std::expected remoteEndpoint() const override + { + return _inner.remoteEndpoint(); + } + + /// Forwarded, as @c localEndpoint is. + [[nodiscard]] std::expected option(SocketOption option) const override + { + return _inner.option(option); + } + + /// Forwarded, as @c localEndpoint is. + [[nodiscard]] std::expected setOption(SocketOption option, std::uint64_t value) override + { + return _inner.setOption(option, value); + } + void close() noexcept override { _inner.close(); } [[nodiscard]] bool isClosed() const noexcept override { return _inner.isClosed(); } diff --git a/src/core/net/windows/DialPrimitives.cpp b/src/core/net/windows/DialPrimitives.cpp index c10ac00b..f1f658b9 100644 --- a/src/core/net/windows/DialPrimitives.cpp +++ b/src/core/net/windows/DialPrimitives.cpp @@ -82,9 +82,13 @@ void closeDialSocket(EventLoop* loop, DialHandles& handles) noexcept { if (!handles.valid()) return; - if (loop != nullptr) - loop->notifyHandleClosing(handles.readiness, FdWakePolicy::Cancel); - ::WSACloseEvent(static_cast(handles.readiness)); + // A completion-port socket (an `ITcpSocket`'s, a `ConnectEx` dial's) has no readiness event. + if (handles.readiness != platform::InvalidHandle) + { + if (loop != nullptr) + loop->notifyHandleClosing(handles.readiness, FdWakePolicy::Cancel); + ::WSACloseEvent(static_cast(handles.readiness)); + } ::closesocket(reinterpret_cast(handles.socket)); handles = DialHandles {}; } diff --git a/src/core/net/windows/IocpDial.cpp b/src/core/net/windows/IocpDial.cpp index 512d94e7..20b99e52 100644 --- a/src/core/net/windows/IocpDial.cpp +++ b/src/core/net/windows/IocpDial.cpp @@ -107,20 +107,41 @@ async::Task dialCompletion(EventLoop* loop, StreamSocketOptions options) { platform::ensureWinsockInitialized(); - auto* const port = loop->completionPort(); - if (port == nullptr) + if (loop->completionPort() == nullptr) co_return std::unexpected( makeNetError(NetErrorCode::Unsupported, 0, "the loop's backend lends no completion port")); - auto socket = ::WSASocketW(endpoint.family, - SOCK_STREAM, - endpoint.protocol, - nullptr, - 0, - WSA_FLAG_OVERLAPPED | WSA_FLAG_NO_HANDLE_INHERIT); + auto const socket = ::WSASocketW(endpoint.family, + SOCK_STREAM, + endpoint.protocol, + nullptr, + 0, + WSA_FLAG_OVERLAPPED | WSA_FLAG_NO_HANDLE_INHERIT); if (socket == detail::InvalidSocket) co_return std::unexpected(fromWinsockError(::WSAGetLastError(), "socket")); + // A statement of its own, for the reason `dialReadiness` gives (C4737). + auto dial = dialCompletionOn( + loop, + DialSocket { loop, DialHandles { .socket = reinterpret_cast(socket) } }, + LocalBinding::Unbound, + endpoint, + deadline, + options); + co_return co_await std::move(dial); +} + +async::Task dialCompletionOn(EventLoop* loop, + DialSocket owned, + LocalBinding binding, + ResolvedEndpoint endpoint, + platform::SteadyTimePoint deadline, + StreamSocketOptions options) +{ + platform::ensureWinsockInitialized(); + auto socket = reinterpret_cast(owned.release().socket); + auto* const port = loop->completionPort(); + // Closes whatever is LEFT when this frame goes -- an `OperationCancelled` thrown out of the wait // included. Closing is also what aborts a `ConnectEx` nothing will wait for; its completion // lands in the operation's own share. The success path empties `socket` instead of disarming. @@ -132,11 +153,15 @@ async::Task dialCompletion(EventLoop* loop, port->forget(reinterpret_cast(socket)); ::closesocket(socket); } }; + if (port == nullptr) + co_return std::unexpected( + makeNetError(NetErrorCode::Unsupported, 0, "the loop's backend lends no completion port")); // Before the connect, while the window scale can still take the receive buffer into account. applySocketBufferSizes(reinterpret_cast(socket), options.buffers); - if (auto bound = bindWildcard(socket, endpoint.family); !bound) - co_return std::unexpected(std::move(bound.error())); + if (binding == LocalBinding::Unbound) + if (auto bound = bindWildcard(socket, endpoint.family); !bound) + co_return std::unexpected(std::move(bound.error())); auto* const connectEx = connectExFor(socket); if (connectEx == nullptr) co_return std::unexpected(fromWinsockError(::WSAGetLastError(), "WSAIoctl(ConnectEx)")); diff --git a/src/core/net/windows/IocpSocket.cpp b/src/core/net/windows/IocpSocket.cpp index 8e9e514b..3becb016 100644 --- a/src/core/net/windows/IocpSocket.cpp +++ b/src/core/net/windows/IocpSocket.cpp @@ -15,6 +15,8 @@ #include #include #include +#include +#include #include #include #include @@ -685,6 +687,36 @@ std::expected IocpSocket::armKeepAlive(KeepAliveSettings const& return detail::armKeepAlive(reinterpret_cast(_socket), settings); } +std::expected IocpSocket::localEndpoint() const +{ + if (_closed || _socket == detail::InvalidSocket) + return std::unexpected(closedSocket("localEndpoint")); + return detail::socketEndpoint(reinterpret_cast(_socket), + detail::SocketSide::Local); +} + +std::expected IocpSocket::remoteEndpoint() const +{ + if (_closed || _socket == detail::InvalidSocket) + return std::unexpected(closedSocket("remoteEndpoint")); + return detail::socketEndpoint(reinterpret_cast(_socket), + detail::SocketSide::Remote); +} + +std::expected IocpSocket::option(SocketOption option) const +{ + if (_closed || _socket == detail::InvalidSocket) + return std::unexpected(closedSocket("option")); + return detail::readSocketOption(reinterpret_cast(_socket), option); +} + +std::expected IocpSocket::setOption(SocketOption option, std::uint64_t value) +{ + if (_closed || _socket == detail::InvalidSocket) + return std::unexpected(closedSocket("setOption")); + return detail::writeSocketOption(reinterpret_cast(_socket), option, value); +} + ResultAwaitable IocpSocket::shutdownWrite() { // The precondition -- no write outstanding -- is the caller's, and is not asserted here, as it @@ -1114,6 +1146,30 @@ SOCKET IocpListener::native() const noexcept return _shared->socket; } +std::expected IocpListener::localEndpoint() const +{ + if (_closed || _shared->socket == detail::InvalidSocket) + return std::unexpected( + makeNetError(NetErrorCode::BadHandle, 0, "localEndpoint on a closed listener")); + return detail::socketEndpoint(reinterpret_cast(_shared->socket), + detail::SocketSide::Local); +} + +std::expected IocpListener::option(SocketOption option) const +{ + if (_closed || _shared->socket == detail::InvalidSocket) + return std::unexpected(makeNetError(NetErrorCode::BadHandle, 0, "option on a closed listener")); + return detail::readSocketOption(reinterpret_cast(_shared->socket), option); +} + +std::expected IocpListener::setOption(SocketOption option, std::uint64_t value) +{ + if (_closed || _shared->socket == detail::InvalidSocket) + return std::unexpected(makeNetError(NetErrorCode::BadHandle, 0, "setOption on a closed listener")); + return detail::writeSocketOption( + reinterpret_cast(_shared->socket), option, value); +} + platform::NativeHandle IocpListener::nativeHandle() const noexcept { // `INVALID_SOCKET` once closed, which is `platform::InvalidHandle` spelled as a SOCKET. diff --git a/src/core/net/windows/IocpSocket.hpp b/src/core/net/windows/IocpSocket.hpp index 27d882c6..13077bb5 100644 --- a/src/core/net/windows/IocpSocket.hpp +++ b/src/core/net/windows/IocpSocket.hpp @@ -150,6 +150,10 @@ class CORE_NET_API IocpSocket final: public ISocket [[nodiscard]] std::expected armKeepAlive(KeepAliveSettings const& settings) override; [[nodiscard]] std::string peerAddress() const override { return _peerAddress; } + [[nodiscard]] std::expected localEndpoint() const override; + [[nodiscard]] std::expected remoteEndpoint() const override; + [[nodiscard]] std::expected option(SocketOption option) const override; + [[nodiscard]] std::expected setOption(SocketOption option, std::uint64_t value) override; void close() noexcept override; @@ -356,6 +360,15 @@ class CORE_NET_API IocpListener final: public IListener [[nodiscard]] std::uint16_t boundPort() const noexcept override { return _boundPort; } + /// @copydoc IListener::localEndpoint + [[nodiscard]] std::expected localEndpoint() const override; + + /// @copydoc IListener::option + [[nodiscard]] std::expected option(SocketOption option) const override; + + /// @copydoc IListener::setOption + [[nodiscard]] std::expected setOption(SocketOption option, std::uint64_t value) override; + /// @return The listening socket, or `INVALID_SOCKET` once closed; for diagnostics and tests. [[nodiscard]] SOCKET native() const noexcept; diff --git a/src/core/net/windows/IocpTcpSocket.cpp b/src/core/net/windows/IocpTcpSocket.cpp new file mode 100644 index 00000000..76c122b8 --- /dev/null +++ b/src/core/net/windows/IocpTcpSocket.cpp @@ -0,0 +1,70 @@ +// SPDX-License-Identifier: Apache-2.0 + +/// @file +/// The Windows halves of an `ITcpSocket`: an overlapped, non-inheritable socket, which is what +/// `ConnectEx` and `AcceptEx` take, and plain `bind` and `listen`. What it becomes is +/// `dialCompletionOn`'s `IocpSocket` or `adoptListener`'s `IocpListener`; the completion-port +/// association is theirs to make, so a socket that is only bound holds none. + +// winsock2.h MUST precede windows.h / ws2tcpip.h (which project headers pull in), so this block +// leads every Win32 net translation unit. +// clang-format off +#include +#include +#include +// clang-format on + +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace core::net::detail +{ + +std::expected openTcpHandles(AddressFamily family) +{ + platform::ensureWinsockInitialized(); + auto const socket = ::WSASocketW(family == AddressFamily::Ipv6 ? AF_INET6 : AF_INET, + SOCK_STREAM, + IPPROTO_TCP, + nullptr, + 0, + WSA_FLAG_OVERLAPPED | WSA_FLAG_NO_HANDLE_INHERIT); + if (socket == InvalidSocket) + return std::unexpected(fromWinsockError(::WSAGetLastError(), "socket")); + auto const handle = reinterpret_cast(socket); + + // Windows' own default, stated rather than inherited: the one platform rule is IPv6-only. + if (family == AddressFamily::Ipv6) + if (auto only = setIntOption(handle, NativeOption { .level = IPPROTO_IPV6, .name = IPV6_V6ONLY }, 1); + !only.has_value()) + { + ::closesocket(socket); + return std::unexpected(std::move(only.error())); + } + + return DialHandles { .socket = handle }; +} + +std::expected bindTcpHandle(platform::NativeHandle socket, ResolvedEndpoint const& local) +{ + auto const* const address = reinterpret_cast(local.storage.data()); + if (::bind(reinterpret_cast(socket), address, static_cast(local.length)) != 0) + return std::unexpected(fromWinsockError(::WSAGetLastError(), "bind")); + return {}; +} + +std::expected listenTcpHandle(platform::NativeHandle socket, int backlog) +{ + if (::listen(reinterpret_cast(socket), backlog) != 0) + return std::unexpected(fromWinsockError(::WSAGetLastError(), "listen")); + return {}; +} + +} // namespace core::net::detail diff --git a/src/core/net/windows/SocketOptionTable.cpp b/src/core/net/windows/SocketOptionTable.cpp new file mode 100644 index 00000000..85754f8c --- /dev/null +++ b/src/core/net/windows/SocketOptionTable.cpp @@ -0,0 +1,109 @@ +// SPDX-License-Identifier: Apache-2.0 + +/// @file +/// The Windows socket-option rows, and the two `int`-option calls beneath them. +/// +/// The keepalive intervals and count are the per-option `TCP_KEEPIDLE`, `TCP_KEEPINTVL` and +/// `TCP_KEEPCNT` (Windows 10 1709 and later), not `SIO_KEEPALIVE_VALS`: that ioctl sets the flag and +/// both intervals together, and nothing reads them back. `armKeepAlive` keeps the ioctl, which is +/// its one-call contract. + +// winsock2.h MUST precede windows.h / ws2tcpip.h (which project headers pull in), so this block +// leads every Win32 net translation unit. +// clang-format off +#include +#include +#include +// clang-format on + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace core::net +{ + +namespace +{ + /// Windows takes any `int` buffer size. + constexpr std::uint64_t BufferMaximum = INT_MAX; + + /// Windows takes larger keepalive times and counts up to 255; these are Linux's limits, which + /// a Windows build run under wine meets through the Linux kernel, and which no caller of a + /// WASI socket can tell from a clamp. + constexpr std::uint64_t KeepAliveTimeMaximum = 32'767; + constexpr std::uint64_t KeepAliveCountMaximum = 127; + + /// A hop limit is one octet on the wire. + constexpr std::uint64_t HopLimitMaximum = 255; + + /// One row per option and family; the families differ only in the hop limit. Windows reports + /// buffer sizes as they were set. + constexpr auto Rows = std::array { + // clang-format off + SocketOptionRow { SocketOption::ReceiveBufferSize, AddressFamily::Ipv4, SOL_SOCKET, SO_RCVBUF, OptionScale::Identity, BufferMaximum }, + SocketOptionRow { SocketOption::SendBufferSize, AddressFamily::Ipv4, SOL_SOCKET, SO_SNDBUF, OptionScale::Identity, BufferMaximum }, + SocketOptionRow { SocketOption::UnicastHopLimit, AddressFamily::Ipv4, IPPROTO_IP, IP_TTL, OptionScale::Identity, HopLimitMaximum }, + SocketOptionRow { SocketOption::KeepAliveEnabled, AddressFamily::Ipv4, SOL_SOCKET, SO_KEEPALIVE, OptionScale::Flag, 1 }, + SocketOptionRow { SocketOption::KeepAliveIdleTime, AddressFamily::Ipv4, IPPROTO_TCP, TCP_KEEPIDLE, OptionScale::Seconds, KeepAliveTimeMaximum }, + SocketOptionRow { SocketOption::KeepAliveInterval, AddressFamily::Ipv4, IPPROTO_TCP, TCP_KEEPINTVL, OptionScale::Seconds, KeepAliveTimeMaximum }, + SocketOptionRow { SocketOption::KeepAliveCount, AddressFamily::Ipv4, IPPROTO_TCP, TCP_KEEPCNT, OptionScale::Identity, KeepAliveCountMaximum }, + SocketOptionRow { SocketOption::ReceiveBufferSize, AddressFamily::Ipv6, SOL_SOCKET, SO_RCVBUF, OptionScale::Identity, BufferMaximum }, + SocketOptionRow { SocketOption::SendBufferSize, AddressFamily::Ipv6, SOL_SOCKET, SO_SNDBUF, OptionScale::Identity, BufferMaximum }, + SocketOptionRow { SocketOption::UnicastHopLimit, AddressFamily::Ipv6, IPPROTO_IPV6, IPV6_UNICAST_HOPS, OptionScale::Identity, HopLimitMaximum }, + SocketOptionRow { SocketOption::KeepAliveEnabled, AddressFamily::Ipv6, SOL_SOCKET, SO_KEEPALIVE, OptionScale::Flag, 1 }, + SocketOptionRow { SocketOption::KeepAliveIdleTime, AddressFamily::Ipv6, IPPROTO_TCP, TCP_KEEPIDLE, OptionScale::Seconds, KeepAliveTimeMaximum }, + SocketOptionRow { SocketOption::KeepAliveInterval, AddressFamily::Ipv6, IPPROTO_TCP, TCP_KEEPINTVL, OptionScale::Seconds, KeepAliveTimeMaximum }, + SocketOptionRow { SocketOption::KeepAliveCount, AddressFamily::Ipv6, IPPROTO_TCP, TCP_KEEPCNT, OptionScale::Identity, KeepAliveCountMaximum }, + // clang-format on + }; +} // namespace + +std::span socketOptionTable() noexcept +{ + return Rows; +} + +namespace detail +{ + std::span reuseAddressOptions() noexcept + { + // None, by P13 ruling R17: Windows binds a port in TIME_WAIT by default, and its + // SO_REUSEADDR would let this socket take over a port another socket listens on. + return {}; + } + + std::expected getIntOption(platform::NativeHandle socket, NativeOption option) + { + auto value = 0; + auto length = static_cast(sizeof(value)); + if (::getsockopt(reinterpret_cast(socket), + option.level, + option.name, + reinterpret_cast(&value), + &length) + != 0) + return std::unexpected(socketError(lastSocketError(), "getsockopt")); + return value; + } + + std::expected setIntOption(platform::NativeHandle socket, NativeOption option, int value) + { + if (::setsockopt(reinterpret_cast(socket), + option.level, + option.name, + reinterpret_cast(&value), + static_cast(sizeof(value))) + != 0) + return std::unexpected(socketError(lastSocketError(), "setsockopt")); + return {}; + } +} // namespace detail + +} // namespace core::net diff --git a/src/core/net/windows/SocketsWin32.cpp b/src/core/net/windows/SocketsWin32.cpp index bb4d3241..880e4d1f 100644 --- a/src/core/net/windows/SocketsWin32.cpp +++ b/src/core/net/windows/SocketsWin32.cpp @@ -11,14 +11,19 @@ #include #include #include +#include #include #include #include +#include #include #include #include +#include +#include #include +#include #include #include #include @@ -222,6 +227,29 @@ namespace detail // Winsock's resolver codes are WSAGetLastError values. return gaiCode; } + + std::expected socketEndpoint(platform::NativeHandle socket, SocketSide side) + { + /// The call each side is asked with, indexed by @c SocketSide. + struct EndpointCall + { + decltype(&::getsockname) call; ///< `getsockname` or `getpeername`. + char const* name; ///< Its name, for the error's context. + }; + // Not constexpr: Winsock's functions are imported from ws2_32.dll, and an imported + // function's address is not a constant expression. + static auto const calls = std::array { + EndpointCall { .call = &::getsockname, .name = "getsockname" }, + EndpointCall { .call = &::getpeername, .name = "getpeername" }, + }; + auto const& [call, name] = calls.at(static_cast(side)); + + auto storage = sockaddr_storage {}; + auto length = static_cast(sizeof(storage)); + if (call(reinterpret_cast(socket), reinterpret_cast(&storage), &length) != 0) + return std::unexpected(fromWinsockError(::WSAGetLastError(), name)); + return endpointFromSockaddr(&storage, static_cast(length)); + } } // namespace detail } // namespace core::net From f6e3640afaa27cc2917ba0e7d2f2f6eb1cc2452b Mon Sep 17 00:00:00 2001 From: Christian Parpart Date: Thu, 26 Nov 2026 22:35:13 +0100 Subject: [PATCH 07/19] feat(net): an EventLoop-driven datagram socket An EventLoop-driven datagram socket. IAsyncDatagramSocket is a UDP socket whose sends and receives are coroutines on one EventLoop: bind, connect to a remote or disconnect, receive(maxBytes), send(payload, to), both endpoints, and the buffer and hop-limit options. openAsyncDatagramSocket opens one: on POSIX a non-blocking socket that waits on readiness and then calls recvmsg or sendto, and on Windows an overlapped one on the completion port (WSARecvFrom/WSASendTo through CompletionWait, SIO_UDP_CONNRESET off). The state machine is written once (AsyncDatagramSocket.cpp) over a detail::IDatagramChannel. testing::InMemoryAsyncDatagramNetwork plugs an in-memory channel into the same machine, so the double gives every refusal the real socket gives. A call its state does not allow answers BadHandle with systemCode 0, and an endpoint of the other family answers AddressError. A datagram longer than maxBytes is MessageTooLarge and is dropped; maxBytes is clamped to MaxIpv6DatagramPayload. A stop throws, close resolves with Cancelled, and a datagram that already arrived is delivered. The socket hides three kernel differences: - Linux unbinds a port-0 socket when it disconnects, so the socket binds that endpoint again. - macOS refuses an address on a connected sendto, so a send that names the remote goes out with no address. - Windows fails the next receive after an ICMP port-unreachable unless SIO_UDP_CONNRESET is off. blockOnWithin moves from TcpSocket_test into testing/CoroTestSupport.hpp so both suites can bound their kernel waits with it. Share the one-operation-in-flight claim. The datagram socket's Claim and holding() move to detail/OperationClaim.hpp, templated on the owner's record, so the standard streams can refuse a second read or write the same way. No behaviour change. Also in this commit: - datagram disconnect keeps the bound address, and one receive and one send in flight - the datagram socket's would-block test builds under GCC - close a datagram socket a disconnect widened to the wildcard - waitUntil is bounded by the loop's clock, not by a count of polls Signed-off-by: Christian Parpart --- .agent/reference/provenance.md | 10 + .agent/rules/async-and-net.md | 16 + docs/modules/net.md | 3 + src/core/net/AsyncDatagramLoopback_test.cpp | 441 +++++++++++++++ src/core/net/AsyncDatagramSocket.cpp | 355 ++++++++++++ src/core/net/AsyncDatagram_test.cpp | 527 ++++++++++++++++++ src/core/net/CMakeLists.txt | 10 + src/core/net/IAsyncDatagramSocket.hpp | 150 +++++ src/core/net/TcpSocket_test.cpp | 9 +- src/core/net/detail/DatagramChannel.hpp | 114 ++++ src/core/net/detail/OperationClaim.hpp | 69 +++ .../net/posix/ReadinessDatagramSocket.cpp | 232 ++++++++ src/core/net/testing/CoroTestSupport.hpp | 30 +- .../net/testing/InMemoryAsyncDatagram.cpp | 297 ++++++++++ .../net/testing/InMemoryAsyncDatagram.hpp | 75 +++ src/core/net/windows/IocpDatagramSocket.cpp | 379 +++++++++++++ src/core/net/windows/IocpOperation.hpp | 6 + 17 files changed, 2711 insertions(+), 12 deletions(-) create mode 100644 src/core/net/AsyncDatagramLoopback_test.cpp create mode 100644 src/core/net/AsyncDatagramSocket.cpp create mode 100644 src/core/net/AsyncDatagram_test.cpp create mode 100644 src/core/net/IAsyncDatagramSocket.hpp create mode 100644 src/core/net/detail/DatagramChannel.hpp create mode 100644 src/core/net/detail/OperationClaim.hpp create mode 100644 src/core/net/posix/ReadinessDatagramSocket.cpp create mode 100644 src/core/net/testing/InMemoryAsyncDatagram.cpp create mode 100644 src/core/net/testing/InMemoryAsyncDatagram.hpp create mode 100644 src/core/net/windows/IocpDatagramSocket.cpp diff --git a/.agent/reference/provenance.md b/.agent/reference/provenance.md index afbd4eac..b71c07e0 100644 --- a/.agent/reference/provenance.md +++ b/.agent/reference/provenance.md @@ -288,6 +288,16 @@ others in notes. | `src/core/net/posix/SocketOptionTable.cpp` | origin: core-cpp | - | - | P13 Task 9. Chooses constants within the platform family by `#if` in the data (Ruling R42, P13 ruling R11): `__linux__` for the doubled buffer sizes, `TCP_KEEPIDLE` against macOS's `TCP_KEEPALIVE`; fix round 1: per-row maxima, the buffer maximum chosen per kernel (`__linux__`, `__APPLE__`) | | `src/core/net/windows/IocpTcpSocket.cpp` | origin: core-cpp | - | - | P13 Task 9 | | `src/core/net/windows/SocketOptionTable.cpp` | origin: core-cpp | - | - | P13 Task 9; the reuse-address rows are empty by P13 ruling R17; fix round 1: per-row maxima | +| `src/core/net/IAsyncDatagramSocket.hpp` | origin: core-cpp | - | - | P13 Task 10: a UDP socket driven by the `EventLoop`, and `openAsyncDatagramSocket` | +| `src/core/net/AsyncDatagramSocket.cpp` | origin: core-cpp | - | - | P13 Task 10: the `IAsyncDatagramSocket` state machine, written once over a `detail::IDatagramChannel` | +| `src/core/net/AsyncDatagram_test.cpp` | origin: core-cpp | - | - | P13 Task 10 | +| `src/core/net/AsyncDatagramLoopback_test.cpp` | origin: core-cpp | - | - | P13 Task 10 | +| `src/core/net/detail/DatagramChannel.hpp` | origin: core-cpp | - | - | P13 Task 10: the platform half of a datagram socket, defined per platform and in memory | +| `src/core/net/posix/ReadinessDatagramSocket.cpp` | origin: core-cpp | - | - | P13 Task 10 | +| `src/core/net/windows/IocpDatagramSocket.cpp` | origin: core-cpp | - | - | P13 Task 10: `WSARecvFrom`/`WSASendTo` through `detail::CompletionWait`, `SIO_UDP_CONNRESET` off | +| `src/core/net/testing/InMemoryAsyncDatagram.hpp` | origin: core-cpp | - | - | P13 Task 10: an in-memory network behind the real socket's state machine | +| `src/core/net/testing/InMemoryAsyncDatagram.cpp` | origin: core-cpp | - | - | P13 Task 10 | +| `src/core/net/detail/OperationClaim.hpp` | origin: core-cpp | - | - | P13 Task 11: the one-operation-in-flight claim, moved out of `AsyncDatagramSocket.cpp` (Task 10) to be shared with the standard streams | | `src/core/net/linux/AcceptedSocketOptions_test.cpp` | origin: core-cpp | - | - | P13 Task 9 fix round 1: what a Linux listener's accepted connections inherit | | `src/core/net/HostDrivenBackend.cpp` | origin: core-cpp | - | - | its body: the coalescing (several wakes before the host gets a turn are one pump), the clamp of a deadline already past to a zero delay, and the schedule cleared BEFORE a pump runs so the turn it drives can arm the next one | | `src/core/net/HostDrivenBackend.hpp` | origin: core-cpp | - | - | Task B3: the IoBackend for a loop that is PUMPED rather than one that blocks. Portable, and tested on every platform over testing::ManualHostScheduler -- the browser is one of its hosts, not its definition | diff --git a/.agent/rules/async-and-net.md b/.agent/rules/async-and-net.md index 39ef50fb..464752b9 100644 --- a/.agent/rules/async-and-net.md +++ b/.agent/rules/async-and-net.md @@ -1351,6 +1351,22 @@ in-process doubles (`testing::DatagramBus`, `testing::InMemorySocket`, the parki fit is dropped and answered `DatagramWait::MessageTooLarge` -- `MSG_TRUNC` through `recvmsg`, `WSAEMSGSIZE` -- never handed back cut short and never read as a timeout. A datagram send that places fewer bytes than it was given is `MessageTooLarge`, never a partial write to retry: the rest resent is a second message. +- **The loop-driven datagram socket has one state machine, and its double runs it** (P13 Task 10). + `IAsyncDatagramSocket` is `AsyncDatagramSocket.cpp` over a `detail::IDatagramChannel`; the + platform channels (`posix/ReadinessDatagramSocket.cpp`, `windows/IocpDatagramSocket.cpp`) and + `testing::InMemoryAsyncDatagramNetwork`'s channel only do what the socket decided. So a refusal + -- closed, unbound, unconnected, the other family -- cannot be answered more permissively by the + double: a new state rule goes in the socket, never in a channel. A send or receive holds its own + share of the channel, so a socket destroyed while one is parked leaves the frame something to read. +- **Three kernel differences the datagram socket hides, each where it is written down.** Linux + unbinds a socket whose port the kernel chose when it disconnects (`__udp_disconnect`), so the + socket binds that endpoint again; macOS refuses an address on a connected socket's `sendto` with + `EISCONN`, so a send naming the remote is sent unaddressed; and Windows fails an unconnected + socket's next receive with `WSAECONNRESET` after an ICMP port-unreachable, so + `SIO_UDP_CONNRESET` is turned off at open. An immediate `WSAEMSGSIZE` from an overlapped + `WSARecvFrom` is answered `MessageTooLarge` at once, never waited for, and the operation is left + announced and holding itself, so a packet that may or may not follow frees it. The rebind after a + Linux disconnect takes the address `bind` was given, not `getsockname`'s connected source. - **Sharing a port buys hearing a broadcast, and nothing else.** A unicast to a shared port reaches one socket, and which one differs by platform, so a node that shares a port to hear the segment sends -- and is answered -- from an address only it holds (`answerFromOwnAddress`, diff --git a/docs/modules/net.md b/docs/modules/net.md index 284d00d9..19ccf0ca 100644 --- a/docs/modules/net.md +++ b/docs/modules/net.md @@ -55,12 +55,15 @@ directory `src/core/net/`. Three targets: | `` | `AcceptLoopHealth`: the accept loops of a process that gave up while they were meant to be serving, for a liveness probe | | `` | `closeLingering()`: half-close, drain the peer within `LingerBounds` (time, bytes, reads), then close, so a reply written over a request left unread is not destroyed by the reset a bare close sends | | ``, `` | `IDatagramSocket` (`send`, a bounded `receive`, `close`, `boundAddress`), `DatagramAddress`, `ReceivedDatagram`, `DatagramWait`; `openUdpSocket()` with `BroadcastMode` and `PortSharing`, answering WHY a bind failed. Blocking, on a thread of its own: a datagram socket is not an `ISocket` | +| `` | `IAsyncDatagramSocket` (`bind`, `connect` with a remote or `std::nullopt`, coroutine `receive(maxBytes)` and `send(payload, to)`, `localEndpoint`, `remoteEndpoint`, `option`/`setOption` for the buffer sizes and the hop limit, `close`), `AsyncDatagram`; `openAsyncDatagramSocket(loop, family)`. A UDP socket on an `EventLoop`: readiness on POSIX, the completion port on Windows. A datagram longer than `maxBytes` is `MessageTooLarge` and dropped, never cut short; a state that forbids a call answers `BadHandle` with systemCode 0 | +| ``, `` | `ITcpSocket` (`bind`, then `connect` or `listen`; `localEndpoint`, `option`/`setOption`) and `openTcpSocket(loop, family)`; `SocketOption`, `OptionScale`, `SocketOptionRow` and `socketOptionTable()`, the per-platform option rows every socket reads and writes through | | `` | `answerFromOwnAddress()` and `openSharedPortUdpSocket()`: hear the segment on a shared port, send and be answered from an address only this node holds | | ``, `` | the transports for threads that may block: `BlockingSocket`, whose every awaitable is already settled, and `BlockingConnector`, an `IConnector` that dials on the calling thread within its budget and arms `BlockingConnectorOptions::ioTimeout` before handing the socket over. Driven by `core::async::syncRun`; never on a loop thread | | `` | the one TCP client: `connectTcp()`, `sendAll()`, `receiveExactly()` | | `` | `probeHttpStatus()`, which returns the status an HTTP endpoint answered, and `httpHealthProbe()`, which is whether it was 200 | | `` | the deterministic fake: `InMemoryPipe`, `InMemorySocket`, `InMemorySocketPair`, `InMemoryListener` -- no descriptor, no loop, completed inline, and pinned to a real socket in every closed state by `SocketClosedStates_test.cpp`. Not `testing/InMemoryTransport.hpp`, whose `makeSocketPair()` is a pair of REAL sockets | | ``, `` | `DatagramBus`, a network segment in one process with scripted loss, and the text-to-payload helpers | +| `` | `InMemoryAsyncDatagramNetwork`: `IAsyncDatagramSocket`s that exchange datagrams in memory, behind the real socket's state machine, so every refusal is the real one's. Options are `Unsupported`; loss is a full inbox, a datagram to nobody, or one a connected receiver does not accept | | `` | `FailingListener`, an `IListener` decorator whose first accepts answer scripted `NetError`s and then accept from the listener it decorates, owned or not; `repeatedFailures()` | | ``, `` | `SocketDecorator`, which forwards every verb so a double overrides only the one it stages; `ParkingReadableSocket` and `ParkingWritableSocket`, which park until the test decides and count how each parked operation ended | | `` | `setDiagnosticSink()`: where a failure nobody can be handed goes (a wait that fails mid-sweep); discarded by default | diff --git a/src/core/net/AsyncDatagramLoopback_test.cpp b/src/core/net/AsyncDatagramLoopback_test.cpp new file mode 100644 index 00000000..f0640f7e --- /dev/null +++ b/src/core/net/AsyncDatagramLoopback_test.cpp @@ -0,0 +1,441 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// `openAsyncDatagramSocket` over the platform's real stack and its default backend: readiness on +// POSIX, the completion port on Windows. +// +// **Only what the kernel answers is asserted here**: that a datagram crosses loopback whole and +// says who sent it, that a connected socket hears its remote alone, that an unbound sender is +// given a port, that a datagram longer than the receive is dropped rather than cut, and that a +// dead peer's ICMP answer does not fail the next receive. The state machine's refusals are the +// in-memory suite's (`AsyncDatagram_test.cpp`), which runs the same implementation. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using core::async::Task; +using core::net::AddressFamily; +using core::net::AsyncDatagram; +using core::net::EventLoop; +using core::net::IAsyncDatagramSocket; +using core::net::IpSocketAddress; +using core::net::Ipv4Address; +using core::net::Ipv6Address; +using core::net::NetError; +using core::net::NetErrorCode; +using core::net::ResolvedEndpoint; +using core::net::SocketOption; + +namespace +{ + +/// @return The loopback address of @p family, at @p port. +[[nodiscard]] ResolvedEndpoint loopback(AddressFamily family, std::uint16_t port) +{ + if (family == AddressFamily::Ipv6) + return core::net::toEndpoint( + IpSocketAddress { .address = Ipv6Address { { 0, 0, 0, 0, 0, 0, 0, 1 } }, .port = port }); + return core::net::toEndpoint( + IpSocketAddress { .address = Ipv4Address { { 127, 0, 0, 1 } }, .port = port }); +} + +/// @return The IP form of @p endpoint, which the case requires to exist. +[[nodiscard]] IpSocketAddress ipOf(std::expected const& endpoint) +{ + REQUIRE(endpoint.has_value()); + auto address = core::net::toIpSocketAddress(*endpoint); + REQUIRE(address.has_value()); + return *address; +} + +/// @return Whether @p result failed with @p code. +template +[[nodiscard]] bool failedWith(std::expected const& result, NetErrorCode code) +{ + return !result.has_value() && result.error().code == code; +} + +/// @return @p count bytes, each its own index, offset by @p seed so two senders differ. +[[nodiscard]] std::vector bytes(std::size_t count, unsigned seed = 0) +{ + auto out = std::vector(count); + for (auto index = std::size_t { seed }; auto& value: out) + value = static_cast(index++ & 0xFFU); + return out; +} + +/// A loop over the platform's default backend, kept alive with it. +struct Loop +{ + std::unique_ptr backend = core::net::makeDefaultBackend(); + EventLoop loop { *backend }; +}; + +/// Runs @p task on @p loop, failing the case -- naming it -- if it has not finished within +/// @p limit, so a datagram that never arrives fails one case rather than hanging the binary. +void blockOnWithin(EventLoop& loop, + Task task, + std::chrono::milliseconds limit = std::chrono::seconds { 5 }) +{ + if (!core::net::testing::blockOnWithin(loop, std::move(task), limit)) + FAIL("a datagram wait in \"" << Catch::getResultCapture().getCurrentTestName() + << "\" took longer than " << limit.count() << " ms"); +} + +/// @return An open, unbound socket of @p family, or a SKIP where the host has no such family. +[[nodiscard]] std::unique_ptr openOrSkip(EventLoop& loop, AddressFamily family) +{ + auto opened = core::net::openAsyncDatagramSocket(loop, family); + if (!opened.has_value() && family == AddressFamily::Ipv6) + SKIP("this host has no IPv6: " << opened.error().toString()); + REQUIRE(opened.has_value()); + return std::move(*opened); +} + +/// @return A socket of @p family bound to its loopback at a kernel-chosen port, or a SKIP where +/// the host has no IPv6 loopback. +[[nodiscard]] std::unique_ptr boundOrSkip(EventLoop& loop, AddressFamily family) +{ + auto socket = openOrSkip(loop, family); + auto const bound = socket->bind(loopback(family, 0)); + if (!bound.has_value() && family == AddressFamily::Ipv6) + SKIP("this host has no IPv6 loopback: " << bound.error().toString()); + REQUIRE(bound.has_value()); + return socket; +} + +/// @return What one receive on @p socket answered, bounded. +[[nodiscard]] std::expected receiveWithin(EventLoop& loop, + IAsyncDatagramSocket& socket, + std::size_t maxBytes) +{ + auto out = std::optional> {}; + blockOnWithin(loop, [](IAsyncDatagramSocket* s, std::size_t max, decltype(out)* into) -> Task { + *into = co_await s->receive(max); + }(&socket, maxBytes, &out)); + REQUIRE(out.has_value()); + return std::move(*out); +} + +/// @return What one send from @p socket answered, bounded. +[[nodiscard]] std::expected sendWithin(EventLoop& loop, + IAsyncDatagramSocket& socket, + std::vector payload, + std::optional to) +{ + auto out = std::optional> {}; + blockOnWithin(loop, + [](IAsyncDatagramSocket* s, + std::vector bytesToSend, + std::optional destination, + decltype(out)* into) -> Task { + *into = co_await s->send(std::move(bytesToSend), destination); + }(&socket, std::move(payload), to, &out)); + REQUIRE(out.has_value()); + return *out; +} + +[[nodiscard]] AddressFamily eachFamily() +{ + return GENERATE(AddressFamily::Ipv4, AddressFamily::Ipv6); +} + +} // namespace + +TEST_CASE("A datagram echoes over loopback, with its sender", "[net][async-datagram][loopback]") +{ + auto const family = eachFamily(); + auto context = Loop {}; + auto server = boundOrSkip(context.loop, family); + auto client = boundOrSkip(context.loop, family); + + REQUIRE(sendWithin(context.loop, *client, bytes(1200), server->localEndpoint().value()).has_value()); + auto const got = receiveWithin(context.loop, *server, 2048); + REQUIRE(got.has_value()); + CHECK(got->payload == bytes(1200)); + CHECK(ipOf(got->from) == ipOf(client->localEndpoint())); + + REQUIRE(sendWithin(context.loop, *server, got->payload, got->from).has_value()); + auto const echoed = receiveWithin(context.loop, *client, 2048); + REQUIRE(echoed.has_value()); + CHECK(echoed->payload == bytes(1200)); + CHECK(ipOf(echoed->from) == ipOf(server->localEndpoint())); +} + +TEST_CASE("A receive and a send in flight together both complete", "[net][async-datagram][loopback]") +{ + auto context = Loop {}; + auto server = boundOrSkip(context.loop, AddressFamily::Ipv4); + auto client = boundOrSkip(context.loop, AddressFamily::Ipv4); + auto const to = server->localEndpoint().value(); + + // The receive parks before the datagram exists, so the readiness or completion path -- not a + // datagram already queued -- is what answers it. + auto received = std::optional> {}; + auto sent = std::optional> {}; + blockOnWithin( + context.loop, + core::net::testing::allOf( + [](IAsyncDatagramSocket* s, decltype(received)* into) -> Task { + *into = co_await s->receive(64); + }(server.get(), &received), + [](EventLoop* loop, IAsyncDatagramSocket* s, ResolvedEndpoint target, decltype(sent)* into) + -> Task { + co_await loop->delay(std::chrono::milliseconds { 20 }); + *into = co_await s->send(bytes(33), target); + }(&context.loop, client.get(), to, &sent))); + REQUIRE(sent.has_value()); + CHECK(sent->has_value()); + REQUIRE(received.has_value()); + REQUIRE(received->has_value()); + CHECK((*received)->payload == bytes(33)); +} + +TEST_CASE("A connected datagram socket hears its remote alone", "[net][async-datagram][loopback]") +{ + auto context = Loop {}; + auto server = boundOrSkip(context.loop, AddressFamily::Ipv4); + auto peer = boundOrSkip(context.loop, AddressFamily::Ipv4); + auto stranger = boundOrSkip(context.loop, AddressFamily::Ipv4); + auto const to = server->localEndpoint().value(); + + REQUIRE(server->connect(peer->localEndpoint().value()).has_value()); + CHECK(ipOf(server->remoteEndpoint()) == ipOf(peer->localEndpoint())); + + REQUIRE(sendWithin(context.loop, *stranger, bytes(10, 1), to).has_value()); + REQUIRE(sendWithin(context.loop, *peer, bytes(10, 2), to).has_value()); + auto const first = receiveWithin(context.loop, *server, 64); + REQUIRE(first.has_value()); + CHECK(first->payload == bytes(10, 2)); + CHECK(ipOf(first->from) == ipOf(peer->localEndpoint())); + + // To the remote, by default and by name: the second is what macOS refuses as EISCONN unless + // the socket leaves the address off. + REQUIRE(sendWithin(context.loop, *server, bytes(3, 3), std::nullopt).has_value()); + REQUIRE(sendWithin(context.loop, *server, bytes(3, 4), peer->localEndpoint().value()).has_value()); + auto const byDefault = receiveWithin(context.loop, *peer, 64); + REQUIRE(byDefault.has_value()); + CHECK(byDefault->payload == bytes(3, 3)); + auto const byName = receiveWithin(context.loop, *peer, 64); + REQUIRE(byName.has_value()); + CHECK(byName->payload == bytes(3, 4)); + + // Disconnected, the stranger is heard again -- at the same port, which Linux takes from a + // socket that bound port 0 unless it is bound again. + auto const before = ipOf(server->localEndpoint()); + auto const disconnected = server->connect(std::nullopt); + if (!disconnected.has_value()) + { + // macOS and the BSDs widen the loopback address to the wildcard at a disconnect: the socket + // is closed rather than left hearing every interface. + CHECK(disconnected.error().code == NetErrorCode::Unsupported); + CHECK(failedWith(server->localEndpoint(), NetErrorCode::BadHandle)); + SKIP("this system widens a bound address at a disconnect; the socket was closed, as it must be"); + } + CHECK(ipOf(server->localEndpoint()) == before); + CHECK(failedWith(server->remoteEndpoint(), NetErrorCode::BadHandle)); + REQUIRE(sendWithin(context.loop, *stranger, bytes(10, 5), to).has_value()); + auto const after = receiveWithin(context.loop, *server, 64); + REQUIRE(after.has_value()); + CHECK(after->payload == bytes(10, 5)); + CHECK(ipOf(after->from) == ipOf(stranger->localEndpoint())); +} + +TEST_CASE("A disconnect keeps the wildcard a datagram socket bound, at its port", + "[net][async-datagram][loopback]") +{ + // While connected, `getsockname` reports the route's source address; binding that again after + // the disconnect would leave the socket hearing one interface rather than every one. + auto const family = eachFamily(); + auto context = Loop {}; + auto socket = openOrSkip(context.loop, family); + auto const any = family == AddressFamily::Ipv6 + ? core::net::toEndpoint(IpSocketAddress { .address = Ipv6Address {}, .port = 0 }) + : core::net::toEndpoint(IpSocketAddress { .address = Ipv4Address {}, .port = 0 }); + REQUIRE(socket->bind(any).has_value()); + auto const port = ipOf(socket->localEndpoint()).port; + REQUIRE(port != 0); + auto peer = boundOrSkip(context.loop, family); + + REQUIRE(socket->connect(peer->localEndpoint().value()).has_value()); + REQUIRE(socket->connect(std::nullopt).has_value()); + + auto const local = ipOf(socket->localEndpoint()); + CHECK(local.address == ipOf(any).address); + CHECK(local.port == port); +} + +TEST_CASE("A send on an unbound datagram socket binds it to an ephemeral port", + "[net][async-datagram][loopback]") +{ + auto const family = eachFamily(); + auto context = Loop {}; + auto server = boundOrSkip(context.loop, family); + auto client = openOrSkip(context.loop, family); + + REQUIRE(sendWithin(context.loop, *client, bytes(8), server->localEndpoint().value()).has_value()); + auto const local = ipOf(client->localEndpoint()); + CHECK(local.port != 0); + + auto const got = receiveWithin(context.loop, *server, 64); + REQUIRE(got.has_value()); + CHECK(ipOf(got->from).port == local.port); + + // Bound now, so it receives the answer at that port. + REQUIRE(sendWithin(context.loop, *server, bytes(2), got->from).has_value()); + auto const answer = receiveWithin(context.loop, *client, 64); + REQUIRE(answer.has_value()); + CHECK(answer->payload == bytes(2)); +} + +TEST_CASE("A datagram longer than the receive is MessageTooLarge, never cut short", + "[net][async-datagram][loopback]") +{ + auto context = Loop {}; + auto server = boundOrSkip(context.loop, AddressFamily::Ipv4); + auto client = boundOrSkip(context.loop, AddressFamily::Ipv4); + auto const to = server->localEndpoint().value(); + + REQUIRE(sendWithin(context.loop, *client, bytes(100), to).has_value()); + REQUIRE(sendWithin(context.loop, *client, bytes(10), to).has_value()); + REQUIRE(sendWithin(context.loop, *client, bytes(1000), to).has_value()); + + CHECK(failedWith(receiveWithin(context.loop, *server, 10 - 1), NetErrorCode::MessageTooLarge)); + auto const exact = receiveWithin(context.loop, *server, 10); + REQUIRE(exact.has_value()); + CHECK(exact->payload == bytes(10)); + // A limit past the largest datagram is clamped rather than allocated. + auto const unlimited = receiveWithin(context.loop, *server, std::numeric_limits::max()); + REQUIRE(unlimited.has_value()); + CHECK(unlimited->payload == bytes(1000)); +} + +TEST_CASE("A dead peer's ICMP answer does not fail the next receive", "[net][async-datagram][loopback]") +{ + // On Windows an unconnected UDP socket that sent to a closed port fails its next receive with + // WSAECONNRESET, unless SIO_UDP_CONNRESET is turned off. Elsewhere this is how it always was. + auto context = Loop {}; + auto server = boundOrSkip(context.loop, AddressFamily::Ipv4); + auto peer = boundOrSkip(context.loop, AddressFamily::Ipv4); + + auto const deadPort = [&] { + auto dead = boundOrSkip(context.loop, AddressFamily::Ipv4); + return ipOf(dead->localEndpoint()).port; + }(); + + REQUIRE(sendWithin(context.loop, *server, bytes(4), loopback(AddressFamily::Ipv4, deadPort)).has_value()); + // Time for the port-unreachable to come back before anything else does. + blockOnWithin(context.loop, + core::net::testing::sleepFor(&context.loop, std::chrono::milliseconds { 50 })); + REQUIRE(sendWithin(context.loop, *peer, bytes(6), server->localEndpoint().value()).has_value()); + + auto const got = receiveWithin(context.loop, *server, 64); + REQUIRE(got.has_value()); + CHECK(got->payload == bytes(6)); +} + +TEST_CASE("A stop or a close ends a real datagram receive", "[net][async-datagram][loopback]") +{ + auto context = Loop {}; + auto server = boundOrSkip(context.loop, AddressFamily::Ipv4); + + SECTION("a stop throws, and the socket still receives") + { + auto isCancelled = false; + blockOnWithin(context.loop, + core::net::testing::anyOf( + [](IAsyncDatagramSocket* s, bool* cancelled) -> Task { + try + { + std::ignore = co_await s->receive(64); + } + catch (core::async::OperationCancelled const&) + { + *cancelled = true; + throw; + } + }(server.get(), &isCancelled), + core::net::testing::sleepFor(&context.loop, std::chrono::milliseconds { 20 }))); + CHECK(isCancelled); + + auto client = boundOrSkip(context.loop, AddressFamily::Ipv4); + REQUIRE(sendWithin(context.loop, *client, bytes(5), server->localEndpoint().value()).has_value()); + auto const got = receiveWithin(context.loop, *server, 64); + REQUIRE(got.has_value()); + CHECK(got->payload == bytes(5)); + } + + SECTION("a close resolves it with Cancelled") + { + auto out = std::optional> {}; + blockOnWithin(context.loop, + core::net::testing::allOf( + [](IAsyncDatagramSocket* s, decltype(out)* into) -> Task { + *into = co_await s->receive(64); + }(server.get(), &out), + [](EventLoop* loop, IAsyncDatagramSocket* s) -> Task { + co_await loop->delay(std::chrono::milliseconds { 20 }); + s->close(); + }(&context.loop, server.get()))); + REQUIRE(out.has_value()); + CHECK(failedWith(*out, NetErrorCode::Cancelled)); + CHECK(failedWith(server->localEndpoint(), NetErrorCode::BadHandle)); + } + + SECTION("destroying the socket resolves it with Cancelled") + { + auto out = std::optional> {}; + blockOnWithin(context.loop, + core::net::testing::allOf( + [](IAsyncDatagramSocket* s, decltype(out)* into) -> Task { + *into = co_await s->receive(64); + }(server.get(), &out), + [](EventLoop* loop, std::unique_ptr* s) -> Task { + co_await loop->delay(std::chrono::milliseconds { 20 }); + s->reset(); + }(&context.loop, &server))); + REQUIRE(out.has_value()); + CHECK(failedWith(*out, NetErrorCode::Cancelled)); + } +} + +TEST_CASE("A datagram socket sets and reads back its options", "[net][async-datagram][loopback]") +{ + auto const family = eachFamily(); + auto context = Loop {}; + auto socket = openOrSkip(context.loop, family); + + REQUIRE(socket->setOption(SocketOption::UnicastHopLimit, 17).has_value()); + CHECK(socket->option(SocketOption::UnicastHopLimit) == 17U); + REQUIRE(socket->setOption(SocketOption::ReceiveBufferSize, 65536).has_value()); + auto const receiveBuffer = socket->option(SocketOption::ReceiveBufferSize); + REQUIRE(receiveBuffer.has_value()); + CHECK(*receiveBuffer >= 4096U); + REQUIRE(socket->setOption(SocketOption::SendBufferSize, 65536).has_value()); + CHECK(socket->option(SocketOption::SendBufferSize).has_value()); + + // A row exists for keep-alive, and a datagram socket still refuses it: it is a stream's. + CHECK(failedWith(socket->option(SocketOption::KeepAliveEnabled), NetErrorCode::Unsupported)); + CHECK(failedWith(socket->setOption(SocketOption::KeepAliveIdleTime, 30), NetErrorCode::Unsupported)); +} diff --git a/src/core/net/AsyncDatagramSocket.cpp b/src/core/net/AsyncDatagramSocket.cpp new file mode 100644 index 00000000..a496a57c --- /dev/null +++ b/src/core/net/AsyncDatagramSocket.cpp @@ -0,0 +1,355 @@ +// SPDX-License-Identifier: Apache-2.0 + +/// @file +/// `openAsyncDatagramSocket` and the one `IAsyncDatagramSocket` implementation: the state machine, +/// written once over an `detail::IDatagramChannel` -- the platform's, or the in-memory network's. + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace core::net +{ + +namespace +{ + /// The options a datagram socket has. The keep-alive rows exist too, and some kernels even + /// accept `SO_KEEPALIVE` on a UDP socket, but a datagram has no connection to keep alive. + constexpr auto DatagramOptions = std::array { + SocketOption::ReceiveBufferSize, + SocketOption::SendBufferSize, + SocketOption::UnicastHopLimit, + }; + + /// @return The socket's own refusal of a call its state does not allow: never the OS's. + [[nodiscard]] NetError refused(std::string what) + { + return makeNetError(NetErrorCode::BadHandle, 0, std::move(what)); + } + + /// @return A task that answers @p error without touching any socket. + template + async::Task> refuse(NetError error) + { + co_return std::unexpected(std::move(error)); + } + + /// @return @p family's wildcard address at port 0. + [[nodiscard]] ResolvedEndpoint wildcardOf(AddressFamily family) noexcept + { + if (family == AddressFamily::Ipv6) + return toEndpoint(IpSocketAddress { .address = Ipv6Address {} }); + return toEndpoint(IpSocketAddress { .address = Ipv4Address {} }); + } + + /// Which operations a socket has in flight. Shared with the tasks it hands out, because a + /// task may outlive its socket. Two predicates rather than one state: a receive and a send are + /// independent, and all four combinations are legal. + struct Outstanding + { + bool isReceiving = false; ///< A receive is in flight. + bool isSending = false; ///< A send is in flight. + }; + + /// One in-flight operation's hold on its slot in @c Outstanding. + using Claim = detail::OperationClaim; + + /// The one `IAsyncDatagramSocket`: what each state allows, over a channel that does it. + class AsyncDatagramSocket final: public IAsyncDatagramSocket + { + public: + /// @param channel The channel, unbound. + /// @param family The family it was opened with. + AsyncDatagramSocket(std::shared_ptr channel, AddressFamily family): + _channel { std::move(channel) }, _family { family } + { + } + + ~AsyncDatagramSocket() override { close(); } + AsyncDatagramSocket(AsyncDatagramSocket const&) = delete; + AsyncDatagramSocket& operator=(AsyncDatagramSocket const&) = delete; + AsyncDatagramSocket(AsyncDatagramSocket&&) = delete; + AsyncDatagramSocket& operator=(AsyncDatagramSocket&&) = delete; + + [[nodiscard]] std::expected bind(ResolvedEndpoint const& local) override + { + if (_isClosed) + return std::unexpected(refused("bind on a closed datagram socket")); + // Refused here rather than by the kernel, whose second bind is an `EINVAL` that reads + // like a bad address. + if (_bound.has_value()) + return std::unexpected(refused("bind on a datagram socket that is already bound")); + return ofFamily(local, "bind").and_then([&](IpSocketAddress const& address) { + return _channel->bind(local).transform([&] { _bound = address; }); + }); + } + + [[nodiscard]] std::expected connect(std::optional remote) override + { + if (_isClosed) + return std::unexpected(refused("connect on a closed datagram socket")); + if (!remote.has_value()) + { + if (!_remote.has_value()) + return std::unexpected(refused("disconnect on an unconnected datagram socket")); + // The port, from before: Linux unbinds a socket whose port the kernel chose when it + // disconnects (`__udp_disconnect` unhashes it unless the port was named), so a + // socket that bound port 0 would lose the port its peers know it by. + return _channel->endpoint(detail::SocketSide::Local) + .and_then([&](ResolvedEndpoint const& local) { + auto const port = detail::portOfSockaddr(local.storage.data(), local.length); + return _channel->connect(std::nullopt).and_then([&] { + // Disconnected from here, whether or not the port can be taken back. + _remote.reset(); + return keepPort(port).and_then([&] { return keepAddress(); }); + }); + }); + } + return ofFamily(*remote, "connect").and_then([&](IpSocketAddress address) { + return bindIfUnbound().and_then([&] { return _channel->connect(remote); }).transform([&] { + _remote = address; + }); + }); + } + + [[nodiscard]] async::Task> receive( + std::size_t maxBytes) override + { + if (_isClosed) + return refuse(refused("receive on a closed datagram socket")); + // Not left to the kernel, which parks an unbound POSIX socket for ever and fails a + // Windows one: one answer on every platform. + if (!_bound.has_value()) + return refuse(refused("receive on an unbound datagram socket")); + if (_outstanding->isReceiving) + return refuse(refused("receive while another receive is in flight")); + // Clamped, so a caller asking for "anything" is not taken at its word by the allocator. + return detail::holding(Claim { _outstanding, &Outstanding::isReceiving }, + _channel->receive(std::min(maxBytes, MaxIpv6DatagramPayload))); + } + + [[nodiscard]] async::Task> send( + std::vector payload, std::optional to) override + { + if (_isClosed) + return refuse(refused("send on a closed datagram socket")); + if (_outstanding->isSending) + return refuse(refused("send while another send is in flight")); + auto destination = destinationOf(to); + if (!destination.has_value()) + return refuse(std::move(destination.error())); + if (auto bound = bindIfUnbound(); !bound.has_value()) + return refuse(std::move(bound.error())); + return detail::holding(Claim { _outstanding, &Outstanding::isSending }, + _channel->send(std::move(payload), *destination)); + } + + [[nodiscard]] std::expected localEndpoint() const override + { + if (_isClosed) + return std::unexpected(refused("localEndpoint on a closed datagram socket")); + // Not asked of the OS: an unbound socket is the wildcard at port 0 on POSIX and an error + // on Windows. + if (!_bound.has_value()) + return std::unexpected(refused("localEndpoint on an unbound datagram socket")); + return _channel->endpoint(detail::SocketSide::Local); + } + + [[nodiscard]] std::expected remoteEndpoint() const override + { + if (_isClosed) + return std::unexpected(refused("remoteEndpoint on a closed datagram socket")); + if (!_remote.has_value()) + return std::unexpected(refused("remoteEndpoint on an unconnected datagram socket")); + return _channel->endpoint(detail::SocketSide::Remote); + } + + [[nodiscard]] std::expected option(SocketOption option) const override + { + return optionAllowed(option, "option").and_then([&] { return _channel->option(option); }); + } + + [[nodiscard]] std::expected setOption(SocketOption option, + std::uint64_t value) override + { + return optionAllowed(option, "setOption").and_then([&] { + return _channel->setOption(option, value); + }); + } + + void close() noexcept override + { + if (std::exchange(_isClosed, true)) + return; + _channel->close(); + } + + private: + /// @return @p endpoint as an IP address, or why it is not one of this socket's family. + [[nodiscard]] std::expected ofFamily(ResolvedEndpoint const& endpoint, + char const* operation) const + { + return toIpSocketAddress(endpoint).and_then( + [&](IpSocketAddress address) -> std::expected { + if (address.family() != _family) + return std::unexpected( + makeNetError(NetErrorCode::AddressError, + 0, + std::string { operation } + + ": the endpoint is not of the socket's address family")); + return address; + }); + } + + /// Binds what was bound again where a disconnect took its port, and does nothing otherwise -- + /// on every kernel but Linux, and on Linux for a socket bound to a named port. + /// + /// The address is the one @c bind was given, wildcard or named, not what `getsockname` + /// said while connected: that is the route's source address, and binding it would leave a + /// wildcard socket hearing one interface. + /// @param port The port the socket held before the disconnect. + /// @return Nothing, or @c NetErrorCode::AddressInUse where another socket took the port in + /// between. The socket is disconnected either way. + [[nodiscard]] std::expected keepPort(std::uint16_t port) + { + auto const now = _channel->endpoint(detail::SocketSide::Local); + if (now.has_value() && detail::portOfSockaddr(now->storage.data(), now->length) != 0) + return {}; + auto again = *_bound; + again.port = port; + return _channel->bind(toEndpoint(again)); + } + + /// Refuses a disconnect that left the socket bound wider than it was bound: macOS and the BSDs + /// reset a socket's local address to the wildcard when it disconnects (`udp_disconnect`), so + /// one bound to 127.0.0.1 would go on hearing every interface. Its port it keeps, so it cannot + /// be bound to the address again; it is closed instead, which fails closed. + /// @return Nothing where the address is the one @c bind was given, or a wildcard was; + /// @c NetErrorCode::Unsupported, the socket closed, where it is wider now. + [[nodiscard]] std::expected keepAddress() + { + auto const isWildcard = std::visit( + [](auto const& address) { + auto const isZero = [](auto part) { + return part == 0; + }; + if constexpr (std::is_same_v, Ipv4Address>) + return std::ranges::all_of(address.octets, isZero); + else + return std::ranges::all_of(address.segments, isZero); + }, + _bound->address); + if (isWildcard) + return {}; + auto const now = + _channel->endpoint(detail::SocketSide::Local).and_then([](ResolvedEndpoint const& local) { + return toIpSocketAddress(local); + }); + if (now.has_value() && now->address == _bound->address) + return {}; + close(); + return std::unexpected( + makeNetError(NetErrorCode::Unsupported, + 0, + "the system widened the bound address at the disconnect, so the " + "socket is closed rather than heard on every interface")); + } + + /// Binds the family's wildcard where nothing is bound yet, so a socket that sends or + /// connects has a port to be answered on and a state that says so. + [[nodiscard]] std::expected bindIfUnbound() + { + if (_bound.has_value()) + return {}; + return bind(wildcardOf(_family)); + } + + /// Where a send goes: @p to on an unconnected socket, nothing (the kernel's remote) on a + /// connected one. Naming the remote is allowed and sent unaddressed, because macOS refuses + /// an address on a connected socket with `EISCONN` where Linux and Windows accept it. + [[nodiscard]] std::expected, NetError> destinationOf( + std::optional to) const + { + if (!_remote.has_value()) + { + if (!to.has_value()) + return std::unexpected( + refused("send with no destination on an unconnected datagram socket")); + return ofFamily(*to, "send").transform([&](IpSocketAddress const&) { return to; }); + } + if (!to.has_value()) + return std::optional {}; + return ofFamily(*to, "send") + .and_then([&](IpSocketAddress const& address) + -> std::expected, NetError> { + if (address != *_remote) + return std::unexpected( + makeNetError(NetErrorCode::AddressError, + 0, + "send: a connected datagram socket sends to its remote only")); + return std::optional {}; + }); + } + + /// @return Nothing when @p option may be asked of an open datagram socket. + [[nodiscard]] std::expected optionAllowed(SocketOption option, + char const* operation) const + { + if (_isClosed) + return std::unexpected(refused(std::string { operation } + " on a closed datagram socket")); + if (std::ranges::find(DatagramOptions, option) == DatagramOptions.end()) + return std::unexpected( + makeNetError(NetErrorCode::Unsupported, + 0, + std::string { operation } + ": a datagram socket has no such option")); + return {}; + } + + std::shared_ptr _channel; + AddressFamily _family; + std::optional _bound; ///< What @c bind was given; empty while unbound. + std::shared_ptr _outstanding = std::make_shared(); + std::optional _remote; ///< The connected remote; empty while unconnected. + bool _isClosed = false; + }; +} // namespace + +namespace detail +{ + std::unique_ptr makeAsyncDatagramSocket(std::shared_ptr channel, + AddressFamily family) + { + return std::make_unique(std::move(channel), family); + } +} // namespace detail + +std::expected, NetError> openAsyncDatagramSocket(EventLoop& loop, + AddressFamily family) +{ + // Before the socket exists, as a dial asks: on Windows, a loop with no completion port could + // never complete a send or a receive. + return detail::dialableOn(loop) + .and_then([&loop, family] { return detail::openDatagramChannel(loop, family); }) + .transform([family](std::shared_ptr channel) { + return detail::makeAsyncDatagramSocket(std::move(channel), family); + }); +} + +} // namespace core::net diff --git a/src/core/net/AsyncDatagram_test.cpp b/src/core/net/AsyncDatagram_test.cpp new file mode 100644 index 00000000..008c090f --- /dev/null +++ b/src/core/net/AsyncDatagram_test.cpp @@ -0,0 +1,527 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// `IAsyncDatagramSocket`'s state machine and cancellation, over `testing::InMemoryAsyncDatagramNetwork`. +// +// **In memory, and on a loop that waits on nothing**, because what is asserted here is the +// socket's own: which state refuses what, what a stop and a close each resolve a pending receive +// with, and that a datagram already taken is never lost to a stop. The double runs the real +// socket's state machine, so every refusal here is the real socket's too; what only the kernel can +// answer is `AsyncDatagramLoopback_test.cpp`. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using core::async::Task; +using core::net::AddressFamily; +using core::net::AsyncDatagram; +using core::net::IAsyncDatagramSocket; +using core::net::IpSocketAddress; +using core::net::Ipv4Address; +using core::net::Ipv6Address; +using core::net::NetError; +using core::net::NetErrorCode; +using core::net::ResolvedEndpoint; +using core::net::SocketOption; +using core::net::testing::InMemoryAsyncDatagramNetwork; +using core::net::testing::TestLoop; + +namespace +{ + +/// @return The loopback address of @p family, at @p port. +[[nodiscard]] ResolvedEndpoint loopback(AddressFamily family, std::uint16_t port) +{ + if (family == AddressFamily::Ipv6) + return core::net::toEndpoint( + IpSocketAddress { .address = Ipv6Address { { 0, 0, 0, 0, 0, 0, 0, 1 } }, .port = port }); + return core::net::toEndpoint( + IpSocketAddress { .address = Ipv4Address { { 127, 0, 0, 1 } }, .port = port }); +} + +/// @return @p family's wildcard address at @p port. +[[nodiscard]] ResolvedEndpoint wildcard(AddressFamily family, std::uint16_t port) +{ + if (family == AddressFamily::Ipv6) + return core::net::toEndpoint(IpSocketAddress { .address = Ipv6Address {}, .port = port }); + return core::net::toEndpoint(IpSocketAddress { .address = Ipv4Address {}, .port = port }); +} + +/// @return The IP form of @p endpoint, which the case requires to exist. +[[nodiscard]] IpSocketAddress ipOf(std::expected const& endpoint) +{ + REQUIRE(endpoint.has_value()); + auto address = core::net::toIpSocketAddress(*endpoint); + REQUIRE(address.has_value()); + return *address; +} + +/// @return Whether @p result failed with @p code. +template +[[nodiscard]] bool failedWithCode(std::expected const& result, NetErrorCode code) +{ + return !result.has_value() && result.error().code == code; +} + +/// @return Whether @p result failed with @p code and no system code: a refusal that never +/// reached an OS. +template +[[nodiscard]] bool refusedWith(std::expected const& result, NetErrorCode code) +{ + return !result.has_value() && result.error().code == code && result.error().systemCode == 0; +} + +/// @return @p count bytes, each its own index. +[[nodiscard]] std::vector bytes(std::size_t count) +{ + auto out = std::vector(count); + for (auto index = std::size_t { 0 }; auto& value: out) + value = static_cast(index++ & 0xFFU); + return out; +} + +/// What a receiving flow ended with. +struct Received +{ + std::optional> result; ///< Set when it returned. + bool isCancelled = false; ///< Set when it unwound. + bool isFinished = false; ///< Set either way. +}; + +/// Receives one datagram into @p out, recording an unwind rather than letting it escape. +Task receiveInto(IAsyncDatagramSocket* socket, std::size_t maxBytes, Received* out) +{ + try + { + out->result = co_await socket->receive(maxBytes); + } + catch (core::async::OperationCancelled const&) + { + out->isCancelled = true; + } + out->isFinished = true; +} + +/// Sends one datagram and records the outcome. +Task sendInto(IAsyncDatagramSocket* socket, + std::vector payload, + std::optional to, + std::optional>* out) +{ + *out = co_await socket->send(std::move(payload), to); +} + +/// The network, a loop, and the means to run a flow on it. +struct Fixture +{ + core::platform::ManualClock clock {}; + TestLoop loop { clock }; + InMemoryAsyncDatagramNetwork network {}; + + /// @return An open, unbound socket of @p family. + [[nodiscard]] std::unique_ptr open(AddressFamily family) + { + auto opened = network.open(loop, family); + REQUIRE(opened.has_value()); + return std::move(*opened); + } + + /// @return A socket of @p family bound to its loopback at a port the network chose. + [[nodiscard]] std::unique_ptr bound(AddressFamily family) + { + auto socket = open(family); + REQUIRE(socket->bind(loopback(family, 0)).has_value()); + return socket; + } + + /// Sends @p payload from @p socket and returns what the send answered. + [[nodiscard]] std::expected send(IAsyncDatagramSocket& socket, + std::vector payload, + std::optional to) + { + auto out = std::optional> {}; + auto flow = sendInto(&socket, std::move(payload), to, &out); + flow.handle().resume(); + std::ignore = loop.drain(); + REQUIRE(out.has_value()); + return *out; + } + + /// Starts @p flow and runs the loop until nothing is left to do. + void run(Task& flow) + { + flow.handle().resume(); + std::ignore = loop.drain(); + } + + /// @return What one receive on @p socket answered, the loop run until it settled. + [[nodiscard]] std::expected receive(IAsyncDatagramSocket& socket, + std::size_t maxBytes) + { + auto out = Received {}; + auto flow = receiveInto(&socket, maxBytes, &out); + run(flow); + REQUIRE(out.result.has_value()); + return std::move(*out.result); + } +}; + +[[nodiscard]] AddressFamily eachFamily() +{ + return GENERATE(AddressFamily::Ipv4, AddressFamily::Ipv6); +} + +} // namespace + +TEST_CASE("An in-memory datagram arrives whole, with its sender", "[net][async-datagram][inmemory]") +{ + auto const family = eachFamily(); + auto fixture = Fixture {}; + auto server = fixture.bound(family); + auto client = fixture.bound(family); + + REQUIRE(fixture.send(*client, bytes(300), server->localEndpoint().value()).has_value()); + auto const got = fixture.receive(*server, 1024); + REQUIRE(got.has_value()); + CHECK(got->payload == bytes(300)); + CHECK(ipOf(got->from) == ipOf(client->localEndpoint())); + + // And back, to the address the datagram said it came from. + REQUIRE(fixture.send(*server, bytes(7), got->from).has_value()); + auto const echoed = fixture.receive(*client, 7); + REQUIRE(echoed.has_value()); + CHECK(echoed->payload == bytes(7)); + CHECK(ipOf(echoed->from) == ipOf(server->localEndpoint())); +} + +TEST_CASE("An in-memory receive on an unbound socket is refused as BadHandle", + "[net][async-datagram][inmemory]") +{ + auto fixture = Fixture {}; + auto socket = fixture.open(AddressFamily::Ipv4); + CHECK(refusedWith(fixture.receive(*socket, 64), NetErrorCode::BadHandle)); + CHECK(refusedWith(socket->localEndpoint(), NetErrorCode::BadHandle)); +} + +TEST_CASE("A stop during an in-memory receive throws, and leaves the socket usable", + "[net][async-datagram][inmemory]") +{ + auto fixture = Fixture {}; + auto server = fixture.bound(AddressFamily::Ipv4); + auto client = fixture.bound(AddressFamily::Ipv4); + + auto source = core::async::StopSource {}; + auto out = Received {}; + auto flow = receiveInto(server.get(), 64, &out); + flow.handle().promise().setStopToken(source.get_token()); + fixture.run(flow); + REQUIRE_FALSE(out.isFinished); + + source.request_stop(); + std::ignore = fixture.loop.drain(); + CHECK(out.isFinished); + CHECK(out.isCancelled); + CHECK_FALSE(out.result.has_value()); + + // A stop is not a close: the next receive answers the next datagram. + REQUIRE(fixture.send(*client, bytes(5), server->localEndpoint().value()).has_value()); + auto const got = fixture.receive(*server, 64); + REQUIRE(got.has_value()); + CHECK(got->payload == bytes(5)); +} + +TEST_CASE("close() during an in-memory receive resolves it with Cancelled", "[net][async-datagram][inmemory]") +{ + auto fixture = Fixture {}; + auto server = fixture.bound(AddressFamily::Ipv4); + + auto out = Received {}; + auto flow = receiveInto(server.get(), 64, &out); + fixture.run(flow); + REQUIRE_FALSE(out.isFinished); + + server->close(); + std::ignore = fixture.loop.drain(); + REQUIRE(out.isFinished); + CHECK_FALSE(out.isCancelled); + REQUIRE(out.result.has_value()); + CHECK(refusedWith(*out.result, NetErrorCode::Cancelled)); +} + +TEST_CASE("Destroying an in-memory socket during a receive resolves it with Cancelled", + "[net][async-datagram][inmemory]") +{ + auto fixture = Fixture {}; + auto server = fixture.bound(AddressFamily::Ipv4); + + auto out = Received {}; + auto flow = receiveInto(server.get(), 64, &out); + fixture.run(flow); + REQUIRE_FALSE(out.isFinished); + + // The frame keeps its own share of what it reads after it resumes. + server.reset(); + std::ignore = fixture.loop.drain(); + REQUIRE(out.isFinished); + REQUIRE(out.result.has_value()); + CHECK(refusedWith(*out.result, NetErrorCode::Cancelled)); +} + +TEST_CASE("A datagram that arrived before the stop is delivered, not dropped", + "[net][async-datagram][inmemory]") +{ + auto fixture = Fixture {}; + auto server = fixture.bound(AddressFamily::Ipv4); + auto client = fixture.bound(AddressFamily::Ipv4); + + auto source = core::async::StopSource {}; + auto out = Received {}; + auto flow = receiveInto(server.get(), 64, &out); + flow.handle().promise().setStopToken(source.get_token()); + fixture.run(flow); + REQUIRE_FALSE(out.isFinished); + + // The datagram reaches the parked receive, and the stop lands before the loop resumes it. + auto sent = std::optional> {}; + auto sending = sendInto(client.get(), bytes(9), server->localEndpoint().value(), &sent); + sending.handle().resume(); + REQUIRE(sent.has_value()); + REQUIRE(sent->has_value()); + REQUIRE_FALSE(out.isFinished); + source.request_stop(); + std::ignore = fixture.loop.drain(); + + REQUIRE(out.isFinished); + CHECK_FALSE(out.isCancelled); + REQUIRE(out.result.has_value()); + REQUIRE(out.result->has_value()); + CHECK((*out.result)->payload == bytes(9)); +} + +TEST_CASE("An oversized in-memory datagram is MessageTooLarge, and the next one still arrives", + "[net][async-datagram][inmemory]") +{ + auto fixture = Fixture {}; + auto server = fixture.bound(AddressFamily::Ipv4); + auto client = fixture.bound(AddressFamily::Ipv4); + auto const to = server->localEndpoint().value(); + + REQUIRE(fixture.send(*client, bytes(10), to).has_value()); + REQUIRE(fixture.send(*client, bytes(4), to).has_value()); + + // Whole or not at all: ten bytes do not fit four, and are not handed back as four. + CHECK(refusedWith(fixture.receive(*server, 4), NetErrorCode::MessageTooLarge)); + // Exactly the limit fits. + auto const next = fixture.receive(*server, 4); + REQUIRE(next.has_value()); + CHECK(next->payload == bytes(4)); +} + +TEST_CASE("An in-memory payload above the family's largest is refused at the send", + "[net][async-datagram][inmemory]") +{ + auto fixture = Fixture {}; + auto server = fixture.bound(AddressFamily::Ipv6); + auto client = fixture.bound(AddressFamily::Ipv6); + auto const to = server->localEndpoint().value(); + + CHECK(refusedWith(fixture.send(*client, bytes(core::net::MaxIpv6DatagramPayload + 1), to), + NetErrorCode::MessageTooLarge)); + REQUIRE(fixture.send(*client, bytes(core::net::MaxIpv6DatagramPayload), to).has_value()); + // A limit beyond the largest datagram is clamped, not allocated. + auto const got = fixture.receive(*server, std::numeric_limits::max()); + REQUIRE(got.has_value()); + CHECK(got->payload.size() == core::net::MaxIpv6DatagramPayload); + + auto v4 = fixture.bound(AddressFamily::Ipv4); + auto v4Client = fixture.bound(AddressFamily::Ipv4); + CHECK(refusedWith( + fixture.send(*v4Client, bytes(core::net::MaxIpv4DatagramPayload + 1), v4->localEndpoint().value()), + NetErrorCode::MessageTooLarge)); +} + +TEST_CASE("connect filters what an in-memory socket receives, and disconnect lifts it", + "[net][async-datagram][inmemory]") +{ + auto fixture = Fixture {}; + auto server = fixture.bound(AddressFamily::Ipv4); + auto peer = fixture.bound(AddressFamily::Ipv4); + auto stranger = fixture.bound(AddressFamily::Ipv4); + auto const to = server->localEndpoint().value(); + + REQUIRE(server->connect(peer->localEndpoint().value()).has_value()); + CHECK(ipOf(server->remoteEndpoint()) == ipOf(peer->localEndpoint())); + + REQUIRE(fixture.send(*stranger, bytes(1), to).has_value()); + REQUIRE(fixture.send(*peer, bytes(2), to).has_value()); + auto const fromPeer = fixture.receive(*server, 64); + REQUIRE(fromPeer.has_value()); + CHECK(fromPeer->payload == bytes(2)); + + // A connected socket sends to its remote by default. + REQUIRE(fixture.send(*server, bytes(3), std::nullopt).has_value()); + auto const atPeer = fixture.receive(*peer, 64); + REQUIRE(atPeer.has_value()); + CHECK(atPeer->payload == bytes(3)); + + REQUIRE(server->connect(std::nullopt).has_value()); + CHECK(refusedWith(server->remoteEndpoint(), NetErrorCode::BadHandle)); + REQUIRE(fixture.send(*stranger, bytes(4), to).has_value()); + auto const fromStranger = fixture.receive(*server, 64); + REQUIRE(fromStranger.has_value()); + CHECK(fromStranger->payload == bytes(4)); +} + +TEST_CASE("An in-memory send on an unbound socket binds the wildcard at a fresh port", + "[net][async-datagram][inmemory]") +{ + auto const family = eachFamily(); + auto fixture = Fixture {}; + auto server = fixture.bound(family); + auto client = fixture.open(family); + + REQUIRE(fixture.send(*client, bytes(6), server->localEndpoint().value()).has_value()); + auto const local = ipOf(client->localEndpoint()); + CHECK(local.port != 0); + CHECK(local.address == ipOf(wildcard(family, 0)).address); + + // Answered at the port it was given, from the address a loopback route picks. + auto const got = fixture.receive(*server, 64); + REQUIRE(got.has_value()); + CHECK(ipOf(got->from).port == local.port); + CHECK(ipOf(got->from).address == ipOf(server->localEndpoint()).address); +} + +TEST_CASE("In-memory binds that overlap are AddressInUse", "[net][async-datagram][inmemory]") +{ + auto fixture = Fixture {}; + auto first = fixture.bound(AddressFamily::Ipv4); + auto const port = ipOf(first->localEndpoint()).port; + + auto same = fixture.open(AddressFamily::Ipv4); + CHECK(failedWithCode(same->bind(loopback(AddressFamily::Ipv4, port)), NetErrorCode::AddressInUse)); + auto any = fixture.open(AddressFamily::Ipv4); + CHECK(failedWithCode(any->bind(wildcard(AddressFamily::Ipv4, port)), NetErrorCode::AddressInUse)); + // The other family's port space is its own. + auto other = fixture.open(AddressFamily::Ipv6); + CHECK(other->bind(loopback(AddressFamily::Ipv6, port)).has_value()); + // A closed socket gives its port back. + first->close(); + CHECK(same->bind(loopback(AddressFamily::Ipv4, port)).has_value()); +} + +TEST_CASE("A datagram socket has one receive and one send in flight at a time", + "[net][async-datagram][inmemory]") +{ + auto fixture = Fixture {}; + auto server = fixture.bound(AddressFamily::Ipv4); + auto client = fixture.bound(AddressFamily::Ipv4); + auto const to = server->localEndpoint().value(); + + // A receive parked on the loop holds the receive slot; a send may still go. + auto first = Received {}; + auto parked = receiveInto(server.get(), 64, &first); + fixture.run(parked); + REQUIRE_FALSE(first.isFinished); + CHECK(refusedWith(fixture.receive(*server, 64), NetErrorCode::BadHandle)); + CHECK(fixture.send(*server, bytes(1), client->localEndpoint().value()).has_value()); + + // Answered, the slot is free again. + REQUIRE(fixture.send(*client, bytes(2), to).has_value()); + std::ignore = fixture.loop.drain(); + REQUIRE(first.isFinished); + REQUIRE(fixture.send(*client, bytes(3), to).has_value()); + auto const next = fixture.receive(*server, 64); + REQUIRE(next.has_value()); + CHECK(next->payload == bytes(3)); + + // A finished task gives its slot back at once, though its owner still holds it. + REQUIRE(fixture.send(*client, bytes(7), to).has_value()); + REQUIRE(fixture.send(*client, bytes(8), to).has_value()); + auto direct = server->receive(64); + direct.handle().resume(); + REQUIRE(direct.done()); + auto const after = fixture.receive(*server, 64); + REQUIRE(after.has_value()); + CHECK(after->payload == bytes(8)); + + // A task holds its slot from the call, even one that never runs, until it is destroyed. + { + auto const unstarted = client->send(bytes(4), to); + CHECK(refusedWith(fixture.send(*client, bytes(5), to), NetErrorCode::BadHandle)); + auto const unstartedReceive = client->receive(64); + CHECK(refusedWith(fixture.receive(*client, 64), NetErrorCode::BadHandle)); + } + CHECK(fixture.send(*client, bytes(6), to).has_value()); +} + +TEST_CASE("The datagram socket refuses each state's impossible calls without the OS", + "[net][async-datagram][inmemory]") +{ + auto fixture = Fixture {}; + auto socket = fixture.open(AddressFamily::Ipv4); + auto const somewhere = loopback(AddressFamily::Ipv4, 9); + + // Unconnected. + CHECK(refusedWith(socket->remoteEndpoint(), NetErrorCode::BadHandle)); + CHECK(refusedWith(socket->connect(std::nullopt), NetErrorCode::BadHandle)); + CHECK(refusedWith(fixture.send(*socket, bytes(1), std::nullopt), NetErrorCode::BadHandle)); + + // The other family, wherever an endpoint is taken. + auto const v6 = loopback(AddressFamily::Ipv6, 9); + CHECK(refusedWith(socket->bind(v6), NetErrorCode::AddressError)); + CHECK(refusedWith(socket->connect(v6), NetErrorCode::AddressError)); + CHECK(refusedWith(fixture.send(*socket, bytes(1), v6), NetErrorCode::AddressError)); + // None of those bound it. + CHECK(refusedWith(socket->localEndpoint(), NetErrorCode::BadHandle)); + + // Bound once. + REQUIRE(socket->bind(loopback(AddressFamily::Ipv4, 0)).has_value()); + CHECK(refusedWith(socket->bind(loopback(AddressFamily::Ipv4, 0)), NetErrorCode::BadHandle)); + // Bound but unconnected: there is nothing to disconnect. + CHECK(refusedWith(socket->connect(std::nullopt), NetErrorCode::BadHandle)); + + // Connected: a send names the remote or nothing. + REQUIRE(socket->connect(somewhere).has_value()); + CHECK(refusedWith(fixture.send(*socket, bytes(1), loopback(AddressFamily::Ipv4, 10)), + NetErrorCode::AddressError)); + CHECK(fixture.send(*socket, bytes(1), somewhere).has_value()); + + // The keep-alive options belong to a stream. + CHECK(refusedWith(socket->option(SocketOption::KeepAliveEnabled), NetErrorCode::Unsupported)); + CHECK(refusedWith(socket->setOption(SocketOption::KeepAliveCount, 3), NetErrorCode::Unsupported)); + + // Closed: everything. + socket->close(); + socket->close(); // idempotent + CHECK(refusedWith(socket->bind(loopback(AddressFamily::Ipv4, 0)), NetErrorCode::BadHandle)); + CHECK(refusedWith(socket->connect(somewhere), NetErrorCode::BadHandle)); + CHECK(refusedWith(socket->connect(std::nullopt), NetErrorCode::BadHandle)); + CHECK(refusedWith(socket->localEndpoint(), NetErrorCode::BadHandle)); + CHECK(refusedWith(socket->remoteEndpoint(), NetErrorCode::BadHandle)); + CHECK(refusedWith(socket->option(SocketOption::ReceiveBufferSize), NetErrorCode::BadHandle)); + CHECK(refusedWith(socket->setOption(SocketOption::ReceiveBufferSize, 1), NetErrorCode::BadHandle)); + CHECK(refusedWith(fixture.send(*socket, bytes(1), somewhere), NetErrorCode::BadHandle)); + CHECK(refusedWith(fixture.receive(*socket, 1), NetErrorCode::BadHandle)); +} diff --git a/src/core/net/CMakeLists.txt b/src/core/net/CMakeLists.txt index 3d44001b..5a2f106d 100644 --- a/src/core/net/CMakeLists.txt +++ b/src/core/net/CMakeLists.txt @@ -133,6 +133,7 @@ core_cpp_add_module(net KIND STATIC HttpServer.hpp IAdmissionControl.hpp IAsyncAddressResolver.hpp + IAsyncDatagramSocket.hpp ICompletionPort.hpp IConnector.hpp IDatagramSocket.hpp @@ -179,6 +180,7 @@ core_cpp_add_module(net KIND STATIC testing/CoroTestSupport.hpp testing/DatagramPayload.hpp testing/FailingListener.hpp + testing/InMemoryAsyncDatagram.hpp testing/InMemoryDatagram.hpp testing/InMemorySocket.hpp testing/InMemoryTransport.hpp @@ -195,6 +197,7 @@ core_cpp_add_module(net KIND STATIC AcceptLoopHealth.cpp AcceptPolicy.cpp AsyncBufferedReader.cpp + AsyncDatagramSocket.cpp BlockingConnector.cpp BlockingSocket.cpp ConnectFlow.cpp @@ -216,13 +219,16 @@ core_cpp_add_module(net KIND STATIC TcpSocket.cpp ThreadedAddressResolver.cpp WriteQueue.cpp + testing/InMemoryAsyncDatagram.cpp testing/InMemoryDatagram.cpp testing/InMemorySocket.cpp ${_coreCppNetDefaultBackend} detail/BlockingPrimitives.hpp detail/DatagramAddressing.hpp + detail/DatagramChannel.hpp detail/DatagramReceiveBuffer.hpp detail/DialPrimitives.hpp + detail/OperationClaim.hpp detail/PeerAddress.hpp detail/SocketEndpoint.hpp detail/SocketErrors.hpp @@ -244,6 +250,7 @@ core_cpp_add_module(net KIND STATIC posix/PosixSocket.cpp posix/PosixSocket.hpp posix/PosixTcpSocket.cpp + posix/ReadinessDatagramSocket.cpp posix/SocketErrors.cpp posix/SocketOptionTable.cpp posix/SocketsPosix.cpp @@ -268,6 +275,7 @@ core_cpp_add_module(net KIND STATIC windows/InvalidSocket.hpp windows/IocpBackend.cpp windows/IocpBackend.hpp + windows/IocpDatagramSocket.cpp windows/IocpDial.cpp windows/IocpOperation.hpp windows/IocpSocket.cpp @@ -366,6 +374,8 @@ core_cpp_add_test(net AcceptPolicy_test.cpp AdoptSocket_test.cpp AsyncBufferedReader_test.cpp + AsyncDatagram_test.cpp + AsyncDatagramLoopback_test.cpp BackendParity_test.cpp BlockingConnector_test.cpp BlockingSocket_test.cpp diff --git a/src/core/net/IAsyncDatagramSocket.hpp b/src/core/net/IAsyncDatagramSocket.hpp new file mode 100644 index 00000000..20bd360c --- /dev/null +++ b/src/core/net/IAsyncDatagramSocket.hpp @@ -0,0 +1,150 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// `IAsyncDatagramSocket` — a UDP socket driven by an @c EventLoop: it binds, optionally connects, +/// and sends and receives whole datagrams as coroutines. +/// +/// The blocking @c IDatagramSocket (``) is for a thread of its own +/// that sends a handful of datagrams a minute; this is for a flow on a loop, which must not block +/// it. Implementations: the real socket behind @c openAsyncDatagramSocket (readiness on POSIX, the +/// completion port on Windows), and the in-process network behind +/// `testing::InMemoryAsyncDatagramNetwork` (``). Both +/// run the same state machine, so the double cannot answer a state more permissively than the +/// real socket does. + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace core::net +{ + +class EventLoop; + +/// One received datagram, and who sent it. +struct AsyncDatagram +{ + std::vector payload; ///< The whole message, exactly as it arrived. + ResolvedEndpoint from; ///< The sender, as the kernel reports it. +}; + +/// A UDP socket whose sends and receives are coroutines on one @c EventLoop. +/// +/// **States.** A socket opens unbound. @c bind binds it; @c connect and @c send bind it to the +/// family's wildcard address first when it is not bound yet, so a socket that only sends still has +/// a port to be answered on. @c connect with a remote fixes the default destination and filters +/// what @c receive yields to that remote; @c connect with `std::nullopt` lifts both again. @c close +/// ends every state. +/// +/// **Refusals that never reach the OS** carry @c NetErrorCode::BadHandle with systemCode 0: any +/// call after @c close, @c receive or @c localEndpoint on an unbound socket, a second @c bind, +/// @c remoteEndpoint or a disconnect on an unconnected socket, a @c send with no destination on +/// an unconnected socket, and a second @c receive or a second @c send while one is in flight (a task +/// is in flight from the call until it is destroyed). An endpoint of the other family, or a @c send to an +/// address other than the connected remote, is @c NetErrorCode::AddressError with systemCode 0. +/// +/// **Cancellation.** A stop of the awaiting flow throws @c async::OperationCancelled; @c close +/// resolves a pending @c receive or @c send with @c NetErrorCode::Cancelled. A datagram that had +/// already been received when the stop arrived is returned, never dropped: the data wins. +/// +/// **Thread affinity.** Every call, and the destructor, on the loop's thread. +class IAsyncDatagramSocket +{ + public: + IAsyncDatagramSocket() = default; + virtual ~IAsyncDatagramSocket() = default; + IAsyncDatagramSocket(IAsyncDatagramSocket const&) = delete; + IAsyncDatagramSocket& operator=(IAsyncDatagramSocket const&) = delete; + IAsyncDatagramSocket(IAsyncDatagramSocket&&) = delete; + IAsyncDatagramSocket& operator=(IAsyncDatagramSocket&&) = delete; + + /// Binds the socket to @p local. Port 0 lets the kernel choose; @c localEndpoint reports it. + /// @param local The address and port to bind, of the socket's family. + /// @return Nothing, or why it could not bind. + [[nodiscard]] virtual std::expected bind(ResolvedEndpoint const& local) = 0; + + /// Connects the socket to @p remote, or disconnects it. + /// + /// A connected socket only receives from, and sends by default to, the remote. Connecting again + /// replaces the remote. An unbound socket is bound to the family's wildcard address first. + /// + /// A disconnect keeps the bound address and port. Linux takes a kernel-chosen port away at a + /// disconnect, so the socket binds it again; if another socket took it in between, the + /// disconnect still happened and answers @c NetErrorCode::AddressInUse. macOS and the BSDs reset + /// a named address to the wildcard at a disconnect, which nothing can bind back: such a socket is + /// closed, never left hearing every interface, and the disconnect answers + /// @c NetErrorCode::Unsupported. + /// @param remote The remote, or `std::nullopt` to disconnect. + /// @return Nothing, or why the kernel refused. + [[nodiscard]] virtual std::expected connect(std::optional remote) = 0; + + /// Waits for one datagram. + /// + /// **Whole or not at all.** A datagram longer than @p maxBytes is dropped and answered + /// @c NetErrorCode::MessageTooLarge, never handed back cut short; the next receive answers the + /// next datagram. + /// @param maxBytes The longest payload accepted, clamped to @c MaxIpv6DatagramPayload. + /// @return The datagram, or why none was returned. + [[nodiscard]] virtual async::Task> receive( + std::size_t maxBytes) = 0; + + /// Sends one datagram. + /// + /// A successful send means the local stack accepted the whole message, not that it arrived. A + /// send the stack places only part of is @c NetErrorCode::MessageTooLarge, never a partial + /// write: the rest resent would be a second message. An unbound socket is bound to the family's + /// wildcard address first, when this is called rather than when the task runs. + /// @param payload The whole message. + /// @param to The destination, or `std::nullopt` for the connected remote. On a connected socket + /// it must be the remote. + /// @return Nothing, or why the local stack refused it. + [[nodiscard]] virtual async::Task> send( + std::vector payload, std::optional to) = 0; + + /// @return The bound address and port, as the kernel reports them. + [[nodiscard]] virtual std::expected localEndpoint() const = 0; + + /// @return The connected remote, as the kernel reports it. + [[nodiscard]] virtual std::expected remoteEndpoint() const = 0; + + /// Reads one option. A datagram socket has the buffer sizes and the unicast hop limit; the + /// keep-alive options are @c NetErrorCode::Unsupported. + /// @param option The option. + /// @return Its value, in the caller's units (see @c SocketOptionRow). + [[nodiscard]] virtual std::expected option(SocketOption option) const = 0; + + /// Sets one option, clamped to the row's maximum as @c ITcpSocket::setOption does. + /// @param option The option. + /// @param value Its new value, in the caller's units. + /// @return Nothing, or why it was refused. + [[nodiscard]] virtual std::expected setOption(SocketOption option, + std::uint64_t value) = 0; + + /// Closes the socket. A pending @c receive or @c send resolves with @c NetErrorCode::Cancelled. + /// Idempotent; the destructor calls it. + virtual void close() noexcept = 0; +}; + +/// Opens an unbound UDP socket of @p family on @p loop. +/// +/// An IPv6 socket is IPv6-only on every platform, as an @c ITcpSocket is. On Windows the socket +/// ignores the ICMP port-unreachable a dead peer answers with (`SIO_UDP_CONNRESET` off), which would +/// otherwise fail the next receive of an unconnected socket. +/// @param loop The loop every send and receive runs on; must outlive the socket. +/// @param family The address family. +/// @return The socket, or why it could not be opened. +[[nodiscard]] CORE_NET_API std::expected, NetError> +openAsyncDatagramSocket(EventLoop& loop, AddressFamily family); + +} // namespace core::net diff --git a/src/core/net/TcpSocket_test.cpp b/src/core/net/TcpSocket_test.cpp index f45eaedd..cd75d733 100644 --- a/src/core/net/TcpSocket_test.cpp +++ b/src/core/net/TcpSocket_test.cpp @@ -130,14 +130,7 @@ void blockOnWithin(EventLoop& loop, Task task, std::chrono::milliseconds limit = std::chrono::seconds { 5 }) { - auto finished = false; - auto run = [](Task inner, bool* done) -> Task { - co_await std::move(inner); - *done = true; - }; - loop.blockOn(core::net::testing::anyOf(run(std::move(task), &finished), - core::net::testing::sleepFor(&loop, limit))); - if (!finished) + if (!core::net::testing::blockOnWithin(loop, std::move(task), limit)) FAIL("a socket wait in \"" << Catch::getResultCapture().getCurrentTestName() << "\" took longer than " << limit.count() << " ms"); } diff --git a/src/core/net/detail/DatagramChannel.hpp b/src/core/net/detail/DatagramChannel.hpp new file mode 100644 index 00000000..f89285d2 --- /dev/null +++ b/src/core/net/detail/DatagramChannel.hpp @@ -0,0 +1,114 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// `detail::IDatagramChannel` — the platform half of an @c IAsyncDatagramSocket, and the one place +/// its state machine is written. +/// +/// The socket (`AsyncDatagramSocket.cpp`) decides what a call means in each state: whether it is +/// refused, whether it binds the wildcard first, which destination a send takes. A channel only +/// does what it is told, on the OS (`posix/ReadinessDatagramSocket.cpp`, +/// `windows/IocpDatagramSocket.cpp`) or in memory (`testing/InMemoryAsyncDatagram.cpp`). Every +/// state decision is therefore made once, for the real socket and its double alike. + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace core::net::detail +{ + +/// What a datagram socket does on the OS, or in memory, once the socket has decided it may. +/// +/// **Shared, because a send or a receive outlives the socket that started it.** The task a caller +/// holds keeps its own share of the channel, so a socket destroyed while a receive is parked leaves +/// that frame something to read its outcome from. @c receive and @c send therefore take that share +/// when they are called, before the task first runs. +/// +/// No method here checks a state the socket owns (bound, connected, closed by the socket's own +/// @c close); each answers the OS's view, or for a closed channel @c NetErrorCode::Cancelled from a +/// pending operation. +class IDatagramChannel: public std::enable_shared_from_this +{ + public: + IDatagramChannel() = default; + virtual ~IDatagramChannel() = default; + IDatagramChannel(IDatagramChannel const&) = delete; + IDatagramChannel& operator=(IDatagramChannel const&) = delete; + IDatagramChannel(IDatagramChannel&&) = delete; + IDatagramChannel& operator=(IDatagramChannel&&) = delete; + + /// @param local The address to bind, already checked to be of the channel's family. + /// @return Nothing, or why it could not bind. + [[nodiscard]] virtual std::expected bind(ResolvedEndpoint const& local) = 0; + + /// @param remote The remote to connect to, or `std::nullopt` to disconnect. + /// @return Nothing, or why it was refused. + [[nodiscard]] virtual std::expected connect( + std::optional const& remote) = 0; + + /// @param side Which end. + /// @return That end's address. + [[nodiscard]] virtual std::expected endpoint(SocketSide side) const = 0; + + /// @param option One of the datagram options. + /// @return Its value. + [[nodiscard]] virtual std::expected option(SocketOption option) const = 0; + + /// @param option One of the datagram options. + /// @param value Its value. + /// @return Nothing, or why it was refused. + [[nodiscard]] virtual std::expected setOption(SocketOption option, + std::uint64_t value) = 0; + + /// @param maxBytes The longest payload accepted, already clamped. + /// @return One whole datagram; @c NetErrorCode::MessageTooLarge for a longer one, which is dropped. + [[nodiscard]] virtual async::Task> receive( + std::size_t maxBytes) = 0; + + /// @param payload The whole message. + /// @param to The destination, or `std::nullopt` for the connected remote. + /// @return Nothing, or why it was refused. + [[nodiscard]] virtual async::Task> send( + std::vector payload, std::optional to) = 0; + + /// Closes the channel; a pending receive or send resolves with @c NetErrorCode::Cancelled. + /// Idempotent. + virtual void close() noexcept = 0; +}; + +/// Opens the platform's channel: an unbound, non-blocking UDP socket on @p loop. +/// @param loop The loop to drive it on. +/// @param family The address family. +/// @return The channel, or why the socket could not be opened. +[[nodiscard]] std::expected, NetError> openDatagramChannel( + EventLoop& loop, AddressFamily family); + +/// Wraps @p channel in the one @c IAsyncDatagramSocket implementation. +/// @param channel The channel, unbound. +/// @param family The family it was opened with. +/// @return The socket; it closes the channel when it is closed or destroyed. +[[nodiscard]] std::unique_ptr makeAsyncDatagramSocket( + std::shared_ptr channel, AddressFamily family); + +/// The refusal of a pending operation whose channel was closed under it. +/// @param operation What was pending. +/// @return @c NetErrorCode::Cancelled, systemCode 0. +[[nodiscard]] inline NetError closedUnder(char const* operation) +{ + return makeNetError(NetErrorCode::Cancelled, 0, std::string { operation } + ": the socket was closed"); +} + +} // namespace core::net::detail diff --git a/src/core/net/detail/OperationClaim.hpp b/src/core/net/detail/OperationClaim.hpp new file mode 100644 index 00000000..9270430d --- /dev/null +++ b/src/core/net/detail/OperationClaim.hpp @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// `detail::OperationClaim` and `detail::holding` — how an object that allows one operation of a +/// kind in flight marks it taken, and gives it back when the task that carries it is gone. +/// +/// Shared by the loop-driven datagram socket (a receive and a send) and the standard streams (a +/// read, or a write), which refuse a second operation with `BadHandle` while the first is out. + +#include + +#include +#include + +namespace core::net::detail +{ + +/// One in-flight operation's hold on a predicate of @p State, given back when the task that +/// carries it is destroyed -- finished, or dropped before it ever ran. +/// +/// The state is shared rather than borrowed, because a task may outlive the object that handed +/// it out. +/// @tparam State The owner's record of what it has in flight. +template +class OperationClaim +{ + public: + /// @param state The owner's record. + /// @param slot Which of its predicates this claim holds; set here. + OperationClaim(std::shared_ptr state, bool State::* slot) noexcept: + _state { std::move(state) }, _slot { slot } + { + (*_state).*_slot = true; + } + + ~OperationClaim() + { + if (_state != nullptr) + (*_state).*_slot = false; + } + OperationClaim(OperationClaim const&) = delete; + OperationClaim& operator=(OperationClaim const&) = delete; + OperationClaim(OperationClaim&& other) noexcept: + _state { std::exchange(other._state, nullptr) }, _slot { other._slot } + { + } + OperationClaim& operator=(OperationClaim&&) = delete; + + private: + std::shared_ptr _state; + bool State::* _slot; +}; + +/// @tparam State The owner's record, as in @c OperationClaim. +/// @tparam T What @p task answers. +/// @param claim The operation's hold on its slot. +/// @param task The operation. +/// @return @p task, holding @p claim until it finishes. A coroutine parameter, so a task dropped +/// unstarted gives the claim back with its frame; moved into the body once it runs, so +/// a finished task gives it back at once rather than when its owner destroys it. +template +async::Task holding(OperationClaim claim, async::Task task) +{ + [[maybe_unused]] auto const held = std::move(claim); + co_return co_await std::move(task); +} + +} // namespace core::net::detail diff --git a/src/core/net/posix/ReadinessDatagramSocket.cpp b/src/core/net/posix/ReadinessDatagramSocket.cpp new file mode 100644 index 00000000..f5675eac --- /dev/null +++ b/src/core/net/posix/ReadinessDatagramSocket.cpp @@ -0,0 +1,232 @@ +// SPDX-License-Identifier: Apache-2.0 + +/// @file +/// The POSIX `detail::IDatagramChannel`: a non-blocking UDP socket that parks on the loop's +/// readiness (`EventLoop::waitReadable`/`waitWritable`) and then calls `recvmsg`/`sendto`. + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +namespace core::net::detail +{ + +namespace +{ + /// What `connect(AF_UNSPEC)` may answer although it did disconnect the socket. macOS documents + /// `EAFNOSUPPORT` as "harmlessly returned" and answers `EINVAL` for some families; Linux and the + /// other BSDs answer 0, so on them this row is never reached. + constexpr auto HarmlessDisconnectErrors = std::array { EAFNOSUPPORT, EINVAL }; + + /// A UDP socket driven by readiness. + /// + /// The descriptor is -1 once closed, which a parked flow reads on its way out: the close + /// announces itself to the loop (`notifyHandleClosing` with `FdWakePolicy::Resume`), so the + /// flow resumes on its normal path and finds the channel closed. That is safe because the flow + /// holds its own share of the channel, whoever destroyed the socket. + class ReadinessDatagramChannel final: public IDatagramChannel + { + public: + /// @param loop The loop to park on. + /// @param fd The open socket; owned from here. + /// @param family The family it was opened with, which picks the option rows. + ReadinessDatagramChannel(EventLoop& loop, int fd, AddressFamily family) noexcept: + _loop { loop }, _fd { fd }, _family { family } + { + } + + ~ReadinessDatagramChannel() override { close(); } + ReadinessDatagramChannel(ReadinessDatagramChannel const&) = delete; + ReadinessDatagramChannel& operator=(ReadinessDatagramChannel const&) = delete; + ReadinessDatagramChannel(ReadinessDatagramChannel&&) = delete; + ReadinessDatagramChannel& operator=(ReadinessDatagramChannel&&) = delete; + + [[nodiscard]] std::expected bind(ResolvedEndpoint const& local) override + { + if (::bind(_fd, addressOf(local), static_cast(local.length)) != 0) + return std::unexpected(socketError(errno, "bind")); + return {}; + } + + [[nodiscard]] std::expected connect( + std::optional const& remote) override + { + if (remote.has_value()) + { + if (::connect(_fd, addressOf(*remote), static_cast(remote->length)) != 0) + return std::unexpected(socketError(errno, "connect")); + return {}; + } + auto unspecified = sockaddr_storage {}; + unspecified.ss_family = AF_UNSPEC; + if (::connect(_fd, reinterpret_cast(&unspecified), sizeof(sockaddr)) != 0) + if (auto const error = errno; + std::ranges::find(HarmlessDisconnectErrors, error) == HarmlessDisconnectErrors.end()) + return std::unexpected(socketError(error, "connect(AF_UNSPEC)")); + return {}; + } + + [[nodiscard]] std::expected endpoint(SocketSide side) const override + { + return socketEndpoint(_fd, side); + } + + [[nodiscard]] std::expected option(SocketOption option) const override + { + return readSocketOption(_fd, _family, option); + } + + [[nodiscard]] std::expected setOption(SocketOption option, + std::uint64_t value) override + { + return writeSocketOption(_fd, _family, option, value); + } + + [[nodiscard]] async::Task> receive( + std::size_t maxBytes) override + { + return receiveOn(std::static_pointer_cast(shared_from_this()), + maxBytes); + } + + [[nodiscard]] async::Task> send( + std::vector payload, std::optional to) override + { + return sendOn(std::static_pointer_cast(shared_from_this()), + std::move(payload), + to); + } + + void close() noexcept override + { + if (_fd < 0) + return; + contract::assertTeardownIsSerialisedWithDispatch(_loop); + // Before the close, while the descriptor still names this socket: epoll and kqueue + // forget a closed descriptor silently, and a parked flow would never resume. + _loop.notifyHandleClosing(_fd, FdWakePolicy::Resume); + ::close(std::exchange(_fd, -1)); + } + + private: + /// @return @p endpoint's sockaddr. + [[nodiscard]] static sockaddr const* addressOf(ResolvedEndpoint const& endpoint) noexcept + { + return reinterpret_cast(endpoint.storage.data()); + } + + /// The receive: one `recvmsg` whenever the socket is readable, until one answers. + /// + /// `recvmsg` rather than `recvfrom` for `MSG_TRUNC` in `msg_flags`, which every POSIX + /// kernel sets when the datagram was longer than the buffer -- and has then dropped the + /// rest, so the datagram is answered as too large rather than handed back cut short. + static async::Task> receiveOn( + std::shared_ptr self, std::size_t maxBytes) + { + auto payload = std::vector(maxBytes); + while (true) + { + if (self->_fd < 0) + co_return std::unexpected(closedUnder("receive")); + auto from = sockaddr_storage {}; + auto vector = iovec { .iov_base = payload.data(), .iov_len = payload.size() }; + auto message = msghdr {}; + message.msg_name = &from; + message.msg_namelen = sizeof(from); + message.msg_iov = &vector; + message.msg_iovlen = 1; + auto const received = ::recvmsg(self->_fd, &message, 0); + if (received >= 0) + { + if ((message.msg_flags & MSG_TRUNC) != 0) + co_return std::unexpected( + makeNetError(NetErrorCode::MessageTooLarge, + 0, + "receive: the datagram is longer than maxBytes")); + payload.resize(static_cast(received)); + co_return AsyncDatagram { .payload = std::move(payload), + .from = endpointFromSockaddr(&from, message.msg_namelen) }; + } + if (auto const error = errno; !detail::isWouldBlock(error)) + co_return std::unexpected(socketError(error, "recvmsg")); + // The stop path: a cancelled flow throws out of this wait. Nothing was taken from + // the kernel yet, so a datagram that arrived meanwhile is the next receive's. + co_await self->_loop.waitReadable(self->_fd); + } + } + + /// The send: one `sendto` whenever the socket is writable, until one answers. + static async::Task> sendOn( + std::shared_ptr self, + std::vector payload, + std::optional to) + { + auto const* const address = to.has_value() ? addressOf(*to) : nullptr; + auto const length = to.has_value() ? static_cast(to->length) : socklen_t { 0 }; + while (true) + { + if (self->_fd < 0) + co_return std::unexpected(closedUnder("send")); + auto const sent = + ::sendto(self->_fd, payload.data(), payload.size(), MSG_NOSIGNAL, address, length); + if (sent >= 0) + { + // Not reachable on a POSIX kernel, which sends a datagram whole or fails it with + // EMSGSIZE, so no test can reach it; kept because the rule is that a partial + // datagram send is never retried -- the rest resent would be a second message. + if (static_cast(sent) != payload.size()) + co_return std::unexpected(makeNetError( + NetErrorCode::MessageTooLarge, 0, "sendto placed part of the datagram")); + co_return {}; + } + if (auto const error = errno; !detail::isWouldBlock(error)) + co_return std::unexpected(socketError(error, "sendto")); + co_await self->_loop.waitWritable(self->_fd); + } + } + + EventLoop& _loop; + int _fd; + AddressFamily _family; + }; +} // namespace + +std::expected, NetError> openDatagramChannel(EventLoop& loop, + AddressFamily family) +{ + auto const fd = makeDatagramSocket(family == AddressFamily::Ipv6 ? AF_INET6 : AF_INET, 0); + if (fd < 0) + return std::unexpected(socketError(errno, "socket")); + // From here the channel owns the descriptor, and closes it on every way out. + auto channel = std::make_shared(loop, fd, family); + if (!makeNonBlockingCloexec(fd)) + return std::unexpected(socketError(errno, "fcntl(O_NONBLOCK)")); + if (family == AddressFamily::Ipv6) + if (auto only = setIntOption(fd, NativeOption { .level = IPPROTO_IPV6, .name = IPV6_V6ONLY }, 1); + !only.has_value()) + return std::unexpected(std::move(only.error())); + return channel; +} + +} // namespace core::net::detail diff --git a/src/core/net/testing/CoroTestSupport.hpp b/src/core/net/testing/CoroTestSupport.hpp index f0207cc9..1988deb0 100644 --- a/src/core/net/testing/CoroTestSupport.hpp +++ b/src/core/net/testing/CoroTestSupport.hpp @@ -39,15 +39,37 @@ async::Task anyOf(Tasks... tasks) std::ignore = co_await async::whenAny(std::move(tasks)...); } -/// Polls @p ready one loop tick (1ms) at a time, bounded by @p maxTicks. +/// Runs @p task on @p loop and gives up once @p limit has passed, stopping the task then: what +/// bounds a test's kernel wait, so a socket that never becomes ready fails one case rather than +/// hanging the binary into its TIMEOUT. +/// @param loop The loop. +/// @param task The flow to run. +/// @param limit How long it may take. +/// @return Whether @p task finished within @p limit. +[[nodiscard]] inline bool blockOnWithin(EventLoop& loop, + async::Task task, + std::chrono::milliseconds limit) +{ + auto finished = false; + auto run = [](async::Task inner, bool* done) -> async::Task { + co_await std::move(inner); + *done = true; + }; + loop.blockOn(anyOf(run(std::move(task), &finished), sleepFor(&loop, limit))); + return finished; +} + +/// Polls @p ready about once a millisecond, bounded by @p maxMilliseconds of the loop's clock rather +/// than by a count of polls: a 1 ms delay lasts a timer tick, 15.6 ms on Windows, and a thousand of +/// them outlasted the bounds the callers run under. /// @return True when @p ready held before the budget ran out. template -async::Task waitUntil(EventLoop* loop, Predicate ready, int maxTicks = 1000) +async::Task waitUntil(EventLoop* loop, Predicate ready, int maxMilliseconds = 1000) { - auto ticks = 0; + auto const deadline = loop->clock().now() + std::chrono::milliseconds { maxMilliseconds }; while (!ready()) { - if (++ticks > maxTicks) + if (loop->clock().now() >= deadline) co_return false; co_await loop->delay(std::chrono::milliseconds { 1 }); } diff --git a/src/core/net/testing/InMemoryAsyncDatagram.cpp b/src/core/net/testing/InMemoryAsyncDatagram.cpp new file mode 100644 index 00000000..9e6d3c88 --- /dev/null +++ b/src/core/net/testing/InMemoryAsyncDatagram.cpp @@ -0,0 +1,297 @@ +// SPDX-License-Identifier: Apache-2.0 + +/// @file +/// `InMemoryAsyncDatagramNetwork`: an in-memory `detail::IDatagramChannel` per socket, behind the +/// real socket's state machine. + +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace core::net::testing +{ + +namespace +{ + class InMemoryChannel; + + /// The first port a bind to port 0 is given, and the range it cycles through: IANA's dynamic + /// ports. + constexpr std::uint16_t FirstEphemeralPort = 49152; + + /// @return Whether @p address is its family's wildcard. + [[nodiscard]] bool isWildcard(IpSocketAddress const& address) noexcept + { + return std::visit([](auto const& host) { return host == std::remove_cvref_t {}; }, + address.address); + } + + /// @return The largest payload one datagram of @p family carries. + [[nodiscard]] std::size_t largestPayload(AddressFamily family) noexcept + { + return family == AddressFamily::Ipv6 ? MaxIpv6DatagramPayload : MaxIpv4DatagramPayload; + } + + /// @return @p endpoint as an IP address; one the socket has already checked always is. + [[nodiscard]] IpSocketAddress ipOf(ResolvedEndpoint const& endpoint) + { + return toIpSocketAddress(endpoint).value_or(IpSocketAddress { .address = Ipv4Address {} }); + } +} // namespace + +/// Which sockets hold which address. Every field is guarded by @c mutex, and so is every bound +/// and connected address a channel holds, because a sender on another thread reads them. +struct InMemoryAsyncDatagramNetwork::State +{ + /// One bound socket. + struct Holder + { + InMemoryChannel* key = nullptr; ///< Who, for the socket's own delisting. + std::weak_ptr owner; ///< The channel, while anything holds it. + }; + + std::mutex mutex; + std::size_t inboxCapacity = DefaultInboxCapacity; + std::uint16_t nextPort = FirstEphemeralPort; + std::vector bound; +}; + +namespace +{ + using State = InMemoryAsyncDatagramNetwork::State; + + /// One socket on the network: a queue of datagrams that have reached it, and its addresses. + class InMemoryChannel final: public detail::IDatagramChannel + { + public: + /// @param network The network it lives on. + /// @param loop The loop a parked receive resumes on. + /// @param family Its family. + InMemoryChannel(std::shared_ptr network, EventLoop& loop, AddressFamily family): + _network { std::move(network) }, + _family { family }, + _inbox { loop, + async::AsyncQueueOptions { .capacity = _network->inboxCapacity, + .overflow = async::AsyncQueueOverflow::DropNewest } } + { + } + + ~InMemoryChannel() override { close(); } + InMemoryChannel(InMemoryChannel const&) = delete; + InMemoryChannel& operator=(InMemoryChannel const&) = delete; + InMemoryChannel(InMemoryChannel&&) = delete; + InMemoryChannel& operator=(InMemoryChannel&&) = delete; + + [[nodiscard]] std::expected bind(ResolvedEndpoint const& local) override + { + auto address = ipOf(local); + auto const lock = std::scoped_lock { _network->mutex }; + if (address.port == 0) + { + auto const port = freePort(address); + if (!port.has_value()) + return std::unexpected( + makeNetError(NetErrorCode::AddressInUse, 0, "bind: no ephemeral port is free")); + address.port = *port; + } + else if (!isFree(address)) + return std::unexpected( + makeNetError(NetErrorCode::AddressInUse, 0, "bind: the address is taken")); + _local = address; + _network->bound.push_back(State::Holder { + .key = this, .owner = std::static_pointer_cast(shared_from_this()) }); + return {}; + } + + [[nodiscard]] std::expected connect( + std::optional const& remote) override + { + auto const lock = std::scoped_lock { _network->mutex }; + _remote = remote.transform(ipOf); + return {}; + } + + [[nodiscard]] std::expected endpoint( + detail::SocketSide side) const override + { + auto const lock = std::scoped_lock { _network->mutex }; + auto const& address = side == detail::SocketSide::Local ? _local : _remote; + if (!address.has_value()) + return std::unexpected(makeNetError(NetErrorCode::BadHandle, 0, "the endpoint is not set")); + return toEndpoint(*address); + } + + [[nodiscard]] std::expected option(SocketOption) const override + { + return std::unexpected(unmodelled()); + } + + [[nodiscard]] std::expected setOption(SocketOption, std::uint64_t) override + { + return std::unexpected(unmodelled()); + } + + [[nodiscard]] async::Task> receive( + std::size_t maxBytes) override + { + return receiveOn(std::static_pointer_cast(shared_from_this()), maxBytes); + } + + [[nodiscard]] async::Task> send( + std::vector payload, std::optional to) override + { + return sendOn( + std::static_pointer_cast(shared_from_this()), std::move(payload), to); + } + + void close() noexcept override + { + _inbox.close(); + auto const lock = std::scoped_lock { _network->mutex }; + std::erase_if(_network->bound, + [this](State::Holder const& holder) { return holder.key == this; }); + } + + private: + /// @return The refusal of an option, which this double does not model. + [[nodiscard]] static NetError unmodelled() + { + return makeNetError( + NetErrorCode::Unsupported, 0, "InMemoryAsyncDatagramNetwork does not model socket options"); + } + + /// @return Whether a socket may bind @p address. The network's mutex is held. + [[nodiscard]] bool isFree(IpSocketAddress const& address) const + { + return std::ranges::none_of(_network->bound, [&](State::Holder const& holder) { + auto const other = holder.owner.lock(); + if (other == nullptr || !other->_local.has_value()) + return false; + auto const& held = *other->_local; + return held.family() == address.family() && held.port == address.port + && (held.address == address.address || isWildcard(held) || isWildcard(address)); + }); + } + + /// @return A port @p address is free at, or nothing when every dynamic port is taken. The + /// network's mutex is held. + [[nodiscard]] std::optional freePort(IpSocketAddress address) const + { + constexpr auto EphemeralPortCount = 65536U - FirstEphemeralPort; + for ([[maybe_unused]] auto const attempt: std::views::iota(0U, EphemeralPortCount)) + { + address.port = _network->nextPort; + _network->nextPort = _network->nextPort == 65535 + ? FirstEphemeralPort + : static_cast(_network->nextPort + 1); + if (isFree(address)) + return address.port; + } + return std::nullopt; + } + + /// @return The socket @p destination reaches: the one bound to it exactly, else the one bound + /// to the wildcard at its port. The network's mutex is held. + [[nodiscard]] std::shared_ptr receiverOf(IpSocketAddress const& destination) const + { + auto wildcard = std::shared_ptr {}; + for (auto const& holder: _network->bound) + { + auto other = holder.owner.lock(); + if (other == nullptr || !other->_local.has_value()) + continue; + auto const& held = *other->_local; + if (held.family() != destination.family() || held.port != destination.port) + continue; + if (held.address == destination.address) + return other; + if (isWildcard(held)) + wildcard = std::move(other); + } + return wildcard; + } + + static async::Task> receiveOn( + std::shared_ptr self, std::size_t maxBytes) + { + auto datagram = co_await self->_inbox.pop(); + if (!datagram.has_value()) + co_return std::unexpected(detail::closedUnder("receive")); + if (datagram->payload.size() > maxBytes) + co_return std::unexpected(makeNetError( + NetErrorCode::MessageTooLarge, 0, "receive: the datagram is longer than maxBytes")); + co_return std::move(*datagram); + } + + static async::Task> sendOn(std::shared_ptr self, + std::vector payload, + std::optional to) + { + if (payload.size() > largestPayload(self->_family)) + co_return std::unexpected( + makeNetError(NetErrorCode::MessageTooLarge, + 0, + "send: the payload is longer than the family's largest datagram")); + + auto receiver = std::shared_ptr {}; + auto from = IpSocketAddress { .address = Ipv4Address {} }; + { + auto const lock = std::scoped_lock { self->_network->mutex }; + if (!self->_local.has_value()) + co_return std::unexpected(detail::closedUnder("send")); + auto const destination = to.has_value() ? ipOf(*to) : self->_remote.value_or(*self->_local); + from = *self->_local; + // What a loopback route picks for a sender bound to the wildcard. + if (isWildcard(from)) + from.address = destination.address; + receiver = self->receiverOf(destination); + // A connected receiver hears its remote alone. + if (receiver != nullptr && receiver->_remote.has_value() && *receiver->_remote != from) + receiver.reset(); + } + // Outside the network's lock, for `AsyncQueue::push`'s reason: it posts the woken + // receiver to its executor, whose own lock must never nest inside a producer's. + if (receiver != nullptr) + std::ignore = receiver->_inbox.push( + AsyncDatagram { .payload = std::move(payload), .from = toEndpoint(from) }); + co_return {}; + } + + std::shared_ptr _network; + AddressFamily _family; + std::optional _local; ///< Guarded by the network's mutex. + std::optional _remote; ///< Guarded by the network's mutex. + async::AsyncQueue _inbox; + }; +} // namespace + +InMemoryAsyncDatagramNetwork::InMemoryAsyncDatagramNetwork(std::size_t inboxCapacity): + _state { std::make_shared() } +{ + _state->inboxCapacity = inboxCapacity; +} + +InMemoryAsyncDatagramNetwork::~InMemoryAsyncDatagramNetwork() = default; + +std::expected, NetError> InMemoryAsyncDatagramNetwork::open( + EventLoop& loop, AddressFamily family) +{ + return detail::makeAsyncDatagramSocket(std::make_shared(_state, loop, family), family); +} + +} // namespace core::net::testing diff --git a/src/core/net/testing/InMemoryAsyncDatagram.hpp b/src/core/net/testing/InMemoryAsyncDatagram.hpp new file mode 100644 index 00000000..d637615a --- /dev/null +++ b/src/core/net/testing/InMemoryAsyncDatagram.hpp @@ -0,0 +1,75 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// `InMemoryAsyncDatagramNetwork` — UDP between @c IAsyncDatagramSocket s in one process, for a +/// consumer that tests a datagram protocol without the kernel. + +#include +#include +#include +#include + +#include +#include +#include + +namespace core::net::testing +{ + +/// A network of in-memory datagram sockets. +/// +/// **The state machine is the real socket's.** Every socket this opens runs the same +/// @c IAsyncDatagramSocket implementation as @c openAsyncDatagramSocket, over an in-memory channel, +/// so each refusal (closed, unbound, unconnected, wrong family) is answered exactly as the real one +/// answers it. What differs is only what the kernel would do: +/// +/// - **Addresses.** A bind to port 0 takes the next free port from 49152 up. Two sockets of one +/// family may not hold the same port when their addresses are equal or either is the wildcard +/// (@c NetErrorCode::AddressInUse). A datagram is delivered to the socket bound to its exact +/// destination, else to the one bound to the wildcard on that port. +/// - **Senders.** `from` is the sender's bound address, or, when the sender bound the wildcard, +/// the destination's address at the sender's port: what a loopback route picks. +/// - **Loss.** A datagram to nobody, from someone a connected receiver does not accept, or to a +/// receiver whose queue holds @c inboxCapacity datagrams already, is dropped and the send still +/// succeeds, as UDP's does. +/// - **Sizes.** A payload above the family's largest (@c MaxIpv4DatagramPayload, +/// @c MaxIpv6DatagramPayload) is @c NetErrorCode::MessageTooLarge at the send. +/// +/// **What it does not model, and what that produces.** Options: every @c option and @c setOption is +/// @c NetErrorCode::Unsupported (a refusal, never a false pass). ICMP: a send to a dead port is +/// silent, as an unconnected real socket's is. Several loops: a send delivers through the +/// receiving socket's loop, so sockets on different threads work, but one socket still belongs to +/// one loop. +/// +/// The network may be destroyed before its sockets; they keep what they need. +class CORE_NET_API InMemoryAsyncDatagramNetwork +{ + public: + /// The queue depth a receiver holds when the caller names none. + static constexpr std::size_t DefaultInboxCapacity = 64; + + /// @param inboxCapacity How many datagrams one socket queues before it drops the newest. + explicit InMemoryAsyncDatagramNetwork(std::size_t inboxCapacity = DefaultInboxCapacity); + ~InMemoryAsyncDatagramNetwork(); + InMemoryAsyncDatagramNetwork(InMemoryAsyncDatagramNetwork const&) = delete; + InMemoryAsyncDatagramNetwork& operator=(InMemoryAsyncDatagramNetwork const&) = delete; + InMemoryAsyncDatagramNetwork(InMemoryAsyncDatagramNetwork&&) = delete; + InMemoryAsyncDatagramNetwork& operator=(InMemoryAsyncDatagramNetwork&&) = delete; + + /// Opens an unbound socket on this network. + /// @param loop The loop its receives resume on; must outlive the socket. + /// @param family The address family. + /// @return The socket. Never fails today; the result type is @c openAsyncDatagramSocket 's, so + /// a consumer can inject either. + [[nodiscard]] std::expected, NetError> open(EventLoop& loop, + AddressFamily family); + + /// The network's shared state; opaque, and public only so the implementation can name it. + struct State; + + private: + std::shared_ptr _state; +}; + +} // namespace core::net::testing diff --git a/src/core/net/windows/IocpDatagramSocket.cpp b/src/core/net/windows/IocpDatagramSocket.cpp new file mode 100644 index 00000000..05b7db3c --- /dev/null +++ b/src/core/net/windows/IocpDatagramSocket.cpp @@ -0,0 +1,379 @@ +// SPDX-License-Identifier: Apache-2.0 + +/// @file +/// The Windows `detail::IDatagramChannel`: an overlapped UDP socket on the loop's completion port, +/// whose receives and sends are `WSARecvFrom` and `WSASendTo` waited for through +/// `detail::CompletionWait`. + +// winsock2.h MUST precede windows.h / ws2tcpip.h (which project headers pull in), so this block +// leads every Win32 net translation unit. +// clang-format off +#include +#include +#include +#include +// clang-format on + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace core::net::detail +{ + +namespace +{ + /// One outstanding `WSARecvFrom` or `WSASendTo`, and everything the kernel writes into or reads + /// from until it completes: the payload, and for a receive the sender's address and its length. + /// + /// **It holds itself while the kernel holds it** (@c self), and the port gives that share back + /// when the packet is dequeued, so neither the channel nor the waiting frame has to outlive the + /// kernel's use of it ([fastcached#465](https://github.com/LASTRADA-Software/fastcached/issues/465)). + struct DatagramOperation: IocpOperation + { + std::vector payload; ///< Received into, or sent from. + sockaddr_storage from {}; ///< A receive's sender. + INT fromLength = static_cast(sizeof(sockaddr_storage)); ///< Its length, in and out. + DWORD flags = 0; ///< A receive's flags, in and out. + std::optional to; ///< A send's destination. + std::shared_ptr self; + + /// @param operation This operation. + static void released(IocpOperation& operation) noexcept + { + auto const keep = std::move(static_cast(operation).self); + } + }; + + /// @return Whether @p error, from an issued `WSARecvFrom`, is a datagram longer than the buffer. + /// + /// Answered at once as @c NetErrorCode::MessageTooLarge, never waited for: the kernel's status + /// is the warning `STATUS_BUFFER_OVERFLOW`, for which the I/O manager may or may not still queue + /// a packet, and a wait for one that never comes would park the receive for ever. The operation + /// is therefore left announced and holding itself, rather than withdrawn: a late packet is then + /// recognised and frees it through `onDequeued`, and none costs only the port's drain diagnostic. + [[nodiscard]] constexpr bool isTruncation(int error) noexcept + { + return error == WSAEMSGSIZE || error == ERROR_MORE_DATA; + } + + /// A UDP socket on a completion port. + class IocpDatagramChannel final: public IDatagramChannel + { + public: + /// @param loop The loop whose port completes this socket's operations. + /// @param socket The open overlapped socket; owned from here. + /// @param family The family it was opened with. + IocpDatagramChannel(EventLoop& loop, SOCKET socket, AddressFamily family) noexcept: + _loop { loop }, _port { loop.completionPort() }, _socket { socket }, _family { family } + { + } + + ~IocpDatagramChannel() override { close(); } + IocpDatagramChannel(IocpDatagramChannel const&) = delete; + IocpDatagramChannel& operator=(IocpDatagramChannel const&) = delete; + IocpDatagramChannel(IocpDatagramChannel&&) = delete; + IocpDatagramChannel& operator=(IocpDatagramChannel&&) = delete; + + /// Associates the socket with the loop's port and turns off what an unconnected UDP socket + /// must not do on Windows: fail its next receive with `WSAECONNRESET` because an earlier + /// send drew an ICMP port-unreachable. + /// @return Nothing, or why the socket cannot be served. + [[nodiscard]] std::expected prepare() + { + if (_family == AddressFamily::Ipv6) + if (auto only = setIntOption( + handle(), NativeOption { .level = IPPROTO_IPV6, .name = IPV6_V6ONLY }, 1); + !only.has_value()) + return std::unexpected(std::move(only.error())); + auto reportReset = BOOL { FALSE }; + auto returned = DWORD { 0 }; + if (::WSAIoctl(_socket, + SIO_UDP_CONNRESET, + &reportReset, + sizeof(reportReset), + nullptr, + 0, + &returned, + nullptr, + nullptr) + == SOCKET_ERROR) + return std::unexpected(fromWinsockError(::WSAGetLastError(), "WSAIoctl(SIO_UDP_CONNRESET)")); + return _port->associate(handle()).transform([this] { _isAssociated = true; }); + } + + [[nodiscard]] std::expected bind(ResolvedEndpoint const& local) override + { + if (::bind(_socket, addressOf(local), static_cast(local.length)) != 0) + return std::unexpected(fromWinsockError(::WSAGetLastError(), "bind")); + return {}; + } + + [[nodiscard]] std::expected connect( + std::optional const& remote) override + { + if (remote.has_value()) + return connectTo(*remote); + // An all-zero address of the socket's family is Winsock's documented disconnect. Not + // `AF_UNSPEC`, which libuv sends: wine hands that to Linux, which then takes the + // kernel-chosen port away while wine still refuses the bind that would restore it. + auto zero = ResolvedEndpoint {}; + zero.length = static_cast(_family == AddressFamily::Ipv6 ? sizeof(sockaddr_in6) + : sizeof(sockaddr_in)); + reinterpret_cast(zero.storage.data())->sa_family = + static_cast(_family == AddressFamily::Ipv6 ? AF_INET6 : AF_INET); + return connectTo(zero); + } + + [[nodiscard]] std::expected endpoint(SocketSide side) const override + { + return socketEndpoint(handle(), side); + } + + [[nodiscard]] std::expected option(SocketOption option) const override + { + return readSocketOption(handle(), _family, option); + } + + [[nodiscard]] std::expected setOption(SocketOption option, + std::uint64_t value) override + { + return writeSocketOption(handle(), _family, option, value); + } + + [[nodiscard]] async::Task> receive( + std::size_t maxBytes) override + { + return receiveOn(std::static_pointer_cast(shared_from_this()), maxBytes); + } + + [[nodiscard]] async::Task> send( + std::vector payload, std::optional to) override + { + return sendOn( + std::static_pointer_cast(shared_from_this()), std::move(payload), to); + } + + void close() noexcept override + { + if (_socket == InvalidSocket) + return; + contract::assertTeardownIsSerialisedWithDispatch(_loop); + // Taken first: a wait resolved below may resume a flow that ends this channel's life. + auto const waits = std::exchange(_waits, {}); + if (_isAssociated) + _port->forget(handle()); + // What aborts every operation still outstanding; each completes later into its own share. + ::closesocket(std::exchange(_socket, InvalidSocket)); + for (auto* const wait: waits) + wait->close(); + } + + private: + /// @return The socket as the platform's handle. + [[nodiscard]] platform::NativeHandle handle() const noexcept + { + return reinterpret_cast(_socket); + } + + /// @return @p endpoint's sockaddr. + [[nodiscard]] static sockaddr const* addressOf(ResolvedEndpoint const& endpoint) noexcept + { + return reinterpret_cast(endpoint.storage.data()); + } + + /// @return Nothing, or why `connect` to @p remote was refused. + [[nodiscard]] std::expected connectTo(ResolvedEndpoint const& remote) const + { + if (::connect(_socket, addressOf(remote), static_cast(remote.length)) != 0) + return std::unexpected(fromWinsockError(::WSAGetLastError(), "connect")); + return {}; + } + + /// @return A fresh operation over @p payload, announced to the port and holding itself. + [[nodiscard]] std::shared_ptr begin(std::vector payload) + { + auto operation = std::make_shared(); + operation->payload = std::move(payload); + operation->onDequeued = &DatagramOperation::released; + // Announced BEFORE the call: the packet can be queued the instant it is issued. + _port->beginOperation(static_cast(operation.get())); + operation->self = operation; + return operation; + } + + /// Takes back an operation the kernel refused outright, which no packet will name. + void withdraw(DatagramOperation& operation) noexcept + { + _port->withdrawOperation(static_cast(&operation)); + operation.self.reset(); + } + + /// Waits for @p operation's completion and says what it did. + /// + /// The completion is the single writer of the outcome: a stop asks the kernel for the + /// operation back and goes on waiting, so a receive that completed with a datagram first is + /// still returned. Only an abort the stop caused unwinds the flow. + /// @return The bytes transferred. + /// @throws async::OperationCancelled where the flow's stop took the operation back. + static async::Task> completionOf( + std::shared_ptr self, + std::shared_ptr operation, + char const* what) + { + auto wait = CompletionWait { self->_loop, *operation, self->_socket }; + self->_waits.push_back(&wait); + // Delisted however the frame leaves, so a later close never reaches a wait that is gone. + auto const listed = ScopeGuard { [&self, &wait]() noexcept { std::erase(self->_waits, &wait); } }; + co_await wait; + + switch (wait.outcome()) + { + case CompletionWait::Outcome::Completed: break; + case CompletionWait::Outcome::Closed: co_return std::unexpected(closedUnder(what)); + case CompletionWait::Outcome::Refused: + co_return std::unexpected(makeNetError( + NetErrorCode::SystemError, 0, std::string { what } + ": the loop refused the park")); + case CompletionWait::Outcome::Pending: + case CompletionWait::Outcome::Abandoned: throw async::OperationCancelled {}; + } + auto const error = completionError(self->_socket, *operation); + if (error == 0) + co_return operation->bytesTransferred(); + if (isAbort(error)) + { + if (wait.stopped()) + throw async::OperationCancelled {}; + co_return std::unexpected(closedUnder(what)); + } + co_return std::unexpected(fromWinsockError(static_cast(error), what)); + } + + static async::Task> receiveOn( + std::shared_ptr self, std::size_t maxBytes) + { + if (self->_socket == InvalidSocket) + co_return std::unexpected(closedUnder("receive")); + auto const operation = self->begin(std::vector(maxBytes)); + auto buffer = WSABUF { .len = static_cast(operation->payload.size()), + .buf = reinterpret_cast(operation->payload.data()) }; + auto error = 0; + if (::WSARecvFrom(self->_socket, + &buffer, + 1, + nullptr, + &operation->flags, + reinterpret_cast(&operation->from), + &operation->fromLength, + reinterpret_cast(&operation->overlapped), + nullptr) + == SOCKET_ERROR) + error = ::WSAGetLastError(); + if (isTruncation(error)) + co_return std::unexpected(makeNetError(NetErrorCode::MessageTooLarge, + error, + "WSARecvFrom: the datagram is longer than maxBytes")); + if (error != 0 && error != WSA_IO_PENDING) + { + self->withdraw(*operation); + co_return std::unexpected(fromWinsockError(error, "WSARecvFrom")); + } + + auto transferred = co_await completionOf(self, operation, "WSARecvFrom"); + if (!transferred.has_value()) + co_return std::unexpected(std::move(transferred.error())); + operation->payload.resize(*transferred); + co_return AsyncDatagram { + .payload = std::move(operation->payload), + .from = + endpointFromSockaddr(&operation->from, static_cast(operation->fromLength)), + }; + } + + static async::Task> sendOn(std::shared_ptr self, + std::vector payload, + std::optional to) + { + if (self->_socket == InvalidSocket) + co_return std::unexpected(closedUnder("send")); + auto const size = payload.size(); + auto const operation = self->begin(std::move(payload)); + operation->to = to; + auto buffer = WSABUF { .len = static_cast(operation->payload.size()), + .buf = reinterpret_cast(operation->payload.data()) }; + auto error = 0; + if (::WSASendTo(self->_socket, + &buffer, + 1, + nullptr, + 0, + operation->to.has_value() ? addressOf(*operation->to) : nullptr, + operation->to.has_value() ? static_cast(operation->to->length) : 0, + reinterpret_cast(&operation->overlapped), + nullptr) + == SOCKET_ERROR) + error = ::WSAGetLastError(); + if (error != 0 && error != WSA_IO_PENDING) + { + self->withdraw(*operation); + co_return std::unexpected(fromWinsockError(error, "WSASendTo")); + } + + auto transferred = co_await completionOf(self, operation, "WSASendTo"); + if (!transferred.has_value()) + co_return std::unexpected(std::move(transferred.error())); + // Not reachable through Winsock, which places a datagram whole or fails it with + // WSAEMSGSIZE; kept because the rule is that a partial datagram send is never retried. + if (*transferred != size) + co_return std::unexpected( + makeNetError(NetErrorCode::MessageTooLarge, 0, "WSASendTo placed part of the datagram")); + co_return {}; + } + + EventLoop& _loop; + ICompletionPort* _port; + SOCKET _socket; + AddressFamily _family; + bool _isAssociated = false; + std::vector _waits; ///< Every operation parked right now, for @c close. + }; +} // namespace + +std::expected, NetError> openDatagramChannel(EventLoop& loop, + AddressFamily family) +{ + platform::ensureWinsockInitialized(); + auto const socket = ::WSASocketW(family == AddressFamily::Ipv6 ? AF_INET6 : AF_INET, + SOCK_DGRAM, + IPPROTO_UDP, + nullptr, + 0, + WSA_FLAG_OVERLAPPED | WSA_FLAG_NO_HANDLE_INHERIT); + if (socket == InvalidSocket) + return std::unexpected(fromWinsockError(::WSAGetLastError(), "socket")); + // From here the channel owns the socket, and closes it on every way out. + auto channel = std::make_shared(loop, socket, family); + return channel->prepare().transform( + [&] { return std::shared_ptr { std::move(channel) }; }); +} + +} // namespace core::net::detail diff --git a/src/core/net/windows/IocpOperation.hpp b/src/core/net/windows/IocpOperation.hpp index a27383e6..256d6220 100644 --- a/src/core/net/windows/IocpOperation.hpp +++ b/src/core/net/windows/IocpOperation.hpp @@ -210,10 +210,16 @@ class CompletionWait /// Retires the park if the frame is going away while it is still registered — a flow /// destroyed mid-wait. The operation outlives this on its own share. + /// + /// An operation still in the kernel is asked back too: nobody will read what it completes + /// with, and an orphaned receive left posted would take the next datagram on its socket into + /// storage nobody reads. ~CompletionWait() { _cancelReg.reset(); _timer.reset(); + if (_outcome == Outcome::Pending && !_operation.completed) + std::ignore = ::CancelIoEx(reinterpret_cast(_socket), &_operation.overlapped); if (_park) _loop.unregisterPark(std::exchange(_park, ParkId {})); // Finished and handed to the loop, and the frame is going away before the loop resumed From c16571c9805bc1a2dcc8d05b510a9d7da8538f6a Mon Sep 17 00:00:00 2001 From: Christian Parpart Date: Thu, 26 Nov 2026 23:16:32 +0100 Subject: [PATCH 08/19] feat(net): standard streams, pollable where the OS allows and offloaded otherwise openStandardStreams(loop, blocking, handles, maxReadChunk) builds an IInputStream and two IOutputStreams over a process's standard handles (processStandardHandles) or any others. classifyStreamHandle sorts a handle by fstat type or GetFileType, one table per platform: - A POSIX pipe, socket or terminal is Pollable: the input waits with waitReadable, confirms with a zero-timeout poll, and reads. No descriptor's O_NONBLOCK is set or cleared, because it is shared with the parent; a non-blocking one inherited as such still works. - A regular file, /dev/null, every Windows handle, and an input whose registration the backend refuses (macOS kqueue, some ttys) are Blocking: the read runs on the blocking executor through a detail::ParkedCall worker. A stop throws at once; the worker stays the stream's one outstanding read, the next read waits for it, and its bytes are kept, beyond maxBytes included. On Windows the stop also sends CancelSynchronousIo to the worker thread. Output always goes through async::offload, in order. A write to a pipe nobody reads answers SystemError (EPIPE): SIGPIPE is blocked on the writing thread and consumed. One read and one write in flight; a second answers BadHandle with systemCode 0. Also in this commit: - a stop that reaches a queued stdin worker keeps it from reading - no SIGPIPE from a standard-stream write on macOS - set a description's F_SETNOSIGPIPE once and leave it set Signed-off-by: Christian Parpart --- .agent/reference/provenance.md | 12 + .agent/rules/async-and-net.md | 20 + docs/modules/net.md | 1 + src/core/net/CMakeLists.txt | 12 + src/core/net/StandardStreams.cpp | 497 +++++++++++++ src/core/net/StandardStreams.hpp | 207 ++++++ src/core/net/StandardStreamsTestSupport.hpp | 94 +++ src/core/net/StandardStreams_test.cpp | 680 ++++++++++++++++++ .../net/detail/StandardStreamPrimitives.hpp | 97 +++ .../net/posix/StandardStreamPrimitives.cpp | 216 ++++++ .../net/posix/StandardStreamsTestSupport.cpp | 67 ++ src/core/net/posix/StandardStreams_test.cpp | 457 ++++++++++++ src/core/net/posix/StreamKindTable.cpp | 63 ++ .../net/windows/StandardStreamPrimitives.cpp | 132 ++++ .../windows/StandardStreamsTestSupport.cpp | 73 ++ src/core/net/windows/StreamKindTable.cpp | 49 ++ 16 files changed, 2677 insertions(+) create mode 100644 src/core/net/StandardStreams.cpp create mode 100644 src/core/net/StandardStreams.hpp create mode 100644 src/core/net/StandardStreamsTestSupport.hpp create mode 100644 src/core/net/StandardStreams_test.cpp create mode 100644 src/core/net/detail/StandardStreamPrimitives.hpp create mode 100644 src/core/net/posix/StandardStreamPrimitives.cpp create mode 100644 src/core/net/posix/StandardStreamsTestSupport.cpp create mode 100644 src/core/net/posix/StandardStreams_test.cpp create mode 100644 src/core/net/posix/StreamKindTable.cpp create mode 100644 src/core/net/windows/StandardStreamPrimitives.cpp create mode 100644 src/core/net/windows/StandardStreamsTestSupport.cpp create mode 100644 src/core/net/windows/StreamKindTable.cpp diff --git a/.agent/reference/provenance.md b/.agent/reference/provenance.md index b71c07e0..4b94e388 100644 --- a/.agent/reference/provenance.md +++ b/.agent/reference/provenance.md @@ -298,6 +298,18 @@ others in notes. | `src/core/net/testing/InMemoryAsyncDatagram.hpp` | origin: core-cpp | - | - | P13 Task 10: an in-memory network behind the real socket's state machine | | `src/core/net/testing/InMemoryAsyncDatagram.cpp` | origin: core-cpp | - | - | P13 Task 10 | | `src/core/net/detail/OperationClaim.hpp` | origin: core-cpp | - | - | P13 Task 11: the one-operation-in-flight claim, moved out of `AsyncDatagramSocket.cpp` (Task 10) to be shared with the standard streams | +| `src/core/net/StandardStreams.hpp` | origin: core-cpp | - | - | P13 Task 11: the standard streams as coroutines, `classifyStreamHandle`, `openStandardStreams` | +| `src/core/net/StandardStreams.cpp` | origin: core-cpp | - | - | P13 Task 11: the input (Pollable through the loop, Blocking through a `detail::ParkedCall` worker, P13 ruling R13) and the offloaded output | +| `src/core/net/detail/StandardStreamPrimitives.hpp` | origin: core-cpp | - | - | P13 Task 11: the platform half of the standard streams, defined per platform | +| `src/core/net/posix/StandardStreamPrimitives.cpp` | origin: core-cpp | - | - | P13 Task 11: `read`, `write` with `SIGPIPE` held off the writing thread, a zero-timeout `poll` | +| `src/core/net/posix/StreamKindTable.cpp` | origin: core-cpp | - | - | P13 Task 11: `fstat` type to stream kind; a character device is Pollable only as a terminal (P13 ruling R14) | +| `src/core/net/windows/StandardStreamPrimitives.cpp` | origin: core-cpp | - | - | P13 Task 11: synchronous `ReadFile`/`WriteFile`, `CancelSynchronousIo` on a stop | +| `src/core/net/windows/StreamKindTable.cpp` | origin: core-cpp | - | - | P13 Task 11: `GetFileType` to stream kind; every row Blocking, each with its reason | +| `src/core/net/StandardStreams_test.cpp` | origin: core-cpp | - | - | P13 Task 11 | +| `src/core/net/StandardStreamsTestSupport.hpp` | origin: core-cpp | - | - | P13 Task 11: the pipes, files and null device the cases make for themselves | +| `src/core/net/posix/StandardStreams_test.cpp` | origin: core-cpp | - | - | P13 Task 11: pipes, sockets and pseudo-terminals through the loop | +| `src/core/net/posix/StandardStreamsTestSupport.cpp` | origin: core-cpp | - | - | P13 Task 11 | +| `src/core/net/windows/StandardStreamsTestSupport.cpp` | origin: core-cpp | - | - | P13 Task 11 | | `src/core/net/linux/AcceptedSocketOptions_test.cpp` | origin: core-cpp | - | - | P13 Task 9 fix round 1: what a Linux listener's accepted connections inherit | | `src/core/net/HostDrivenBackend.cpp` | origin: core-cpp | - | - | its body: the coalescing (several wakes before the host gets a turn are one pump), the clamp of a deadline already past to a zero delay, and the schedule cleared BEFORE a pump runs so the turn it drives can arm the next one | | `src/core/net/HostDrivenBackend.hpp` | origin: core-cpp | - | - | Task B3: the IoBackend for a loop that is PUMPED rather than one that blocks. Portable, and tested on every platform over testing::ManualHostScheduler -- the browser is one of its hosts, not its definition | diff --git a/.agent/rules/async-and-net.md b/.agent/rules/async-and-net.md index 464752b9..a637a112 100644 --- a/.agent/rules/async-and-net.md +++ b/.agent/rules/async-and-net.md @@ -1367,6 +1367,26 @@ in-process doubles (`testing::DatagramBus`, `testing::InMemorySocket`, the parki `WSARecvFrom` is answered `MessageTooLarge` at once, never waited for, and the operation is left announced and holding itself, so a packet that may or may not follow frees it. The rebind after a Linux disconnect takes the address `bind` was given, not `getsockname`'s connected source. +- **A standard handle's flags are the parent's, so the standard streams never set one** (P13 Task + 11). `O_NONBLOCK` lives on the open file description an inherited descriptor shares with its + parent, and a shell whose stdin turned non-blocking under it reads `EAGAIN` as end of input. A + Pollable input (`classifyStreamHandle`: a pipe, a socket, a terminal) therefore waits on the loop + and then asks a zero-timeout `poll` before it reads, so a spurious readiness never blocks the + loop's thread on a blocking descriptor. A regular file and `/dev/null` are never Pollable, because + epoll refuses both (`EPERM`); a registration the backend refuses anyway (macOS kqueue, some ttys) + turns the stream Blocking for good. No Windows handle is Pollable: a console cannot join a + completion port, and an inherited pipe is not overlapped. +- **A blocking stdin read is a `detail::ParkedCall`, not `async::offload`** (P13 ruling R13): + `offload` never resumes before its work returns, and a read of a terminal may never return. A stop + hands the waiter back at once; the worker read stays the stream's ONE outstanding read, the next + read waits for that same worker (swapping in a fresh call under the worker's mutex), and what it + read is the next read's -- bytes beyond the next read's `maxBytes` are kept, never dropped. On + Windows the stop also sends `CancelSynchronousIo` to the worker's thread, recorded and forgotten + under that mutex so it can never reach the pool thread's next job. +- **A write to a pipe nobody reads is an error, not a signal.** There is no `MSG_NOSIGNAL` for a + pipe and no descriptor flag a child may set, so the standard output blocks `SIGPIPE` on the + writing thread for the write and consumes one the write raised (`sigwait`, since macOS lacks + `sigtimedwait`) before the mask returns. - **Sharing a port buys hearing a broadcast, and nothing else.** A unicast to a shared port reaches one socket, and which one differs by platform, so a node that shares a port to hear the segment sends -- and is answered -- from an address only it holds (`answerFromOwnAddress`, diff --git a/docs/modules/net.md b/docs/modules/net.md index 19ccf0ca..f75def5e 100644 --- a/docs/modules/net.md +++ b/docs/modules/net.md @@ -57,6 +57,7 @@ directory `src/core/net/`. Three targets: | ``, `` | `IDatagramSocket` (`send`, a bounded `receive`, `close`, `boundAddress`), `DatagramAddress`, `ReceivedDatagram`, `DatagramWait`; `openUdpSocket()` with `BroadcastMode` and `PortSharing`, answering WHY a bind failed. Blocking, on a thread of its own: a datagram socket is not an `ISocket` | | `` | `IAsyncDatagramSocket` (`bind`, `connect` with a remote or `std::nullopt`, coroutine `receive(maxBytes)` and `send(payload, to)`, `localEndpoint`, `remoteEndpoint`, `option`/`setOption` for the buffer sizes and the hop limit, `close`), `AsyncDatagram`; `openAsyncDatagramSocket(loop, family)`. A UDP socket on an `EventLoop`: readiness on POSIX, the completion port on Windows. A datagram longer than `maxBytes` is `MessageTooLarge` and dropped, never cut short; a state that forbids a call answers `BadHandle` with systemCode 0 | | ``, `` | `ITcpSocket` (`bind`, then `connect` or `listen`; `localEndpoint`, `option`/`setOption`) and `openTcpSocket(loop, family)`; `SocketOption`, `OptionScale`, `SocketOptionRow` and `socketOptionTable()`, the per-platform option rows every socket reads and writes through | +| `` | `IInputStream` (coroutine `read(maxBytes)` answering a `StreamRead` with `InputEnd`), `IOutputStream` (coroutine `write(bytes)`), `StandardStreamHandles`, `processStandardHandles()`, `StreamKind` and `classifyStreamHandle()`, and `openStandardStreams(loop, blocking, handles, maxReadChunk)`. A POSIX pipe, socket or terminal input waits on the loop and reads only once a zero-timeout `poll` confirms it; a regular file, `/dev/null`, every Windows handle, and an input whose registration the backend refuses read on the blocking executor, where a stop ends the wait and the bytes the worker read are the next read's. Output always goes through the executor, in order. No descriptor's `O_NONBLOCK` is touched: it is shared with the parent. One read and one write in flight; a second answers `BadHandle` with systemCode 0 | | `` | `answerFromOwnAddress()` and `openSharedPortUdpSocket()`: hear the segment on a shared port, send and be answered from an address only this node holds | | ``, `` | the transports for threads that may block: `BlockingSocket`, whose every awaitable is already settled, and `BlockingConnector`, an `IConnector` that dials on the calling thread within its budget and arms `BlockingConnectorOptions::ioTimeout` before handing the socket over. Driven by `core::async::syncRun`; never on a loop thread | | `` | the one TCP client: `connectTcp()`, `sendAll()`, `receiveExactly()` | diff --git a/src/core/net/CMakeLists.txt b/src/core/net/CMakeLists.txt index 5a2f106d..10fc8cd2 100644 --- a/src/core/net/CMakeLists.txt +++ b/src/core/net/CMakeLists.txt @@ -161,6 +161,7 @@ core_cpp_add_module(net KIND STATIC Sockets.hpp SplitSocket.hpp SshAgentEndpoint.hpp + StandardStreams.hpp TcpClient.hpp ThreadedAddressResolver.hpp UdpSocket.hpp @@ -215,6 +216,7 @@ core_cpp_add_module(net KIND STATIC SocketContract.cpp SocketOption.cpp Sockets.cpp + StandardStreams.cpp TcpClient.cpp TcpSocket.cpp ThreadedAddressResolver.cpp @@ -234,6 +236,7 @@ core_cpp_add_module(net KIND STATIC detail/SocketErrors.hpp detail/SocketOptionAccess.hpp detail/SshAgentEndpoint.hpp + detail/StandardStreamPrimitives.hpp detail/TcpSocketPrimitives.hpp detail/WakeupChannel.hpp SOURCES_POSIX @@ -255,6 +258,8 @@ core_cpp_add_module(net KIND STATIC posix/SocketOptionTable.cpp posix/SocketsPosix.cpp posix/SshAgentEndpoint.cpp + posix/StandardStreamPrimitives.cpp + posix/StreamKindTable.cpp posix/StreamSocketOptions.cpp posix/UdpSocket.cpp posix/UnixListener.cpp @@ -289,6 +294,8 @@ core_cpp_add_module(net KIND STATIC windows/SocketOptionTable.cpp windows/SocketsWin32.cpp windows/SshAgentEndpoint.cpp + windows/StandardStreamPrimitives.cpp + windows/StreamKindTable.cpp windows/StreamSocketOptions.cpp windows/UdpSocket.cpp windows/UnixSocketPath.cpp @@ -401,6 +408,8 @@ core_cpp_add_test(net SocketDeadline_test.cpp SocketEndpoints_test.cpp Socket_test.cpp + StandardStreams_test.cpp + StandardStreamsTestSupport.hpp StreamSocketOptions_test.cpp TcpClient_test.cpp TcpSocket_test.cpp @@ -448,6 +457,8 @@ core_cpp_add_test(net posix/ResolverErrors_test.cpp posix/SocketErrors_test.cpp posix/SshAgentEndpoint_test.cpp + posix/StandardStreams_test.cpp + posix/StandardStreamsTestSupport.cpp posix/UnixSocket_test.cpp posix/WaitReadableClose_test.cpp SOURCES_LINUX @@ -463,6 +474,7 @@ core_cpp_add_test(net windows/ResolverErrors_test.cpp windows/SocketErrors_test.cpp windows/SshAgentEndpoint_test.cpp + windows/StandardStreamsTestSupport.cpp windows/UnixListener_test.cpp LABELS loopback # IoAwaitable_test.cpp's loop of inline completions skips where symmetric transfer is not a diff --git a/src/core/net/StandardStreams.cpp b/src/core/net/StandardStreams.cpp new file mode 100644 index 00000000..2f3fe0db --- /dev/null +++ b/src/core/net/StandardStreams.cpp @@ -0,0 +1,497 @@ +// SPDX-License-Identifier: Apache-2.0 + +/// @file +/// `openStandardStreams`: one input stream that waits on the loop where its handle allows and reads +/// on the blocking executor where it does not, and an output stream that always writes there. + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace core::net +{ + +namespace +{ + using ReadAnswer = std::expected; + + /// How a worker read ended. + enum class WorkerEnding : std::uint8_t + { + Answered, ///< It read, reached the end, failed, or was dropped unrun: @c read says which. + Interrupted, ///< A stop reached it queued, or cancelled it (Windows): it read nothing, and the next + ///< read reads afresh. + }; + + /// What a worker does when its turn on the executor comes. + enum class WorkerEntry : std::uint8_t + { + Read, ///< Read the handle. + Interrupted, ///< A stop came while it was queued: answer without reading. + }; + + /// What one worker read hands back. + struct WorkerAnswer + { + ReadAnswer read; + WorkerEnding ending = WorkerEnding::Answered; + }; + + /// One worker read's rendezvous with the flow that waits for it (`.agent/rules/async-and-net.md`, + /// Ruling R13): a stop ends the wait, not the read. + using ReadCall = detail::ParkedCall; + + /// @return The stream's own refusal of a call its state does not allow: never the OS's. + [[nodiscard]] NetError refused(std::string what) + { + return makeNetError(NetErrorCode::BadHandle, 0, std::move(what)); + } + + /// @return A task that answers @p error without touching any handle. + template + async::Task> refuse(NetError error) + { + co_return std::unexpected(std::move(error)); + } + + /// @return The first @p count bytes of @p buffer as a read: @c InputEnd::Reached when none. + [[nodiscard]] StreamRead readOf(std::vector buffer, std::size_t count) + { + buffer.resize(count); + auto const end = count == 0 ? InputEnd::Reached : InputEnd::More; + return StreamRead { .bytes = std::move(buffer), .end = end }; + } + + /// What a read that finds a worker read outstanding does next. + enum class NextStep : std::uint8_t + { + Fresh, ///< The worker is done and left nothing to deliver: start another. + Late, ///< The worker is done and its answer was kept: deliver that. + Wait, ///< The worker is still reading: wait for its answer. + }; + + /// One worker read, shared by the stream, the worker running it and a stop that may interrupt it. + /// + /// **Exactly one worker read is outstanding per stream.** A stopped flow leaves the read running, + /// and the stream's next read waits for that same worker rather than starting a second beside it: + /// two blocked reads of one handle would race for its bytes. The worker answers whichever call is + /// current when it finishes, so the next read swaps in a fresh call (the stopped one's is + /// cancelled for good) and waits on that; one mutex orders the swap against the worker's answer. + class BlockingRead + { + public: + /// @param loop Where an answer's waiter is handed back. + explicit BlockingRead(EventLoop& loop): _loop { &loop }, _call { std::make_shared(&loop) } + { + } + + /// @return The call the first waiter waits on. + [[nodiscard]] std::shared_ptr firstCall() const noexcept { return _call; } + + /// The worker, just before its read: records its thread for @c interrupt, unless a stop + /// already came while it was queued -- then it must not read at all, or it would block a + /// thread (and on POSIX take the input) for a reader that is gone. + /// @return Whether to read. + [[nodiscard]] WorkerEntry enter() noexcept + { + auto const guard = std::scoped_lock { _mutex }; + if (_stop == StopRequest::Pending) + return WorkerEntry::Interrupted; + _reader.emplace(); + return WorkerEntry::Read; + } + + /// The worker, after its read: forgets its thread and answers the current call. At most once. + /// @param answer What the read came to. + void finish(WorkerAnswer answer) noexcept + { + auto const guard = std::scoped_lock { _mutex }; + _reader.reset(); + if (_isFinished == Finished::Yes) + return; + _isFinished = Finished::Yes; + _call->settle(std::move(answer)); + } + + /// The stop callback: cancels the worker's read where the OS allows, or, before the worker + /// has started it, remembers the stop for @c enter. Any thread. + void interrupt() noexcept + { + auto const guard = std::scoped_lock { _mutex }; + if (_reader.has_value()) + _reader->interrupt(); + else if (_isFinished == Finished::No) + _stop = StopRequest::Pending; + } + + /// What a read after a stop does with this worker read. + struct Next + { + NextStep step = NextStep::Fresh; + std::optional late {}; ///< For @c NextStep::Late. + std::shared_ptr call {}; ///< For @c NextStep::Wait. + }; + + /// Called on the loop's thread by a read that finds this worker read still the stream's. + /// @return What to do next; a fresh call to wait on where the worker is still reading. + [[nodiscard]] Next resume() + { + auto const guard = std::scoped_lock { _mutex }; + if (_isFinished == Finished::Yes) + { + auto late = _call->takeLateAnswer(); + if (!late.has_value() || late->ending == WorkerEnding::Interrupted) + return Next { .step = NextStep::Fresh }; + return Next { .step = NextStep::Late, .late = std::move(late) }; + } + // A new reader wants this read's bytes: the stop it was going to honour was the last one's. + _stop = StopRequest::None; + _call = std::make_shared(_loop); + return Next { .step = NextStep::Wait, .call = _call }; + } + + private: + /// Whether a stop reached the read before its worker started it. + enum class StopRequest : std::uint8_t + { + None, + Pending, + }; + + /// Whether the worker has answered. + enum class Finished : std::uint8_t + { + No, + Yes, + }; + + std::mutex _mutex; + EventLoop* _loop; + std::shared_ptr _call; + std::optional _reader; + Finished _isFinished = Finished::No; + StopRequest _stop = StopRequest::None; + }; + + /// A worker read's hold on its @c BlockingRead, owned by the detached flow that runs it. + /// + /// **Its destructor is the guard that nobody is stranded**: a worker that never answers -- its + /// executor freed it unrun -- answers @c NetErrorCode::Cancelled here. + class ReadLease + { + public: + explicit ReadLease(std::shared_ptr job) noexcept: _job { std::move(job) } {} + ReadLease(ReadLease&&) noexcept = default; + ReadLease(ReadLease const&) = delete; + ReadLease& operator=(ReadLease const&) = delete; + ReadLease& operator=(ReadLease&&) = delete; + ~ReadLease() { fail(NetErrorCode::Cancelled); } + + /// @return The read this lease holds. + [[nodiscard]] BlockingRead& job() const noexcept { return *_job; } + + /// Answers the read, once. + void finish(WorkerAnswer answer) noexcept + { + if (auto const job = std::exchange(_job, nullptr)) + job->finish(std::move(answer)); + } + + /// Answers a failure that allocates nothing, for the paths that cannot take a throw. + void fail(NetErrorCode code) noexcept + { + if (_job) + finish(WorkerAnswer { .read = std::unexpected(makeNetError(code)) }); + } + + private: + std::shared_ptr _job; + }; + + /// Runs one blocking read of @p handle on @p blocking and answers its call. + /// + /// Detached, because nobody may own it: the waiting flow may be stopped and gone, and the stream + /// with it, long before the read returns. It holds everything it touches by value or by share. + /// @param blocking Where the read runs. + /// @param handle What it reads. + /// @param maxBytes The most it reads. + /// @param lease The read it answers. + async::DetachedTask runBlockingRead(async::IExecutor* blocking, + platform::NativeHandle handle, + std::size_t maxBytes, + ReadLease lease) + { + try + { + co_await async::ResumeOn { *blocking }; + auto buffer = std::vector(maxBytes); + if (lease.job().enter() == WorkerEntry::Interrupted) + { + lease.finish(WorkerAnswer { .read = StreamRead {}, .ending = WorkerEnding::Interrupted }); + co_return; + } + auto got = detail::readStream(handle, buffer, detail::ReadWait::Block); + if (got.has_value()) + lease.finish(WorkerAnswer { .read = readOf(std::move(buffer), *got) }); + else if (got.error().code == NetErrorCode::Cancelled) + lease.finish(WorkerAnswer { .read = std::unexpected(std::move(got.error())), + .ending = WorkerEnding::Interrupted }); + else + lease.finish(WorkerAnswer { .read = std::unexpected(std::move(got.error())) }); + } + catch (...) + { + lease.fail(NetErrorCode::SystemError); + } + } + + /// The stop callback of a flow waiting for a worker read. + struct Interrupt + { + BlockingRead* job = nullptr; + + void operator()() const noexcept { job->interrupt(); } + }; + + /// An input stream's state, shared with the reads it hands out: a read may outlive its stream. + /// Touched on the loop's thread only, but for @c BlockingRead, which guards itself. + struct InputState + { + EventLoop* loop; + async::IExecutor* blocking; + platform::NativeHandle handle; + std::size_t maxReadChunk; + StreamKind kind; ///< Turns Blocking for good where the backend refuses it. + bool isReading = false; ///< A read is in flight (@c detail::OperationClaim). + std::shared_ptr job; ///< The worker read still outstanding, if any. + std::vector carry; ///< A worker's bytes beyond what their read asked for. + }; + + /// @return @p read cut to @p maxBytes, the rest kept in @p state's carry for the next read. + [[nodiscard]] StreamRead keepBeyond(InputState& state, StreamRead read, std::size_t maxBytes) + { + if (read.bytes.size() > maxBytes) + { + auto const cut = read.bytes.begin() + static_cast(maxBytes); + state.carry.assign(cut, read.bytes.end()); + read.bytes.erase(cut, read.bytes.end()); + } + return read; + } + + /// @return Up to @p maxBytes of @p state's carry, taken out of it. + [[nodiscard]] StreamRead takeCarry(InputState& state, std::size_t maxBytes) + { + auto read = StreamRead { .bytes = std::exchange(state.carry, {}) }; + return keepBeyond(state, std::move(read), maxBytes); + } + + /// Reads through the blocking executor, joining the worker read a stopped flow left running. + async::Task readBlocking(std::shared_ptr state, std::size_t maxBytes) + { + auto const token = co_await async::thisCoroStopToken(); + while (true) + { + if (token.stop_requested()) + throw async::OperationCancelled {}; + + auto call = std::shared_ptr {}; + if (state->job) + { + auto next = state->job->resume(); + if (next.step == NextStep::Late) + { + state->job.reset(); + if (!next.late->read.has_value()) + co_return std::move(next.late->read); + co_return keepBeyond(*state, std::move(*next.late->read), maxBytes); + } + if (next.step == NextStep::Wait) + call = std::move(next.call); + else + state->job.reset(); + } + if (!state->job) + { + state->job = std::make_shared(*state->loop); + call = state->job->firstCall(); + runBlockingRead(state->blocking, state->handle, maxBytes, ReadLease { state->job }); + } + + auto const job = state->job; + [[maybe_unused]] auto const interrupt = + async::StopCallback { token, Interrupt { .job = job.get() } }; + auto answer = co_await ReadCall::wait(std::move(call)); + state->job.reset(); + if (answer.ending == WorkerEnding::Interrupted) + continue; + if (!answer.read.has_value()) + co_return std::move(answer.read); + co_return keepBeyond(*state, std::move(*answer.read), maxBytes); + } + } + + /// Reads @p state's handle: from its carry, through the loop, or through the blocking executor. + async::Task readInput(std::shared_ptr state, std::size_t maxBytes) + { + if (!state->carry.empty()) + co_return takeCarry(*state, maxBytes); + + if (state->kind == StreamKind::Pollable) + { + auto refusedByBackend = false; + while (!refusedByBackend) + { + try + { + co_await state->loop->waitReadable(state->handle); + } + catch (FdRegistrationFailed const&) + { + refusedByBackend = true; + continue; + } + // Confirmed, because the descriptor may be blocking and the loop's thread must not + // block: a readiness can be spurious, or another reader's. + if (detail::readReadinessNow(state->handle) == detail::ReadReadiness::NotReady) + continue; + auto buffer = std::vector(maxBytes); + auto got = detail::readStream(state->handle, buffer, detail::ReadWait::NoWait); + if (got.has_value()) + co_return readOf(std::move(buffer), *got); + if (got.error().code != NetErrorCode::WouldBlock) + co_return std::unexpected(std::move(got.error())); + } + // macOS's kqueue refuses some terminals: the executor reads them from now on. + state->kind = StreamKind::Blocking; + } + co_return co_await readBlocking(state, maxBytes); + } + + /// @return A read of nothing, answered at once. + async::Task readNothing() + { + co_return StreamRead {}; + } + + /// The one input stream: Pollable or Blocking by its handle, one read in flight. + class StandardInputStream final: public IInputStream + { + public: + explicit StandardInputStream(std::shared_ptr state) noexcept: _state { std::move(state) } + { + } + + [[nodiscard]] async::Task read(std::size_t maxBytes) override + { + if (_state->isReading) + return refuse(refused("read while another read is in flight")); + if (maxBytes == 0) + return readNothing(); + return detail::holding(detail::OperationClaim { _state, &InputState::isReading }, + readInput(_state, std::min(maxBytes, _state->maxReadChunk))); + } + + private: + std::shared_ptr _state; + }; + + /// An output stream's record of its one write in flight. + struct OutputState + { + bool isWriting = false; ///< A write is in flight (@c detail::OperationClaim). + }; + + /// Writes @p bytes to @p handle on @p blocking, coming back to @p loop. + async::Task> writeOffloaded(EventLoop* loop, + async::IExecutor* blocking, + platform::NativeHandle handle, + std::vector bytes) + { + co_return co_await async::offload( + loop, blocking, [handle, &bytes] { return detail::writeStream(handle, bytes); }); + } + + /// The one output stream: every write on the blocking executor, one in flight. + class OffloadedOutputStream final: public IOutputStream + { + public: + OffloadedOutputStream(EventLoop& loop, async::IExecutor& blocking, platform::NativeHandle handle): + _loop { &loop }, + _blocking { &blocking }, + _handle { handle }, + _state { std::make_shared() } + { + } + + [[nodiscard]] async::Task> write( + std::vector bytes) override + { + if (_state->isWriting) + return refuse(refused("write while another write is in flight")); + return detail::holding(detail::OperationClaim { _state, &OutputState::isWriting }, + writeOffloaded(_loop, _blocking, _handle, std::move(bytes))); + } + + private: + EventLoop* _loop; + async::IExecutor* _blocking; + platform::NativeHandle _handle; + std::shared_ptr _state; + }; + +} // namespace + +StandardStreamHandles processStandardHandles() noexcept +{ + return StandardStreamHandles { + .input = platform::standardInput(), + .output = platform::standardOutput(), + .error = platform::standardError(), + }; +} + +StandardStreams openStandardStreams(EventLoop& loop, + async::IExecutor& blocking, + StandardStreamHandles handles, + std::size_t maxReadChunk) +{ + auto input = std::make_shared(InputState { + .loop = &loop, + .blocking = &blocking, + .handle = handles.input, + .maxReadChunk = std::max(maxReadChunk, 1), + .kind = classifyStreamHandle(handles.input), + .job = nullptr, + .carry = {}, + }); + return StandardStreams { + .input = std::make_unique(std::move(input)), + .output = std::make_unique(loop, blocking, handles.output), + .error = std::make_unique(loop, blocking, handles.error), + }; +} + +} // namespace core::net diff --git a/src/core/net/StandardStreams.hpp b/src/core/net/StandardStreams.hpp new file mode 100644 index 00000000..9b7cf683 --- /dev/null +++ b/src/core/net/StandardStreams.hpp @@ -0,0 +1,207 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// The process's standard streams as coroutines on an @c EventLoop: an input that reads what is +/// there, and two outputs that write in order, whatever kind of object each handle turns out to be. +/// +/// What a standard handle is decides how it can be waited for, and the process does not choose it: +/// the parent does. A pipe, a socket or a terminal on POSIX can be waited for on the loop; a regular +/// file is always "readable" and `epoll` refuses it outright (`EPERM`), `/dev/null` likewise, and +/// on Windows a console handle cannot go on a completion port and an inherited pipe is not opened +/// overlapped. @c classifyStreamHandle sorts a handle into the two ways this header knows, and +/// @c openStandardStreams builds each stream the way its handle allows. +/// +/// **No descriptor's flags are touched.** An inherited descriptor shares its open file description +/// with the parent, so `O_NONBLOCK` set here would be set in the parent's shell too, and a shell +/// whose stdin turned non-blocking under it reads `EAGAIN` as end of input. A @c StreamKind::Pollable +/// input therefore waits for readiness, confirms it, and then reads what is there with a read that +/// cannot block; everything else is read and written on the blocking executor. +/// +/// **The handles are not owned.** A stream never closes its handle: the process's standard handles +/// belong to the process, and a test's to the test. + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace core::net +{ + +class EventLoop; + +/// How a stream's handle can be driven without blocking the loop. +enum class StreamKind : std::uint8_t +{ + /// Waited for on the loop and then read without blocking: a POSIX pipe, socket or terminal. + Pollable, + /// Read or written on the blocking executor: a regular file, a device that is not a terminal + /// (`/dev/null`), and on Windows every kind of handle, because neither a console nor an inherited + /// anonymous pipe can go on the completion port. + Blocking, +}; + +/// Sorts @p handle by what the OS says it is: `fstat`'s file type on POSIX, `GetFileType` on +/// Windows. One table row per type, in each platform's `StreamKindTable.cpp`. +/// +/// A handle the OS cannot describe -- closed, invalid -- is @c StreamKind::Blocking, the kind that +/// assumes nothing: its first read then reports what is wrong with it. +/// @param handle The handle to classify; never read, written or changed. +/// @return How a stream over @p handle is driven. +[[nodiscard]] CORE_NET_API StreamKind classifyStreamHandle(platform::NativeHandle handle) noexcept; + +/// Whether a read reached the end of its input. +enum class InputEnd : std::uint8_t +{ + More, ///< The input may have more. + Reached, ///< The writer closed it, or a file ended: this read returned no bytes. +}; + +/// What one @c IInputStream::read returned. +struct StreamRead +{ + std::vector bytes; ///< What was read; empty exactly when @c end is reached, or when + ///< zero bytes were asked for. + InputEnd end = InputEnd::More; ///< Whether the input ended. +}; + +/// An input stream read by a flow on one @c EventLoop. +/// +/// **One read in flight.** A second @c read while one is in flight -- from the call until its task +/// finishes or is destroyed unstarted -- answers @c NetErrorCode::BadHandle with systemCode 0 and +/// touches nothing. +/// +/// **A stop loses no input.** It throws @c async::OperationCancelled. A worker read the stop +/// reaches while it is still queued never reads, and the next @c read starts afresh. One already +/// running cannot be taken back on POSIX, so it is left to finish and whatever it returns is what +/// the next @c read returns; on Windows the stop also cancels it (`CancelSynchronousIo`), and the +/// next @c read then reads afresh. A stop landing in the instant between the worker's start and its +/// `ReadFile` is not seen by that read, which then finishes like a POSIX one. +/// +/// **A blocking read holds an executor thread until input arrives** -- every Windows stdin, a regular +/// file only briefly, and a macOS terminal its kqueue refuses for as long as nobody types. A stopped +/// read keeps holding it: the thread is the read's until the read returns. See +/// @c openStandardStreams for what that asks of the executor. +/// +/// **It assumes it is its handle's only reader.** Another reader of the same handle could take the +/// bytes between the readiness and the read, and the read would then wait for more on the blocking +/// path's terms. +class IInputStream +{ + public: + virtual ~IInputStream() = default; + IInputStream() = default; + IInputStream(IInputStream const&) = delete; + IInputStream& operator=(IInputStream const&) = delete; + IInputStream(IInputStream&&) = delete; + IInputStream& operator=(IInputStream&&) = delete; + + /// Reads what is available, waiting until something is. + /// @param maxBytes The most to return; clamped to the stream's `maxReadChunk`. Zero answers an + /// empty @c StreamRead at once, with @c InputEnd::More, and reads nothing. + /// @return At least one byte with @c InputEnd::More, or no bytes with @c InputEnd::Reached at + /// the end of the input; a read error as a @c NetError (@c NetErrorCode::SystemError with + /// the OS's code, unless the code has a class of its own). + /// @throws async::OperationCancelled where the awaiting flow is stopped first. + [[nodiscard]] virtual async::Task> read(std::size_t maxBytes) = 0; +}; + +/// An output stream written by a flow on one @c EventLoop, always through the blocking executor. +/// +/// **In order, one write in flight.** A second @c write while one is in flight answers +/// @c NetErrorCode::BadHandle with systemCode 0, so writes reach the handle in the order their +/// flow awaited them. A stop already requested when a write starts throws +/// @c async::OperationCancelled and writes nothing; a write that has started is finished, and +/// answered. +/// +/// **A closed reader is an error, never a signal.** On POSIX `SIGPIPE` is blocked on the writing +/// thread for the write and a pending one consumed -- and on macOS, which raises a pipe's +/// `SIGPIPE` at the whole process, the description's `F_SETNOSIGPIPE` is set at the first write and +/// left set for the life of the process, which every process sharing the description then sees -- so +/// a write to a pipe nobody reads answers +/// @c NetErrorCode::SystemError with `EPIPE` rather than ending the process; on Windows it is +/// `ERROR_NO_DATA` or `ERROR_BROKEN_PIPE`. +class IOutputStream +{ + public: + virtual ~IOutputStream() = default; + IOutputStream() = default; + IOutputStream(IOutputStream const&) = delete; + IOutputStream& operator=(IOutputStream const&) = delete; + IOutputStream(IOutputStream&&) = delete; + IOutputStream& operator=(IOutputStream&&) = delete; + + /// Writes all of @p bytes. + /// @param bytes What to write. + /// @return How many bytes were written: all of them, or fewer where the handle failed part-way. + /// The failure itself is not reported then; a later write that meets it again does. A + /// failure before the first byte is the @c NetError. + /// @throws async::OperationCancelled where the awaiting flow was stopped before the write. + [[nodiscard]] virtual async::Task> write( + std::vector bytes) = 0; +}; + +/// The three handles a set of standard streams is built over. +struct StandardStreamHandles +{ + platform::NativeHandle input; ///< Read by @c StandardStreams::input. + platform::NativeHandle output; ///< Written by @c StandardStreams::output. + platform::NativeHandle error; ///< Written by @c StandardStreams::error. +}; + +/// The process's own standard handles: `platform::standardInput()`, `standardOutput()` and +/// `standardError()`. Separate from @c openStandardStreams so a host or a test can build the +/// streams over handles of its own. +/// @return The handles; on Windows an absent one (a GUI process) is what `GetStdHandle` returns. +[[nodiscard]] CORE_NET_API StandardStreamHandles processStandardHandles() noexcept; + +/// The three streams of a process, or of whatever handles @c openStandardStreams was given. +struct StandardStreams +{ + std::unique_ptr input; ///< Over @c StandardStreamHandles::input. + std::unique_ptr output; ///< Over @c StandardStreamHandles::output. + std::unique_ptr error; ///< Over @c StandardStreamHandles::error. +}; + +/// Builds a stream over each of @p handles, each driven the way @c classifyStreamHandle says. +/// +/// A @c StreamKind::Pollable input whose registration the loop's backend refuses -- macOS's kqueue +/// refuses some terminals with `EINVAL` -- turns into a @c StreamKind::Blocking one at that read, +/// and stays one. +/// +/// Every stream, and every task it returns, is used on @p loop's thread. A stream may be destroyed +/// while a read it returned is still parked: that read finishes on its own, into state it shares. +/// +/// **The thread budget of @p blocking.** A Blocking input's read occupies one of its threads until +/// input arrives, and a stopped read keeps it (see @c IInputStream). Writes run on the same +/// executor, so it needs at least two threads -- or the input a separate executor of its own -- +/// or a write waits behind a read nobody answers. Stopping or joining the executor at exit waits for +/// that read too, which on a terminal means for the user to type. Passing the loop itself as +/// @p blocking (the single-threaded configuration) runs that read on the loop's thread and blocks +/// the whole loop until stdin has input. +/// +/// **A handle stays open until every worker read on it has returned**, not only until the streams +/// are gone: a POSIX worker that finds a non-blocking descriptor empty polls it again by number, and +/// a number closed and reused meanwhile would be another file's. +/// @param loop Where the streams' flows run, and where a blocking call's answer comes back to; +/// must outlive the streams and their tasks. +/// @param blocking Where every blocking read and write runs; must outlive the streams and their +/// tasks, and any read still running on it. +/// @param handles The handles; not owned. +/// @param maxReadChunk The most one read returns, and so the most it allocates. Zero is taken as one. +/// @return The streams. +[[nodiscard]] CORE_NET_API StandardStreams openStandardStreams(EventLoop& loop, + async::IExecutor& blocking, + StandardStreamHandles handles, + std::size_t maxReadChunk = std::size_t { 64 } + * 1024); + +} // namespace core::net diff --git a/src/core/net/StandardStreamsTestSupport.hpp b/src/core/net/StandardStreamsTestSupport.hpp new file mode 100644 index 00000000..d342137b --- /dev/null +++ b/src/core/net/StandardStreamsTestSupport.hpp @@ -0,0 +1,94 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// Test-only: the handles the standard-stream cases build their streams over, made by the test +/// itself -- never the test process's own stdio. Defined per platform, in +/// `posix/StandardStreamsTestSupport.cpp` and `windows/StandardStreamsTestSupport.cpp`, so the +/// portable cases carry no `#ifdef`. + +#include +#include + +#include +#include +#include + +namespace core::net::streams_test +{ + +/// A handle the test made, closed when this goes. +class OwnedHandle +{ + public: + OwnedHandle() = default; + /// @param handle The handle to own; `platform::InvalidHandle` owns nothing. + explicit OwnedHandle(platform::NativeHandle handle) noexcept: _handle { handle } {} + ~OwnedHandle() { reset(); } + OwnedHandle(OwnedHandle const&) = delete; + OwnedHandle& operator=(OwnedHandle const&) = delete; + OwnedHandle(OwnedHandle&& other) noexcept: + _handle { std::exchange(other._handle, platform::InvalidHandle) } + { + } + OwnedHandle& operator=(OwnedHandle&& other) noexcept + { + if (this != &other) + { + reset(); + _handle = std::exchange(other._handle, platform::InvalidHandle); + } + return *this; + } + + /// @return The handle; `platform::InvalidHandle` when none is owned. + [[nodiscard]] platform::NativeHandle get() const noexcept { return _handle; } + + /// Closes the handle now. + void reset() noexcept + { + if (_handle != platform::InvalidHandle) + platform::platformClose(std::exchange(_handle, platform::InvalidHandle)); + } + + private: + platform::NativeHandle _handle = platform::InvalidHandle; +}; + +/// Both ends of an anonymous pipe: blocking, and on Windows not overlapped -- what a child +/// inherits as its standard handles. +struct TestPipe +{ + OwnedHandle read; ///< The end a stream reads. + OwnedHandle write; ///< The end the test writes. +}; + +/// @return A new anonymous pipe; the case fails where the OS refuses one. +[[nodiscard]] TestPipe makeTestPipe(); + +/// @param path An existing file. +/// @return @p path opened for reading. +[[nodiscard]] OwnedHandle openForReading(std::filesystem::path const& path); + +/// @param path The file to create, or to truncate. +/// @return @p path opened for writing. +[[nodiscard]] OwnedHandle openForWriting(std::filesystem::path const& path); + +/// @return The null device (`/dev/null`, `NUL`) opened for reading. +[[nodiscard]] OwnedHandle openNullDevice(); + +/// What a stop does to a worker already blocked in its read. +enum class RunningReadStop : std::uint8_t +{ + Waits, ///< Nothing: the read keeps its thread until input arrives (POSIX). + Cancels, ///< `CancelSynchronousIo` ends it, and its thread is free at once (Windows). +}; + +/// @return What a stop does to a running worker read on this platform. +[[nodiscard]] RunningReadStop runningReadStop() noexcept; + +/// @return What this platform's table says an anonymous pipe is: @c StreamKind::Pollable on POSIX, +/// @c StreamKind::Blocking on Windows. +[[nodiscard]] StreamKind pipeStreamKind() noexcept; + +} // namespace core::net::streams_test diff --git a/src/core/net/StandardStreams_test.cpp b/src/core/net/StandardStreams_test.cpp new file mode 100644 index 00000000..c282843e --- /dev/null +++ b/src/core/net/StandardStreams_test.cpp @@ -0,0 +1,680 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The standard streams over handles each case makes for itself -- a file, the null device, a pipe +// -- and never over the test process's own stdio: a regular file is read on the blocking executor, +// a stop loses no input, one read and one write are in flight at a time, and writes land in order. +// What only POSIX has -- a pipe, a socket or a terminal waited for on the loop -- is in +// posix/StandardStreams_test.cpp. +#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 +#include + +using core::async::Task; +using core::async::testing::ManualExecutor; +using core::net::EventLoop; +using core::net::IInputStream; +using core::net::InputEnd; +using core::net::IOutputStream; +using core::net::NetError; +using core::net::NetErrorCode; +using core::net::openStandardStreams; +using core::net::StandardStreamHandles; +using core::net::StreamKind; +using core::net::StreamRead; +using core::net::streams_test::makeTestPipe; +using core::net::streams_test::openForReading; +using core::net::streams_test::openForWriting; +using core::net::streams_test::openNullDevice; +using core::net::testing::TestLoop; +using core::platform::InvalidHandle; + +namespace +{ + +/// What one awaited read came to: nothing yet, an answer (possibly a failure), or a stop. +struct ReadOutcome +{ + std::optional> answer; + bool isCancelled = false; + std::atomic isFinished { false }; +}; + +/// What one awaited write came to. +struct WriteOutcome +{ + std::optional> answer; + bool isCancelled = false; + bool isFinished = false; +}; + +/// Reads at most @p maxBytes from @p input and records how it ended, a stop included. +Task readInto(IInputStream* input, std::size_t maxBytes, ReadOutcome* out) +{ + try + { + out->answer = co_await input->read(maxBytes); + } + catch (core::async::OperationCancelled const&) + { + out->isCancelled = true; + } + out->isFinished.store(true, std::memory_order_release); +} + +/// Writes @p text to @p output and records how it ended. +Task writeInto(IOutputStream* output, std::string text, WriteOutcome* out) +{ + try + { + auto bytes = std::vector {}; + for (auto const c: text) + bytes.push_back(static_cast(c)); + out->answer = co_await output->write(std::move(bytes)); + } + catch (core::async::OperationCancelled const&) + { + out->isCancelled = true; + } + out->isFinished = true; +} + +/// Sets @p ran on one of @p executor's threads. +core::async::DetachedTask runOnExecutor(core::async::IExecutor* executor, std::atomic* ran) +{ + co_await core::async::ResumeOn { *executor }; + ran->store(true, std::memory_order_release); +} + +/// @return @p bytes as text. +[[nodiscard]] std::string textOf(std::vector const& bytes) +{ + auto text = std::string {}; + for (auto const b: bytes) + text.push_back(static_cast(b)); + return text; +} + +/// @return @p outcome's bytes as text; the case fails where it holds no successful read. +[[nodiscard]] std::string textOf(ReadOutcome const& outcome) +{ + REQUIRE(outcome.answer.has_value()); + REQUIRE(outcome.answer->has_value()); + return textOf((*outcome.answer)->bytes); +} + +/// @return @p outcome's end; the case fails where it holds no successful read. +[[nodiscard]] InputEnd endOf(ReadOutcome const& outcome) +{ + REQUIRE(outcome.answer.has_value()); + REQUIRE(outcome.answer->has_value()); + return (*outcome.answer)->end; +} + +/// Writes @p text to a new file at @p path. +void writeFile(std::filesystem::path const& path, std::string_view text) +{ + auto file = std::ofstream { path, std::ios::binary }; + file << text; +} + +/// @return What the file at @p path holds. +[[nodiscard]] std::string readFile(std::filesystem::path const& path) +{ + // Read by size, not through istreambuf_iterator, whose inlined buffer pointers GCC 14 calls a + // potential null dereference at -O2. + auto text = std::string(static_cast(std::filesystem::file_size(path)), '\0'); + auto file = std::ifstream { path, std::ios::binary }; + file.read(text.data(), static_cast(text.size())); + text.resize(static_cast(file.gcount())); + return text; +} + +/// Writes @p text into @p handle with the platform's plain write, as a parent process would. +void feed(core::platform::NativeHandle handle, std::string_view text) +{ + REQUIRE(core::platform::platformWrite(handle, text.data(), text.size()) + == static_cast(text.size())); +} + +/// One input stream over @p input, its outputs over nothing. +[[nodiscard]] StandardStreamHandles inputOnly(core::platform::NativeHandle input) noexcept +{ + return StandardStreamHandles { .input = input, .output = InvalidHandle, .error = InvalidHandle }; +} + +/// A hand-driven loop and blocking executor, and a read that runs across both. +struct Driven +{ + Driven() = default; + + core::platform::ManualClock clock; + TestLoop loop { clock }; + ManualExecutor blocking; + + /// Starts a read, runs what the blocking executor was given, and lets the loop deliver it. + /// @return The finished read; the case fails where it did not finish. + void readNow(IInputStream& input, std::size_t maxBytes, ReadOutcome& outcome) + { + loop.spawn(readInto(&input, maxBytes, &outcome)); + loop.drain(); + blocking.drain(); + loop.drain(); + REQUIRE(outcome.isFinished.load()); + } + + /// Writes @p text, running the blocking executor and the loop until it is answered. + void writeNow(IOutputStream& output, std::string text, WriteOutcome& outcome) + { + loop.spawn(writeInto(&output, std::move(text), &outcome)); + loop.drain(); + blocking.drain(); + loop.drain(); + REQUIRE(outcome.isFinished); + } +}; + +} // namespace + +TEST_CASE("a regular file and the null device are Blocking, and a pipe is what its OS allows", + "[net][standard-streams]") +{ + auto const directory = core::testing::ScopedTempDir { "core-cpp-standard-streams" }; + writeFile(directory / "file", "x"); + auto const file = openForReading(directory / "file"); + auto const null = openNullDevice(); + auto const pipe = makeTestPipe(); + + CHECK(core::net::classifyStreamHandle(file.get()) == StreamKind::Blocking); + CHECK(core::net::classifyStreamHandle(null.get()) == StreamKind::Blocking); + CHECK(core::net::classifyStreamHandle(pipe.read.get()) == core::net::streams_test::pipeStreamKind()); + CHECK(core::net::classifyStreamHandle(pipe.write.get()) == core::net::streams_test::pipeStreamKind()); + CHECK(core::net::classifyStreamHandle(InvalidHandle) == StreamKind::Blocking); +} + +TEST_CASE("the process's standard handles are the platform's", "[net][standard-streams]") +{ + // Only compared, never read or written: the test process's own stdio is not the case's. + auto const handles = core::net::processStandardHandles(); + CHECK(handles.input == core::platform::standardInput()); + CHECK(handles.output == core::platform::standardOutput()); + CHECK(handles.error == core::platform::standardError()); +} + +TEST_CASE("a regular-file input parks on the blocking executor and reads to its end", + "[net][standard-streams]") +{ + auto const directory = core::testing::ScopedTempDir { "core-cpp-standard-streams" }; + writeFile(directory / "input", "hello world"); + auto const file = openForReading(directory / "input"); + auto driven = Driven {}; + auto streams = openStandardStreams(driven.loop, driven.blocking, inputOnly(file.get())); + + auto first = ReadOutcome {}; + driven.loop.spawn(readInto(streams.input.get(), 5, &first)); + driven.loop.drain(); + // Parked, and on the executor: the loop's thread has not read the file. + REQUIRE(driven.blocking.pending() == 1); + CHECK_FALSE(first.isFinished.load()); + driven.blocking.drain(); + CHECK_FALSE(first.isFinished.load()); // answered, but delivered by the loop + driven.loop.drain(); + REQUIRE(first.isFinished.load()); + CHECK(textOf(first) == "hello"); + CHECK(endOf(first) == InputEnd::More); + + auto second = ReadOutcome {}; + driven.readNow(*streams.input, 64, second); + CHECK(textOf(second) == " world"); + CHECK(endOf(second) == InputEnd::More); + + auto last = ReadOutcome {}; + driven.readNow(*streams.input, 64, last); + CHECK(textOf(last).empty()); + CHECK(endOf(last) == InputEnd::Reached); +} + +TEST_CASE("the null device as input ends at once, through the blocking executor", "[net][standard-streams]") +{ + // `stdin < /dev/null`: epoll refuses the null device, so it must never reach the loop. + auto const null = openNullDevice(); + auto driven = Driven {}; + auto streams = openStandardStreams(driven.loop, driven.blocking, inputOnly(null.get())); + + auto outcome = ReadOutcome {}; + driven.loop.spawn(readInto(streams.input.get(), 16, &outcome)); + driven.loop.drain(); + REQUIRE(driven.blocking.pending() == 1); + driven.blocking.drain(); + driven.loop.drain(); + REQUIRE(outcome.isFinished.load()); + CHECK(textOf(outcome).empty()); + CHECK(endOf(outcome) == InputEnd::Reached); +} + +TEST_CASE("a read is clamped to maxReadChunk, and a read of nothing reads nothing", "[net][standard-streams]") +{ + auto const directory = core::testing::ScopedTempDir { "core-cpp-standard-streams" }; + writeFile(directory / "input", "abcdefgh"); + auto const file = openForReading(directory / "input"); + auto driven = Driven {}; + auto streams = openStandardStreams(driven.loop, driven.blocking, inputOnly(file.get()), 3); + + auto none = ReadOutcome {}; + driven.loop.spawn(readInto(streams.input.get(), 0, &none)); + driven.loop.drain(); + REQUIRE(none.isFinished.load()); + CHECK(driven.blocking.pending() == 0); + CHECK(textOf(none).empty()); + CHECK(endOf(none) == InputEnd::More); + + auto clamped = ReadOutcome {}; + driven.readNow(*streams.input, static_cast(-1), clamped); + CHECK(textOf(clamped) == "abc"); + + auto next = ReadOutcome {}; + driven.readNow(*streams.input, 2, next); + CHECK(textOf(next) == "de"); +} + +TEST_CASE("a zero maxReadChunk is taken as one", "[net][standard-streams]") +{ + auto const directory = core::testing::ScopedTempDir { "core-cpp-standard-streams" }; + writeFile(directory / "input", "ab"); + auto const file = openForReading(directory / "input"); + auto driven = Driven {}; + auto streams = openStandardStreams(driven.loop, driven.blocking, inputOnly(file.get()), 0); + + auto outcome = ReadOutcome {}; + driven.readNow(*streams.input, 64, outcome); + CHECK(textOf(outcome) == "a"); +} + +TEST_CASE("a stop during a parked blocking read throws, and the next read returns the late bytes", + "[net][standard-streams]") +{ + auto const directory = core::testing::ScopedTempDir { "core-cpp-standard-streams" }; + writeFile(directory / "input", "late bytes"); + auto const file = openForReading(directory / "input"); + auto driven = Driven {}; + auto streams = openStandardStreams(driven.loop, driven.blocking, inputOnly(file.get())); + + auto source = core::async::StopSource {}; + auto stopped = ReadOutcome {}; + auto flow = readInto(streams.input.get(), 64, &stopped); + flow.handle().promise().setStopToken(source.get_token()); + flow.handle().resume(); + REQUIRE(driven.blocking.pending() == 1); + source.request_stop(); + driven.loop.drain(); + REQUIRE(stopped.isFinished.load()); + CHECK(stopped.isCancelled); + CHECK_FALSE(stopped.answer.has_value()); + + SECTION("the stop reaches the worker while it is still queued") + { + // It must not read for a reader that is gone: it answers without touching the file, and the + // next read starts a worker of its own and takes no late answer. + driven.blocking.drain(); + CHECK(driven.loop.drain() == 0); + + auto resumed = ReadOutcome {}; + driven.loop.spawn(readInto(streams.input.get(), 64, &resumed)); + driven.loop.drain(); + CHECK_FALSE(resumed.isFinished.load()); + REQUIRE(driven.blocking.pending() == 1); // a fresh worker read + driven.blocking.drain(); + driven.loop.drain(); + REQUIRE(resumed.isFinished.load()); + CHECK(textOf(resumed) == "late bytes"); + CHECK(endOf(resumed) == InputEnd::More); + } + + SECTION("the next read asks for less than the worker it joins") + { + // The worker reads 64 bytes' worth for the reader that joined it, which asked for 4; the + // rest is kept for the read after, never dropped. + auto shorter = ReadOutcome {}; + driven.loop.spawn(readInto(streams.input.get(), 4, &shorter)); + driven.loop.drain(); + REQUIRE(driven.blocking.pending() == 1); // the same worker, still queued + driven.blocking.drain(); + driven.loop.drain(); + REQUIRE(shorter.isFinished.load()); + CHECK(textOf(shorter) == "late"); + + auto rest = ReadOutcome {}; + driven.loop.spawn(readInto(streams.input.get(), 64, &rest)); + driven.loop.drain(); + REQUIRE(rest.isFinished.load()); + CHECK(driven.blocking.pending() == 0); + CHECK(textOf(rest) == " bytes"); + } + + SECTION("the next read starts while the worker is still out") + { + // It waits for the same worker read rather than starting a second one beside it. + auto resumed = ReadOutcome {}; + driven.loop.spawn(readInto(streams.input.get(), 64, &resumed)); + driven.loop.drain(); + CHECK_FALSE(resumed.isFinished.load()); + CHECK(driven.blocking.pending() == 1); + driven.blocking.drain(); + driven.loop.drain(); + REQUIRE(resumed.isFinished.load()); + CHECK(textOf(resumed) == "late bytes"); + } + + auto last = ReadOutcome {}; + driven.readNow(*streams.input, 64, last); + CHECK(endOf(last) == InputEnd::Reached); +} + +TEST_CASE("a blocking executor dropping a queued read answers it Cancelled", "[net][standard-streams]") +{ + // A job its executor destroys unrun is freed, not run: the read's guard is what keeps the + // waiter from being stranded. + auto const directory = core::testing::ScopedTempDir { "core-cpp-standard-streams" }; + writeFile(directory / "input", "never read"); + auto const file = openForReading(directory / "input"); + auto clock = core::platform::ManualClock {}; + auto loop = TestLoop { clock }; + auto blocking = std::make_unique(); + auto streams = openStandardStreams(loop, *blocking, inputOnly(file.get())); + + auto outcome = ReadOutcome {}; + loop.spawn(readInto(streams.input.get(), 64, &outcome)); + loop.drain(); + REQUIRE(blocking->pending() == 1); + blocking.reset(); + loop.drain(); + REQUIRE(outcome.isFinished.load()); + REQUIRE(outcome.answer.has_value()); + REQUIRE_FALSE(outcome.answer->has_value()); + CHECK(outcome.answer->error().code == NetErrorCode::Cancelled); +} + +TEST_CASE("a read of a flow already stopped throws and starts no blocking read", "[net][standard-streams]") +{ + auto const directory = core::testing::ScopedTempDir { "core-cpp-standard-streams" }; + writeFile(directory / "input", "untouched"); + auto const file = openForReading(directory / "input"); + auto driven = Driven {}; + auto streams = openStandardStreams(driven.loop, driven.blocking, inputOnly(file.get())); + + driven.loop.rootStopSource().request_stop(); + auto outcome = ReadOutcome {}; + driven.loop.spawn(readInto(streams.input.get(), 64, &outcome)); + driven.loop.drain(); + REQUIRE(outcome.isFinished.load()); + CHECK(outcome.isCancelled); + CHECK(driven.blocking.pending() == 0); +} + +TEST_CASE("a second read while one is in flight is BadHandle, and an answered read frees the slot", + "[net][standard-streams]") +{ + auto const directory = core::testing::ScopedTempDir { "core-cpp-standard-streams" }; + writeFile(directory / "input", "one"); + auto const file = openForReading(directory / "input"); + auto driven = Driven {}; + auto streams = openStandardStreams(driven.loop, driven.blocking, inputOnly(file.get())); + + auto first = ReadOutcome {}; + driven.loop.spawn(readInto(streams.input.get(), 64, &first)); + driven.loop.drain(); + REQUIRE(driven.blocking.pending() == 1); + + auto second = ReadOutcome {}; + driven.loop.spawn(readInto(streams.input.get(), 64, &second)); + driven.loop.drain(); + REQUIRE(second.isFinished.load()); + REQUIRE(second.answer.has_value()); + REQUIRE_FALSE(second.answer->has_value()); + CHECK(second.answer->error().code == NetErrorCode::BadHandle); + CHECK(second.answer->error().systemCode == 0); + CHECK(driven.blocking.pending() == 1); // the refusal started no second worker read + + driven.blocking.drain(); + driven.loop.drain(); + REQUIRE(first.isFinished.load()); + CHECK(textOf(first) == "one"); + + auto third = ReadOutcome {}; + driven.readNow(*streams.input, 64, third); + CHECK(endOf(third) == InputEnd::Reached); + + SECTION("an unstarted read holds the slot until it is destroyed") + { + auto unstarted = std::optional>> { streams.input->read(1) }; + auto refused = ReadOutcome {}; + driven.loop.spawn(readInto(streams.input.get(), 1, &refused)); + driven.loop.drain(); + REQUIRE(refused.answer.has_value()); + REQUIRE_FALSE(refused.answer->has_value()); + CHECK(refused.answer->error().code == NetErrorCode::BadHandle); + + unstarted.reset(); + auto allowed = ReadOutcome {}; + driven.readNow(*streams.input, 1, allowed); + CHECK(endOf(allowed) == InputEnd::Reached); + } +} + +TEST_CASE("three writes arrive in order, each through the blocking executor", "[net][standard-streams]") +{ + auto const directory = core::testing::ScopedTempDir { "core-cpp-standard-streams" }; + auto output = openForWriting(directory / "output"); + auto error = openForWriting(directory / "error"); + auto driven = Driven {}; + auto streams = openStandardStreams( + driven.loop, + driven.blocking, + StandardStreamHandles { .input = InvalidHandle, .output = output.get(), .error = error.get() }); + + for (auto const* text: { "one ", "two ", "three" }) + { + auto outcome = WriteOutcome {}; + driven.loop.spawn(writeInto(streams.output.get(), text, &outcome)); + driven.loop.drain(); + REQUIRE(driven.blocking.pending() == 1); // never written from the loop's thread + driven.blocking.drain(); + driven.loop.drain(); + REQUIRE(outcome.isFinished); + REQUIRE(outcome.answer.has_value()); + REQUIRE(outcome.answer->has_value()); + CHECK(**outcome.answer == std::string_view { text }.size()); + } + auto toError = WriteOutcome {}; + driven.writeNow(*streams.error, "oops", toError); + REQUIRE(toError.answer.has_value()); + REQUIRE(toError.answer->has_value()); + + output.reset(); + error.reset(); + CHECK(readFile(directory / "output") == "one two three"); + CHECK(readFile(directory / "error") == "oops"); +} + +TEST_CASE("a second write while one is in flight is BadHandle and writes nothing", "[net][standard-streams]") +{ + auto const directory = core::testing::ScopedTempDir { "core-cpp-standard-streams" }; + auto output = openForWriting(directory / "output"); + auto driven = Driven {}; + auto streams = openStandardStreams( + driven.loop, + driven.blocking, + StandardStreamHandles { .input = InvalidHandle, .output = output.get(), .error = InvalidHandle }); + + auto first = WriteOutcome {}; + driven.loop.spawn(writeInto(streams.output.get(), "first", &first)); + driven.loop.drain(); + REQUIRE(driven.blocking.pending() == 1); + + auto second = WriteOutcome {}; + driven.loop.spawn(writeInto(streams.output.get(), "second", &second)); + driven.loop.drain(); + REQUIRE(second.isFinished); + REQUIRE(second.answer.has_value()); + REQUIRE_FALSE(second.answer->has_value()); + CHECK(second.answer->error().code == NetErrorCode::BadHandle); + CHECK(second.answer->error().systemCode == 0); + CHECK(driven.blocking.pending() == 1); + + driven.blocking.drain(); + driven.loop.drain(); + REQUIRE(first.isFinished); + + auto third = WriteOutcome {}; + driven.writeNow(*streams.output, "+third", third); + REQUIRE(third.answer.has_value()); + CHECK(third.answer->has_value()); + + output.reset(); + CHECK(readFile(directory / "output") == "first+third"); +} + +TEST_CASE("a write of a stopped flow writes nothing", "[net][standard-streams]") +{ + auto const directory = core::testing::ScopedTempDir { "core-cpp-standard-streams" }; + auto output = openForWriting(directory / "output"); + auto driven = Driven {}; + auto streams = openStandardStreams( + driven.loop, + driven.blocking, + StandardStreamHandles { .input = InvalidHandle, .output = output.get(), .error = InvalidHandle }); + + driven.loop.rootStopSource().request_stop(); + auto outcome = WriteOutcome {}; + driven.writeNow(*streams.output, "never", outcome); + CHECK(outcome.isCancelled); + CHECK(driven.blocking.pending() == 0); + output.reset(); + CHECK(readFile(directory / "output").empty()); +} + +TEST_CASE("a write to a pipe nobody reads is an error, not the end of the process", "[net][standard-streams]") +{ + // On POSIX the write raises SIGPIPE, whose default action ends the process: the case passing at + // all is half of what it checks. + auto pipe = makeTestPipe(); + pipe.read.reset(); + auto driven = Driven {}; + auto streams = openStandardStreams( + driven.loop, + driven.blocking, + StandardStreamHandles { .input = InvalidHandle, .output = pipe.write.get(), .error = InvalidHandle }); + + auto outcome = WriteOutcome {}; + driven.writeNow(*streams.output, "into the void", outcome); + REQUIRE(outcome.answer.has_value()); + REQUIRE_FALSE(outcome.answer->has_value()); + CHECK(outcome.answer->error().code == NetErrorCode::SystemError); + CHECK(outcome.answer->error().systemCode != 0); + + // And again: the first one's signal was consumed, not left pending for the next write. + auto again = WriteOutcome {}; + driven.writeNow(*streams.output, "and again", again); + REQUIRE(again.answer.has_value()); + CHECK_FALSE(again.answer->has_value()); +} + +TEST_CASE("a stopped blocking read of a pipe keeps the bytes that arrive after it", + "[net][standard-streams][threading]") +{ + // A worker really blocked in its read. On POSIX a pipe is Pollable, so the backend refuses its + // registration to make it Blocking; on Windows a pipe is Blocking already, and the stop cancels + // the worker's read instead. Either way the bytes written after the stop are the next read's. + constexpr auto Budget = std::chrono::seconds { 10 }; + + auto pipe = makeTestPipe(); + auto backend = core::net::testing::ScriptedBackend {}; + backend.refuseNextAttach(); + auto loop = EventLoop { backend }; + auto pool = core::async::ThreadPoolExecutor { 1 }; + auto streams = openStandardStreams(loop, pool, inputOnly(pipe.read.get())); + // Outlives the guard: a probe the pool still holds when a REQUIRE fails runs as it stops. + auto probeRan = std::atomic { false }; + // On the way out, a failed REQUIRE's included: the write end closes first, so a worker still + // blocked in its read sees the end and the pool can be joined, rather than hanging the binary. + auto const release = core::net::detail::ScopeGuard { [&]() noexcept { + pipe.write.reset(); + pool.stop(); + } }; + + auto const runUntil = [&](ReadOutcome const& outcome) { + auto const deadline = std::chrono::steady_clock::now() + Budget; + while (!outcome.isFinished.load(std::memory_order_acquire) + && std::chrono::steady_clock::now() < deadline) + { + if (loop.runUntilIdle() == 0) + std::this_thread::yield(); + } + return outcome.isFinished.load(std::memory_order_acquire); + }; + + auto source = core::async::StopSource {}; + auto stopped = ReadOutcome {}; + auto flow = readInto(streams.input.get(), 64, &stopped); + flow.handle().promise().setStopToken(source.get_token()); + flow.handle().resume(); + // Give the worker time to enter its read; the outcome does not depend on whether it has. + std::this_thread::sleep_for(std::chrono::milliseconds { 50 }); + source.request_stop(); + REQUIRE(runUntil(stopped)); + CHECK(stopped.isCancelled); + + if (core::net::streams_test::runningReadStop() == core::net::streams_test::RunningReadStop::Cancels) + { + // The pool's one thread is free again before any input: the stop cancelled the read rather + // than leaving it to wait for bytes. Uncancelled, the probe could not run until the feed below. + runOnExecutor(&pool, &probeRan); + auto const deadline = std::chrono::steady_clock::now() + Budget; + while (!probeRan.load(std::memory_order_acquire) && std::chrono::steady_clock::now() < deadline) + std::this_thread::yield(); + REQUIRE(probeRan.load(std::memory_order_acquire)); + } + + feed(pipe.write.get(), "after the stop"); + auto resumed = ReadOutcome {}; + loop.spawn(readInto(streams.input.get(), 64, &resumed)); + REQUIRE(runUntil(resumed)); + CHECK(textOf(resumed) == "after the stop"); + + pipe.write.reset(); + auto last = ReadOutcome {}; + loop.spawn(readInto(streams.input.get(), 64, &last)); + REQUIRE(runUntil(last)); + CHECK(endOf(last) == InputEnd::Reached); +} diff --git a/src/core/net/detail/StandardStreamPrimitives.hpp b/src/core/net/detail/StandardStreamPrimitives.hpp new file mode 100644 index 00000000..f5b3c813 --- /dev/null +++ b/src/core/net/detail/StandardStreamPrimitives.hpp @@ -0,0 +1,97 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// The platform half of the standard streams (`StandardStreams.cpp`): one blocking read, one +/// complete write, the check that a readable handle really is, and the hold a stop needs on the +/// thread a blocking read runs on. Defined in `posix/StandardStreamPrimitives.cpp` and +/// `windows/StandardStreamPrimitives.cpp`. + +#include +#include + +#include +#include +#include +#include + +namespace core::net::detail +{ + +/// What a read of a descriptor with nothing to read yet does. +enum class ReadWait : std::uint8_t +{ + NoWait, ///< Answers @c NetErrorCode::WouldBlock: the caller waits on its loop. + Block, ///< Waits in the call: the caller is a blocking executor's thread. +}; + +/// Reads what @p handle has. +/// +/// An interrupted call is retried. A descriptor that is non-blocking (its parent's choice) and has +/// nothing to read is waited for or answered @c NetErrorCode::WouldBlock, as @p wait says; a blocking +/// one blocks either way, so @c ReadWait::NoWait is for a handle known to be ready. A read the +/// thread's @c ReadingThread::interrupt cancelled answers @c NetErrorCode::Cancelled. +/// @param handle The handle to read. +/// @param into Where the bytes go; at least one byte long. +/// @param wait What a non-blocking descriptor with nothing to read does. +/// @return How many bytes were read; zero at the end of the input (a Windows broken pipe included). +[[nodiscard]] std::expected readStream(platform::NativeHandle handle, + std::span into, + ReadWait wait); + +/// Writes all of @p bytes to @p handle, blocking until it has. +/// +/// A non-blocking descriptor is waited for. On POSIX `SIGPIPE` is blocked on the calling thread +/// for the call, and one the call raised is consumed before the mask is restored, so a reader that +/// went away is an error and never a signal. Where the system raises it at the process (macOS), the +/// description's `F_SETNOSIGPIPE` is set once and never cleared. +/// @param handle The handle to write. +/// @param bytes What to write. +/// @return How many bytes were written: all of them, or the count before a failure once one byte +/// or more is out. A failure before the first byte is the error. +[[nodiscard]] std::expected writeStream(platform::NativeHandle handle, + std::span bytes); + +/// Whether a handle the loop called readable will answer a read without blocking. +enum class ReadReadiness : std::uint8_t +{ + NotReady, ///< A spurious readiness, or another reader took the bytes: wait again. + Ready, ///< Bytes, the end of the input, or an error are there to be read. +}; + +/// Asks @p handle, without waiting, whether a read would return at once. +/// +/// What lets a @c StreamKind::Pollable input read a descriptor whose `O_NONBLOCK` it must not set: +/// a readiness the loop reported is confirmed before the read, so the loop's thread never blocks. +/// Windows has no Pollable stream; its definition answers @c ReadReadiness::Ready. +/// @param handle The handle to ask. +/// @return Whether a read would return at once. +[[nodiscard]] ReadReadiness readReadinessNow(platform::NativeHandle handle) noexcept; + +/// The thread a blocking read is running on, held so a stop can cancel that read where the OS +/// allows: on Windows `CancelSynchronousIo`, on POSIX nothing, because a read that has started +/// there cannot be taken back without a signal handler the library does not own. +/// +/// Made on the reading thread, just before the read, and destroyed on it, just after, both under +/// the lock the stopper takes to call @c interrupt -- so an interrupt can only ever reach the read +/// it was meant for, never whatever that pool thread runs next. +class ReadingThread +{ + public: + /// Records the calling thread. + ReadingThread() noexcept; + ~ReadingThread(); + ReadingThread(ReadingThread const&) = delete; + ReadingThread& operator=(ReadingThread const&) = delete; + ReadingThread(ReadingThread&&) = delete; + ReadingThread& operator=(ReadingThread&&) = delete; + + /// Cancels the recorded thread's synchronous read, if one is running; any thread may call it. + void interrupt() noexcept; + + private: + /// Windows: a duplicated handle of the reading thread. POSIX keeps nothing here. + [[maybe_unused]] platform::NativeHandle _thread = platform::InvalidHandle; +}; + +} // namespace core::net::detail diff --git a/src/core/net/posix/StandardStreamPrimitives.cpp b/src/core/net/posix/StandardStreamPrimitives.cpp new file mode 100644 index 00000000..e10f42ad --- /dev/null +++ b/src/core/net/posix/StandardStreamPrimitives.cpp @@ -0,0 +1,216 @@ +// SPDX-License-Identifier: Apache-2.0 + +/// @file +/// The POSIX standard-stream primitives: `read`, `write` with `SIGPIPE` held off, and a zero-timeout +/// `poll` to confirm a readiness before a read of a descriptor that may be blocking. + +#include + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace core::net::detail +{ + +namespace +{ + /// @return The error of a failed stream call, classified by the one socket-error table. + [[nodiscard]] NetError streamError(int code, char const* what) + { + return socketError(code, std::string { what }); + } + + /// Blocks until @p fd is ready for @p events, for a descriptor its parent made non-blocking. + void waitFor(int fd, short events) noexcept + { + auto entry = pollfd { .fd = fd, .events = events, .revents = 0 }; + while (::poll(&entry, 1, -1) < 0 && errno == EINTR) + { + } + } + + /// Asks with `select` what `poll` could not: macOS's `poll` answers `POLLNVAL` for an open + /// terminal, which `select` supports. A descriptor `select` cannot hold (`FD_SETSIZE` and above) + /// is answered Ready, and the read then decides, as it would for any other. + [[nodiscard]] ReadReadiness readReadinessBySelect(int fd) noexcept + { + if (fd >= FD_SETSIZE) + return ReadReadiness::Ready; + while (true) + { + auto readable = fd_set {}; + FD_ZERO(&readable); + FD_SET(fd, &readable); + auto zero = timeval {}; + auto const ready = ::select(fd + 1, &readable, nullptr, nullptr, &zero); + if (ready == 0) + return ReadReadiness::NotReady; + if (ready > 0 || errno != EINTR) + return ReadReadiness::Ready; + } + } + + /// Holds `SIGPIPE` off the calling thread for one write, and consumes one the write raised. + /// + /// A write to a pipe whose reader is gone raises `SIGPIPE`, directed at the writing thread, and + /// its default action ends the process. There is no `MSG_NOSIGNAL` for a pipe and no flag to + /// set on a descriptor the parent shares, so the signal is blocked here, and one that became + /// pending during the write -- and was not pending before it -- is taken with `sigwait` before + /// the old mask returns. `sigwait` rather than `sigtimedwait`, which macOS lacks; it is only + /// called with the signal known to be pending, so it does not wait. + class SigpipeHold + { + public: + SigpipeHold() noexcept + { + sigemptyset(&_pipe); + sigaddset(&_pipe, SIGPIPE); + auto pending = sigset_t {}; + sigpending(&pending); + _wasPending = sigismember(&pending, SIGPIPE) == 1 ? Pending::Yes : Pending::No; + pthread_sigmask(SIG_BLOCK, &_pipe, &_previous); + } + + ~SigpipeHold() + { + auto pending = sigset_t {}; + sigpending(&pending); + if (_wasPending == Pending::No && sigismember(&pending, SIGPIPE) == 1) + { + auto taken = 0; + sigwait(&_pipe, &taken); + } + pthread_sigmask(SIG_SETMASK, &_previous, nullptr); + } + + SigpipeHold(SigpipeHold const&) = delete; + SigpipeHold& operator=(SigpipeHold const&) = delete; + SigpipeHold(SigpipeHold&&) = delete; + SigpipeHold& operator=(SigpipeHold&&) = delete; + + private: + /// Whether a `SIGPIPE` was pending before the write: then it is somebody else's to take. + enum class Pending : std::uint8_t + { + No, + Yes, + }; + + sigset_t _pipe {}; + sigset_t _previous {}; + Pending _wasPending = Pending::No; + }; + + /// Where the system raises a pipe's `SIGPIPE` at the whole process rather than at the writing + /// thread (macOS: XNU's write path calls `psignal` on the process), blocking it on the writing + /// thread is not enough: the kernel hands it to any thread that has it unblocked, and its default + /// action ends the process. There the descriptor's own flag (`F_SETNOSIGPIPE`) is set at the first + /// write and **stays set for the life of the process**, so every process sharing the description + /// -- a parent that handed down its stdout -- writes to it without `SIGPIPE` from then on, and + /// sees `EPIPE` instead. A save and a restore around each write would race with every other writer + /// of the description, one restoring the flag while another is mid-write. Nothing on a system + /// without the flag, whose `SIGPIPE` goes to the writing thread. + void keepSigpipeOffDescription([[maybe_unused]] int fd) noexcept + { +#ifdef F_SETNOSIGPIPE + if (::fcntl(fd, F_GETNOSIGPIPE) == 0) + ::fcntl(fd, F_SETNOSIGPIPE, 1); +#endif + } +} // namespace + +std::expected readStream(platform::NativeHandle handle, + std::span into, + ReadWait wait) +{ + while (true) + { + auto const got = ::read(handle, into.data(), into.size()); + if (got >= 0) + return static_cast(got); + auto const code = errno; + if (code == EINTR) + continue; + if (isWouldBlock(code) && wait == ReadWait::Block) + { + waitFor(handle, POLLIN); + continue; + } + if (isWouldBlock(code)) + return std::unexpected(makeNetError(NetErrorCode::WouldBlock, code, "read: nothing to read yet")); + return std::unexpected(streamError(code, "read")); + } +} + +std::expected writeStream(platform::NativeHandle handle, + std::span bytes) +{ + [[maybe_unused]] auto const hold = SigpipeHold {}; + keepSigpipeOffDescription(handle); + auto written = std::size_t { 0 }; + while (written < bytes.size()) + { + auto const rest = bytes.subspan(written); + auto const put = ::write(handle, rest.data(), rest.size()); + if (put >= 0) + { + written += static_cast(put); + continue; + } + auto const code = errno; + if (code == EINTR) + continue; + if (isWouldBlock(code)) + { + waitFor(handle, POLLOUT); + continue; + } + if (written > 0) + return written; + return std::unexpected(streamError(code, "write")); + } + return written; +} + +ReadReadiness readReadinessNow(platform::NativeHandle handle) noexcept +{ + auto entry = pollfd { .fd = handle, .events = POLLIN, .revents = 0 }; + while (true) + { + auto const ready = ::poll(&entry, 1, 0); + if (ready > 0 && (entry.revents & POLLNVAL) != 0 && ::fcntl(handle, F_GETFD) >= 0) + return readReadinessBySelect(handle); // an open descriptor poll cannot ask: a macOS tty + if (ready > 0) + return ReadReadiness::Ready; // POLLIN, POLLHUP, POLLERR, and a closed descriptor's POLLNVAL + if (ready == 0) + return ReadReadiness::NotReady; + if (errno != EINTR) + return ReadReadiness::Ready; // let the read report what poll could not + } +} + +ReadingThread::ReadingThread() noexcept = default; + +ReadingThread::~ReadingThread() = default; + +void ReadingThread::interrupt() noexcept +{ + // Nothing to do: see the class comment. The stop has already handed the waiter back. +} + +} // namespace core::net::detail diff --git a/src/core/net/posix/StandardStreamsTestSupport.cpp b/src/core/net/posix/StandardStreamsTestSupport.cpp new file mode 100644 index 00000000..2077fb15 --- /dev/null +++ b/src/core/net/posix/StandardStreamsTestSupport.cpp @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The POSIX handles of StandardStreamsTestSupport.hpp. +#include + +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace core::net::streams_test +{ + +namespace +{ + /// @return @p fd owned, or a throw naming @p what where it is -1. + [[nodiscard]] OwnedHandle ownedOrThrow(int fd, char const* what) + { + if (fd < 0) + throw std::system_error(errno, std::generic_category(), what); + return OwnedHandle { fd }; + } +} // namespace + +TestPipe makeTestPipe() +{ + auto fds = std::array {}; + if (::pipe(fds.data()) != 0) + throw std::system_error(errno, std::generic_category(), "pipe"); + auto pipe = TestPipe { .read = OwnedHandle { fds[0] }, .write = OwnedHandle { fds[1] } }; + for (auto const fd: fds) + ::fcntl(fd, F_SETFD, FD_CLOEXEC); + return pipe; +} + +OwnedHandle openForReading(std::filesystem::path const& path) +{ + return ownedOrThrow(::open(path.c_str(), O_RDONLY | O_CLOEXEC), "open for reading"); +} + +OwnedHandle openForWriting(std::filesystem::path const& path) +{ + return ownedOrThrow(::open(path.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600), + "open for writing"); +} + +OwnedHandle openNullDevice() +{ + return ownedOrThrow(::open("/dev/null", O_RDONLY | O_CLOEXEC), "open /dev/null"); +} + +StreamKind pipeStreamKind() noexcept +{ + return StreamKind::Pollable; +} + +RunningReadStop runningReadStop() noexcept +{ + return RunningReadStop::Waits; +} + +} // namespace core::net::streams_test diff --git a/src/core/net/posix/StandardStreams_test.cpp b/src/core/net/posix/StandardStreams_test.cpp new file mode 100644 index 00000000..a3e4d657 --- /dev/null +++ b/src/core/net/posix/StandardStreams_test.cpp @@ -0,0 +1,457 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The POSIX half of the standard streams: a pipe, a socket and a terminal are Pollable, read +// through the loop and never through the blocking executor, with the inherited descriptor's flags +// left as the parent set them; and a Pollable input the backend refuses is read on the executor. +#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 +#include +#include +#include + +#include +#include +#include + +using core::async::Task; +using core::async::testing::ManualExecutor; +using core::net::EventLoop; +using core::net::IInputStream; +using core::net::InputEnd; +using core::net::NetError; +using core::net::openStandardStreams; +using core::net::StandardStreamHandles; +using core::net::StreamKind; +using core::net::StreamRead; +using core::net::streams_test::makeTestPipe; +using core::net::streams_test::OwnedHandle; +using core::platform::InvalidHandle; + +namespace +{ + +/// A loop over the platform's default backend, kept alive with it. +struct Loop +{ + std::unique_ptr backend = core::net::makeDefaultBackend(); + EventLoop loop { *backend }; +}; + +/// What one awaited read came to. +struct ReadOutcome +{ + std::optional> answer; + bool isCancelled = false; +}; + +/// Reads at most @p maxBytes from @p input and records how it ended, a stop included. +Task readInto(IInputStream* input, std::size_t maxBytes, ReadOutcome* out) +{ + try + { + out->answer = co_await input->read(maxBytes); + } + catch (core::async::OperationCancelled const&) + { + out->isCancelled = true; + } +} + +/// Writes @p text into @p fd after @p delay on @p loop, as another process would. +Task feedLater(EventLoop* loop, int fd, std::string text, std::chrono::milliseconds delay) +{ + co_await loop->delay(delay); + REQUIRE(::write(fd, text.data(), text.size()) == static_cast(text.size())); +} + +/// Runs @p task on @p loop, failing the case -- naming it -- where it has not finished in 5 s. +void blockOnWithin(EventLoop& loop, Task task) +{ + constexpr auto Limit = std::chrono::seconds { 5 }; + if (!core::net::testing::blockOnWithin(loop, std::move(task), Limit)) + FAIL("a stream wait in \"" << Catch::getResultCapture().getCurrentTestName() + << "\" took longer than 5 s"); +} + +/// @return @p outcome's bytes as text; the case fails where it holds no successful read. +[[nodiscard]] std::string textOf(ReadOutcome const& outcome) +{ + REQUIRE(outcome.answer.has_value()); + REQUIRE(outcome.answer->has_value()); + auto text = std::string {}; + for (auto const b: (*outcome.answer)->bytes) + text.push_back(static_cast(b)); + return text; +} + +/// @return @p outcome's end; the case fails where it holds no successful read. +[[nodiscard]] InputEnd endOf(ReadOutcome const& outcome) +{ + REQUIRE(outcome.answer.has_value()); + REQUIRE(outcome.answer->has_value()); + return (*outcome.answer)->end; +} + +/// One input stream over @p fd, its outputs over nothing. +[[nodiscard]] StandardStreamHandles inputOnly(int fd) noexcept +{ + return StandardStreamHandles { .input = fd, .output = InvalidHandle, .error = InvalidHandle }; +} + +/// Both ends of a connected stream socket pair. +struct SocketPair +{ + OwnedHandle near; ///< The end a stream reads. + OwnedHandle far; ///< The end the test writes. +}; + +[[nodiscard]] SocketPair makeSocketPair() +{ + auto fds = std::array {}; + REQUIRE(::socketpair(AF_UNIX, SOCK_STREAM, 0, fds.data()) == 0); + return SocketPair { .near = OwnedHandle { fds[0] }, .far = OwnedHandle { fds[1] } }; +} + +/// A pseudo-terminal: the controlling side the test writes, and the terminal a stream reads. +struct PseudoTerminal +{ + OwnedHandle controller; ///< The master side. + OwnedHandle terminal; ///< The slave side: what a shell's stdin would be. +}; + +/// @return A new pseudo-terminal in raw mode, so a byte written is a byte read; SKIPs where the +/// host has none. +[[nodiscard]] PseudoTerminal makePseudoTerminal() +{ + auto controller = OwnedHandle { ::posix_openpt(O_RDWR | O_NOCTTY) }; + if (controller.get() < 0) + SKIP("no pseudo-terminal on this host"); + REQUIRE(::grantpt(controller.get()) == 0); + REQUIRE(::unlockpt(controller.get()) == 0); + // ptsname_r, not ptsname: the latter returns a static buffer. + auto name = std::array {}; + REQUIRE(::ptsname_r(controller.get(), name.data(), name.size()) == 0); + auto terminal = OwnedHandle { ::open(name.data(), O_RDWR | O_NOCTTY) }; + REQUIRE(terminal.get() >= 0); + auto mode = termios {}; + REQUIRE(::tcgetattr(terminal.get(), &mode) == 0); + ::cfmakeraw(&mode); + REQUIRE(::tcsetattr(terminal.get(), TCSANOW, &mode) == 0); + return PseudoTerminal { .controller = std::move(controller), .terminal = std::move(terminal) }; +} + +/// Reads @p fd's input through a stream on a real loop: once with the bytes already there, once +/// parked until they arrive. Asserts nothing ever reached the blocking executor. +void readsThroughTheLoop(int readFd, int writeFd) +{ + auto loop = Loop {}; + auto blocking = ManualExecutor {}; + auto streams = openStandardStreams(loop.loop, blocking, inputOnly(readFd)); + + REQUIRE(::write(writeFd, "ready", 5) == 5); + auto ready = ReadOutcome {}; + blockOnWithin(loop.loop, readInto(streams.input.get(), 64, &ready)); + CHECK(textOf(ready) == "ready"); + + auto parked = ReadOutcome {}; + blockOnWithin( + loop.loop, + core::net::testing::allOf(readInto(streams.input.get(), 64, &parked), + feedLater(&loop.loop, writeFd, "later", std::chrono::milliseconds { 20 }))); + CHECK(textOf(parked) == "later"); + CHECK(endOf(parked) == InputEnd::More); + CHECK(blocking.pending() == 0); +} + +} // namespace + +TEST_CASE("a socket, a pseudo-terminal and a FIFO are Pollable", "[net][standard-streams]") +{ + auto const pair = makeSocketPair(); + CHECK(core::net::classifyStreamHandle(pair.near.get()) == StreamKind::Pollable); + + auto const pty = makePseudoTerminal(); + CHECK(core::net::classifyStreamHandle(pty.terminal.get()) == StreamKind::Pollable); + CHECK(::isatty(pty.terminal.get()) == 1); + + auto const pipe = makeTestPipe(); + CHECK(core::net::classifyStreamHandle(pipe.read.get()) == StreamKind::Pollable); +} + +TEST_CASE("a pipe input reads through the loop, never through the blocking executor, to its end", + "[net][standard-streams]") +{ + auto pipe = makeTestPipe(); + readsThroughTheLoop(pipe.read.get(), pipe.write.get()); + + auto loop = Loop {}; + auto blocking = ManualExecutor {}; + auto streams = openStandardStreams(loop.loop, blocking, inputOnly(pipe.read.get())); + pipe.write.reset(); + auto ended = ReadOutcome {}; + blockOnWithin(loop.loop, readInto(streams.input.get(), 64, &ended)); + CHECK(textOf(ended).empty()); + CHECK(endOf(ended) == InputEnd::Reached); + CHECK(blocking.pending() == 0); +} + +TEST_CASE("a socket input reads through the loop", "[net][standard-streams]") +{ + auto const pair = makeSocketPair(); + readsThroughTheLoop(pair.near.get(), pair.far.get()); +} + +TEST_CASE("a terminal input reads through the loop", "[net][standard-streams]") +{ + auto const pty = makePseudoTerminal(); + readsThroughTheLoop(pty.terminal.get(), pty.controller.get()); +} + +TEST_CASE("the inherited descriptor's O_NONBLOCK is neither set nor cleared", "[net][standard-streams]") +{ + // The open file description is the parent's too: a flag set here is set in its shell. + auto const nonBlocking = GENERATE(0, O_NONBLOCK); + auto const pipe = makeTestPipe(); + auto const before = ::fcntl(pipe.read.get(), F_GETFL); + REQUIRE(before >= 0); + REQUIRE(::fcntl(pipe.read.get(), F_SETFL, (before & ~O_NONBLOCK) | nonBlocking) == 0); + auto const set = ::fcntl(pipe.read.get(), F_GETFL); + + readsThroughTheLoop(pipe.read.get(), pipe.write.get()); + CHECK(::fcntl(pipe.read.get(), F_GETFL) == set); +} + +TEST_CASE("a stop during a pollable read throws, and the bytes are the next read's", + "[net][standard-streams]") +{ + auto const pipe = makeTestPipe(); + auto loop = Loop {}; + auto blocking = ManualExecutor {}; + auto streams = openStandardStreams(loop.loop, blocking, inputOnly(pipe.read.get())); + + auto stopped = ReadOutcome {}; + blockOnWithin(loop.loop, + core::net::testing::anyOf( + readInto(streams.input.get(), 64, &stopped), + core::net::testing::sleepFor(&loop.loop, std::chrono::milliseconds { 20 }))); + CHECK(stopped.isCancelled); + + REQUIRE(::write(pipe.write.get(), "kept", 4) == 4); + auto next = ReadOutcome {}; + blockOnWithin(loop.loop, readInto(streams.input.get(), 64, &next)); + CHECK(textOf(next) == "kept"); +} + +TEST_CASE("a pollable input whose registration the backend refuses is read on the blocking executor", + "[net][standard-streams]") +{ + // macOS's kqueue refuses some terminals with EINVAL; epoll would refuse a regular file with + // EPERM, were the table ever to call one Pollable. + auto const pipe = makeTestPipe(); + auto backend = core::net::testing::ScriptedBackend {}; + backend.refuseNextAttach(); + auto loop = EventLoop { backend }; + auto blocking = ManualExecutor {}; + auto streams = openStandardStreams(loop, blocking, inputOnly(pipe.read.get())); + REQUIRE(core::net::classifyStreamHandle(pipe.read.get()) == StreamKind::Pollable); + + REQUIRE(::write(pipe.write.get(), "first", 5) == 5); + auto first = ReadOutcome {}; + loop.spawn(readInto(streams.input.get(), 64, &first)); + std::ignore = loop.runUntilIdle(); + REQUIRE(blocking.pending() == 1); + blocking.drain(); + std::ignore = loop.runUntilIdle(); + CHECK(textOf(first) == "first"); + + // And it stays Blocking: the backend would take the next registration, but it is not asked. + REQUIRE(::write(pipe.write.get(), "second", 6) == 6); + auto second = ReadOutcome {}; + loop.spawn(readInto(streams.input.get(), 64, &second)); + std::ignore = loop.runUntilIdle(); + REQUIRE(blocking.pending() == 1); + blocking.drain(); + std::ignore = loop.runUntilIdle(); + CHECK(textOf(second) == "second"); +} + +TEST_CASE("a refused input over a non-blocking descriptor waits in the worker, not in the loop", + "[net][standard-streams][threading]") +{ + // The parent made the descriptor non-blocking, and it is not this process's to change back: the + // worker's read finds nothing yet and must wait for the bytes rather than answer EAGAIN. + constexpr auto Budget = std::chrono::seconds { 10 }; + auto pipe = makeTestPipe(); + auto const flags = ::fcntl(pipe.read.get(), F_GETFL); + REQUIRE(::fcntl(pipe.read.get(), F_SETFL, flags | O_NONBLOCK) == 0); + auto backend = core::net::testing::ScriptedBackend {}; + backend.refuseNextAttach(); + auto loop = EventLoop { backend }; + auto pool = core::async::ThreadPoolExecutor { 1 }; + auto streams = openStandardStreams(loop, pool, inputOnly(pipe.read.get())); + // On the way out, a failed REQUIRE's included: the write end closes first, so a worker still + // blocked in its read sees the end and the pool can be joined, rather than hanging the binary. + auto const release = core::net::detail::ScopeGuard { [&]() noexcept { + pipe.write.reset(); + pool.stop(); + } }; + + auto outcome = ReadOutcome {}; + auto isFinished = std::atomic { false }; + auto const flow = [](IInputStream* input, ReadOutcome* out, std::atomic* done) -> Task { + co_await readInto(input, 64, out); + done->store(true, std::memory_order_release); + }; + loop.spawn(flow(streams.input.get(), &outcome, &isFinished)); + // One turn first, so the refusal sends the read to the worker while the pipe is still empty. + std::ignore = loop.runUntilIdle(); + std::this_thread::sleep_for(std::chrono::milliseconds { 50 }); + REQUIRE_FALSE(isFinished.load(std::memory_order_acquire)); + REQUIRE(::write(pipe.write.get(), "eventually", 10) == 10); + + auto const deadline = std::chrono::steady_clock::now() + Budget; + while (!isFinished.load(std::memory_order_acquire) && std::chrono::steady_clock::now() < deadline) + { + if (loop.runUntilIdle() == 0) + std::this_thread::yield(); + } + REQUIRE(isFinished.load(std::memory_order_acquire)); + CHECK(textOf(outcome) == "eventually"); + CHECK(::fcntl(pipe.read.get(), F_GETFL) == (flags | O_NONBLOCK)); +} + +TEST_CASE("a readiness with nothing to read waits again instead of blocking the loop", + "[net][standard-streams]") +{ + // A blocking descriptor the loop calls readable may still have nothing: a spurious wake, or + // another reader. The read is confirmed first; unconfirmed, it would block the loop's thread. + // A watchdog writes after 2 s, so a read that did block ends -- with the watchdog's bytes, + // which the case then refuses -- rather than hanging the binary. + // A pipe, and a terminal: macOS's poll cannot ask a tty (POLLNVAL), so the confirmation falls + // back to select there, and this is the case that holds it to that. + auto const kind = GENERATE(as {}, "pipe", "pseudo-terminal"); + CAPTURE(kind); + auto input = OwnedHandle {}; + auto feeder = OwnedHandle {}; + if (kind == "pipe") + { + auto pipe = makeTestPipe(); + input = std::move(pipe.read); + feeder = std::move(pipe.write); + } + else + { + auto pty = makePseudoTerminal(); + input = std::move(pty.terminal); + feeder = std::move(pty.controller); + } + auto backend = core::net::testing::ScriptedBackend {}; + auto loop = EventLoop { backend }; + auto blocking = ManualExecutor {}; + auto streams = openStandardStreams(loop, blocking, inputOnly(input.get())); + + auto mutex = std::mutex {}; + auto finished = std::condition_variable {}; + auto isDone = false; + auto watchdog = std::thread { [&] { + auto lock = std::unique_lock { mutex }; + if (!finished.wait_for(lock, std::chrono::seconds { 2 }, [&] { return isDone; })) + std::ignore = ::write(feeder.get(), "watchdog", 8); + } }; + auto const joinWatchdog = core::net::detail::ScopeGuard { [&]() noexcept { + { + auto const lock = std::scoped_lock { mutex }; + isDone = true; + } + finished.notify_all(); + watchdog.join(); + } }; + + // One turn at a time, each with the one step the script gives it: the flow parks, then is told + // its descriptor is readable while the pipe is empty, then the bytes really arrive. + // Each step is consumed by exactly one backend wait, and a turn that has ready work may not + // wait at all, so a step is driven until a wait has taken it. + auto const step = [&](auto push) { + auto const consumed = backend.waitCount() + 1; + push(); + // Bounded: a loop with nothing parked returns without asking the backend at all. + for ([[maybe_unused]] auto const attempt: std::views::iota(0, 100)) + { + if (backend.waitCount() >= consumed) + break; + std::ignore = loop.runOnce(core::platform::SteadyDuration::zero()); + } + }; + auto const idle = [&] { + backend.pushTimeout(); + }; + auto outcome = ReadOutcome {}; + loop.spawn(readInto(streams.input.get(), 64, &outcome)); + step(idle); + auto const parked = backend.lastHandlerId(); + REQUIRE(parked); + REQUIRE(backend.attachedCount() > 0); + + auto const started = std::chrono::steady_clock::now(); + step([&] { backend.pushReadable(parked); }); + step(idle); + step(idle); + CHECK(std::chrono::steady_clock::now() - started < std::chrono::seconds { 1 }); + REQUIRE_FALSE(outcome.answer.has_value()); + CHECK(blocking.pending() == 0); + + REQUIRE(::write(feeder.get(), "real", 4) == 4); + step([&] { backend.pushReadable(backend.lastHandlerId()); }); + step(idle); + step(idle); + CHECK(textOf(outcome) == "real"); +} + +TEST_CASE("a write turns the description's SIGPIPE off for good where the system has the flag", + "[net][standard-streams]") +{ + // macOS raises a pipe's SIGPIPE at the process, so blocking it on the writing thread is not + // enough. The description's flag is set once and stays set: a save and a restore around each + // write raced with every other writer of the shared description. +#ifdef F_GETNOSIGPIPE + auto pipe = makeTestPipe(); + auto const byte = std::array { std::byte { 'x' } }; + REQUIRE(core::net::detail::writeStream(pipe.write.get(), byte).has_value()); + CHECK(::fcntl(pipe.write.get(), F_GETNOSIGPIPE) == 1); +#else + SKIP("SIGPIPE goes to the writing thread here, and that thread blocks it"); +#endif +} diff --git a/src/core/net/posix/StreamKindTable.cpp b/src/core/net/posix/StreamKindTable.cpp new file mode 100644 index 00000000..06a7698f --- /dev/null +++ b/src/core/net/posix/StreamKindTable.cpp @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: Apache-2.0 + +/// @file +/// `classifyStreamHandle` on POSIX: `fstat`'s file type, looked up in one table. + +#include + +#include + +#include +#include +#include + +#include + +namespace core::net +{ + +namespace +{ + /// What else a file type needs before it is Pollable. + enum class Admission : std::uint8_t + { + Always, ///< Its type is enough. + TerminalOnly, ///< Only a terminal: a character device that is not one (`/dev/null`) is not. + }; + + /// One file type, and how a stream over it is driven. + struct StreamKindRow + { + mode_t type; ///< `S_IFMT`'s value for it. + StreamKind kind; ///< How it is driven when admitted. + Admission admission; ///< What else it needs. + }; + + /// The file types a standard handle can be. A type not listed -- a regular file, a block device, + /// a directory -- is Blocking: a regular file is always "readable", so the loop can do nothing + /// for it, and epoll refuses one outright with EPERM. + /// + /// A character device is Pollable only as a terminal. `/dev/null` is one, and epoll refuses it + /// too; `/dev/zero` and `/dev/urandom` are always readable, which waiting tells nothing about. + constexpr auto StreamKindTable = std::array { + StreamKindRow { .type = S_IFIFO, .kind = StreamKind::Pollable, .admission = Admission::Always }, + StreamKindRow { .type = S_IFSOCK, .kind = StreamKind::Pollable, .admission = Admission::Always }, + StreamKindRow { .type = S_IFCHR, .kind = StreamKind::Pollable, .admission = Admission::TerminalOnly }, + }; +} // namespace + +StreamKind classifyStreamHandle(platform::NativeHandle handle) noexcept +{ + struct stat status {}; + if (::fstat(handle, &status) != 0) + return StreamKind::Blocking; + auto const type = static_cast(status.st_mode & S_IFMT); + auto const row = std::ranges::find(StreamKindTable, type, &StreamKindRow::type); + if (row == StreamKindTable.end()) + return StreamKind::Blocking; + if (row->admission == Admission::TerminalOnly && ::isatty(handle) != 1) + return StreamKind::Blocking; + return row->kind; +} + +} // namespace core::net diff --git a/src/core/net/windows/StandardStreamPrimitives.cpp b/src/core/net/windows/StandardStreamPrimitives.cpp new file mode 100644 index 00000000..ea8c5159 --- /dev/null +++ b/src/core/net/windows/StandardStreamPrimitives.cpp @@ -0,0 +1,132 @@ +// SPDX-License-Identifier: Apache-2.0 + +/// @file +/// The Windows standard-stream primitives: synchronous `ReadFile` and `WriteFile`, and the +/// `CancelSynchronousIo` a stop sends to a worker blocked in a read. + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace core::net::detail +{ + +namespace +{ + /// One Win32 error with a class of its own; every other one is @c NetErrorCode::SystemError. + struct StreamErrorRow + { + DWORD error; + NetErrorCode code; + }; + + constexpr auto StreamErrorTable = std::array { + StreamErrorRow { .error = ERROR_INVALID_HANDLE, .code = NetErrorCode::BadHandle }, + StreamErrorRow { .error = ERROR_ACCESS_DENIED, .code = NetErrorCode::PermissionDenied }, + StreamErrorRow { .error = ERROR_NOT_ENOUGH_MEMORY, .code = NetErrorCode::ResourceExhausted }, + StreamErrorRow { .error = ERROR_OUTOFMEMORY, .code = NetErrorCode::ResourceExhausted }, + StreamErrorRow { .error = ERROR_NO_SYSTEM_RESOURCES, .code = NetErrorCode::ResourceExhausted }, + // Only `ReadingThread::interrupt` cancels a stream's synchronous call. + StreamErrorRow { .error = ERROR_OPERATION_ABORTED, .code = NetErrorCode::Cancelled }, + }; + + /// The errors that end a read's input rather than fail it: a pipe whose writer closed, a file + /// read at its end. + constexpr auto EndOfInputErrors = std::array { ERROR_BROKEN_PIPE, ERROR_HANDLE_EOF }; + + /// @return @p error, classified by the table. + [[nodiscard]] NetError streamError(DWORD error, char const* what) + { + auto const row = std::ranges::find(StreamErrorTable, error, &StreamErrorRow::error); + auto const code = row == StreamErrorTable.end() ? NetErrorCode::SystemError : row->code; + return makeNetError(code, static_cast(error), std::string { what }); + } + + /// @return @p size, as much of it as one call takes. + [[nodiscard]] DWORD chunkOf(std::size_t size) noexcept + { + return static_cast(std::min(size, std::numeric_limits::max())); + } +} // namespace + +std::expected readStream(platform::NativeHandle handle, + std::span into, + [[maybe_unused]] ReadWait wait) +{ + // A synchronous handle has no "nothing yet": every read blocks, whatever @p wait says. + auto got = DWORD { 0 }; + if (ReadFile(handle, into.data(), chunkOf(into.size()), &got, nullptr) != 0) + return static_cast(got); + auto const error = GetLastError(); + if (std::ranges::find(EndOfInputErrors, error) != EndOfInputErrors.end()) + return std::size_t { 0 }; + return std::unexpected(streamError(error, "ReadFile")); +} + +std::expected writeStream(platform::NativeHandle handle, + std::span bytes) +{ + auto written = std::size_t { 0 }; + while (written < bytes.size()) + { + auto const rest = bytes.subspan(written); + auto put = DWORD { 0 }; + if (WriteFile(handle, rest.data(), chunkOf(rest.size()), &put, nullptr) == 0) + { + auto const error = GetLastError(); + if (written > 0) + return written; + return std::unexpected(streamError(error, "WriteFile")); + } + // A success that moved nothing would loop for ever: a pipe in PIPE_NOWAIT mode with a full + // buffer answers so. Reported as what was written, or as the failure it is. + if (put == 0) + { + if (written > 0) + return written; + return std::unexpected( + makeNetError(NetErrorCode::SystemError, 0, "WriteFile: the handle took no bytes")); + } + written += put; + } + return written; +} + +ReadReadiness readReadinessNow([[maybe_unused]] platform::NativeHandle handle) noexcept +{ + // No Windows handle is Pollable (windows/StreamKindTable.cpp), so nothing asks. + return ReadReadiness::Ready; +} + +ReadingThread::ReadingThread() noexcept +{ + auto thread = HANDLE {}; + // THREAD_TERMINATE is the access CancelSynchronousIo needs. + if (DuplicateHandle( + GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(), &thread, THREAD_TERMINATE, FALSE, 0) + != 0) + _thread = thread; +} + +ReadingThread::~ReadingThread() +{ + if (_thread != platform::InvalidHandle) + CloseHandle(_thread); +} + +void ReadingThread::interrupt() noexcept +{ + // ERROR_NOT_FOUND when the read has not started or has just returned: nothing to cancel. + if (_thread != platform::InvalidHandle) + CancelSynchronousIo(_thread); +} + +} // namespace core::net::detail diff --git a/src/core/net/windows/StandardStreamsTestSupport.cpp b/src/core/net/windows/StandardStreamsTestSupport.cpp new file mode 100644 index 00000000..2a1d6fe2 --- /dev/null +++ b/src/core/net/windows/StandardStreamsTestSupport.cpp @@ -0,0 +1,73 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The Windows handles of StandardStreamsTestSupport.hpp. +#include + +#include +#include + +#include + +namespace core::net::streams_test +{ + +namespace +{ + /// @return @p handle owned, or a throw naming @p what where it is invalid. + [[nodiscard]] OwnedHandle ownedOrThrow(HANDLE handle, char const* what) + { + if (handle == INVALID_HANDLE_VALUE || handle == nullptr) + throw std::system_error(static_cast(GetLastError()), std::system_category(), what); + return OwnedHandle { handle }; + } + + /// @return @p path opened with @p access and @p disposition, shared for reading and writing. + [[nodiscard]] OwnedHandle openFile(wchar_t const* path, DWORD access, DWORD disposition, char const* what) + { + return ownedOrThrow(CreateFileW(path, + access, + FILE_SHARE_READ | FILE_SHARE_WRITE, + nullptr, + disposition, + FILE_ATTRIBUTE_NORMAL, + nullptr), + what); + } +} // namespace + +TestPipe makeTestPipe() +{ + auto read = HANDLE {}; + auto write = HANDLE {}; + // CreatePipe's pipe is synchronous, as the anonymous pipe a parent hands its child is. + if (CreatePipe(&read, &write, nullptr, 0) == 0) + throw std::system_error(static_cast(GetLastError()), std::system_category(), "CreatePipe"); + return TestPipe { .read = OwnedHandle { read }, .write = OwnedHandle { write } }; +} + +OwnedHandle openForReading(std::filesystem::path const& path) +{ + return openFile(path.c_str(), GENERIC_READ, OPEN_EXISTING, "open for reading"); +} + +OwnedHandle openForWriting(std::filesystem::path const& path) +{ + return openFile(path.c_str(), GENERIC_WRITE, CREATE_ALWAYS, "open for writing"); +} + +OwnedHandle openNullDevice() +{ + return openFile(L"NUL", GENERIC_READ, OPEN_EXISTING, "open NUL"); +} + +StreamKind pipeStreamKind() noexcept +{ + return StreamKind::Blocking; +} + +RunningReadStop runningReadStop() noexcept +{ + return RunningReadStop::Cancels; +} + +} // namespace core::net::streams_test diff --git a/src/core/net/windows/StreamKindTable.cpp b/src/core/net/windows/StreamKindTable.cpp new file mode 100644 index 00000000..133ce586 --- /dev/null +++ b/src/core/net/windows/StreamKindTable.cpp @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: Apache-2.0 + +/// @file +/// `classifyStreamHandle` on Windows: `GetFileType`, looked up in one table. + +#include + +#include +#include + +#include + +namespace core::net +{ + +namespace +{ + /// One file type, and how a stream over it is driven. + struct StreamKindRow + { + DWORD type; ///< What `GetFileType` answers. + StreamKind kind; ///< How it is driven. + }; + + /// Every row is Blocking, each for its own reason, and written down so the reason is not lost + /// the day one of them could be driven by the loop. A type not listed (`FILE_TYPE_UNKNOWN`, an + /// absent or invalid handle) is Blocking too. + constexpr auto StreamKindTable = std::array { + // A console (or `NUL`): a console handle cannot be associated with a completion port, and + // waiting on its signalled state wakes for mouse and focus events a read would block on. + StreamKindRow { .type = FILE_TYPE_CHAR, .kind = StreamKind::Blocking }, + // A file: always readable, so there is nothing to wait for. + StreamKindRow { .type = FILE_TYPE_DISK, .kind = StreamKind::Blocking }, + // A pipe (a socket too): an inherited anonymous pipe is synchronous, and a handle opened + // without FILE_FLAG_OVERLAPPED cannot be reopened as overlapped by its child. + StreamKindRow { .type = FILE_TYPE_PIPE, .kind = StreamKind::Blocking }, + }; +} // namespace + +StreamKind classifyStreamHandle(platform::NativeHandle handle) noexcept +{ + auto const type = GetFileType(handle); + auto const row = std::ranges::find(StreamKindTable, type, &StreamKindRow::type); + if (row == StreamKindTable.end()) + return StreamKind::Blocking; + return row->kind; +} + +} // namespace core::net From 4fd593ae73be39c83507d2ef0830a4cd54aef66e Mon Sep 17 00:00:00 2001 From: Christian Parpart Date: Fri, 27 Nov 2026 00:01:34 +0100 Subject: [PATCH 09/19] feat(net)!: fail-closed TLS clients, trust stores and platform chain verifiers WrapClient fails closed, with SNI, ALPN, a session seam and failure classification. ITlsContext::wrapClient(inner, executor, TlsPeer) binds one client connection to the host it was dialled for. The default refuses a non-empty server name with Unsupported rather than drop it, so a context with no per-connection check, the pinned-name makeTlsClientContext included, never hands back a connection unverified for the host asked for. makeTlsClientContext(TrustAnchors, TlsClientOptions) is the verifying client that honours it: a DNS name is sent as SNI and checked (no partial wildcards); an IP literal, bracketed or not, sends no SNI and is checked against the IP subjectAltNames; an empty name verifies the chain alone. No option disables verification. trustAnchorsFromPem reads a PEM bundle into anchors. ISocket::tlsSession() (null by default, forwarded by SocketDecorator and SplitSocket) is how code without net_tls reads ITlsSession; tlsSessionOf is now that call, so it sees through forwarding decorators. ITlsSession gains failure() -- Certificate when the checked verification refused the peer, AlertReceived with the alert byte, otherwise Protocol -- and negotiatedProtocol() for ALPN. TlsOptions::alpn is a server's selection list (refusing no overlap with no_application_protocol) and what a pinned-name client offers. StrictTlsPeer takes StrictTlsPeerOptions (version, ALPN, an alert to refuse with) and reports the SNI it received; expiredCopyOf backdates a certificate for the expiry case. BREAKING: StrictTlsPeer::client/server take StrictTlsPeerOptions instead of a TlsVersion, and tlsSessionOf answers through forwarding decorators. Trust stores, platform chain verifiers and system client contexts. makeTlsClientContext takes a TrustSource: TrustAnchors, which OpenSSL checks during the handshake, or an IChainVerifier, asked after the handshake and before any application byte moves. With a verifier the TLS socket's state is one SessionState {Handshaking, Verifying, Established, Failed}: reads, writes and handshakeIfNeeded wait while it verifies, and a refusal is a sticky Failed whose failure() is Certificate. The chain is read with SSL_get_peer_cert_chain and the verifier is asked about the name as the certificate check reads it (no brackets, no zone). TrustStore.hpp adds ITrustStore, makePemTrustStore, and makeFileTrustStore: SSL_CERT_FILE, then SSL_CERT_DIR (one hashed directory), then the first existing row of trustBundleLocations(), a data table that now includes FreeBSD's ca_root_nss bundle and hashed /etc/ssl/certs. Files are read through async::offload, and every failure is a refusal: a named but missing file, an empty store, an unreadable or malformed file, a non-regular file. makeSystemTlsClientContext is one CMake-selected SystemTrust.cpp: Security.framework's SecTrustEvaluateWithError on macOS, CertGetCertificateChain with the SSL chain policy on Windows (both offloaded; Security/CoreFoundation and crypt32 linked PRIVATE), the file store elsewhere. BREAKING: makeTlsClientContext(TrustAnchors const&, TlsClientOptions const&) is replaced by makeTlsClientContext(TrustSource, TlsClientOptions const& = {}); TrustAnchors converts to it. IChainVerifier::verify finishes on the verifier's own executor. A verification runs detached, and may outlive the socket that asked and that socket's loop, so verify() resumes on no loop at all: it finishes on the blocking executor the platform verifiers are built from, and settles the socket's parked wait, which is handed back to the loop that socket runs on. One verifier therefore serves sockets on several loops, and a socket and loop torn down after a stopped handshake are never touched. A full verification budget is ResourceExhausted, not WouldBlock, and leaves the socket to be driven again. Also in this commit: - TLS failures are classified, and peer names checked - a handshake failure is classified when its alert cannot be flushed - the unflushable-alert case breaks the transport by state, not by write count - a session is trusted only once established; the name check, size caps and verifier tests - build GCC 14's trust-store table case without a conditional over initializer lists - what OpenSSL 3.0 and macOS report, in the TLS peer cases - clang-tidy analyses the Windows TLS sources under clang-cl too - a stop ends a TLS socket's wait for its chain verifier - the platform chain verifiers never fetch what a certificate names - a verifying client context refuses an empty server name - reach a TLS case's session through a checked helper Signed-off-by: Christian Parpart --- .agent/reference/provenance.md | 17 + .github/workflows/build.yml | 33 +- docs/modules/net.md | 9 +- src/core/net/CMakeLists.txt | 32 +- src/core/net/ChainVerifierTestSupport.hpp | 118 ++ src/core/net/ExecutorAddressResolver.cpp | 30 +- src/core/net/ISocket.hpp | 10 + src/core/net/ITlsContext.hpp | 46 + src/core/net/ITlsSession.hpp | 66 +- src/core/net/SocketEndpoints_test.cpp | 74 ++ src/core/net/SplitSocket.hpp | 4 + src/core/net/Tls.cpp | 828 ++++++++++++- src/core/net/Tls.hpp | 155 ++- src/core/net/TlsPeer_test.cpp | 832 +++++++++++++ src/core/net/TlsSession_test.cpp | 8 +- src/core/net/TlsTestSupport.hpp | 168 +++ src/core/net/TrustStore.cpp | 241 ++++ src/core/net/TrustStore.hpp | 153 +++ src/core/net/TrustStore_test.cpp | 1055 +++++++++++++++++ src/core/net/darwin/DarwinChainVerifier.cpp | 182 +++ src/core/net/darwin/DarwinChainVerifier.hpp | 33 + .../net/darwin/DarwinChainVerifier_test.cpp | 28 + src/core/net/darwin/SystemTrust.cpp | 33 + src/core/net/detail/Alpn.hpp | 79 ++ src/core/net/detail/InFlightBudget.hpp | 43 + src/core/net/detail/ParkedCall.hpp | 41 +- src/core/net/detail/ParkedCall_test.cpp | 52 + src/core/net/posix/SystemTrust.cpp | 36 + src/core/net/testing/SocketDecorator.hpp | 7 +- src/core/net/testing/StrictTlsPeer.cpp | 134 ++- src/core/net/testing/StrictTlsPeer.hpp | 47 +- src/core/net/windows/SystemTrust.cpp | 34 + src/core/net/windows/WindowsChainVerifier.cpp | 180 +++ src/core/net/windows/WindowsChainVerifier.hpp | 27 + .../net/windows/WindowsChainVerifier_test.cpp | 32 + 35 files changed, 4723 insertions(+), 144 deletions(-) create mode 100644 src/core/net/ChainVerifierTestSupport.hpp create mode 100644 src/core/net/TlsPeer_test.cpp create mode 100644 src/core/net/TlsTestSupport.hpp create mode 100644 src/core/net/TrustStore.cpp create mode 100644 src/core/net/TrustStore.hpp create mode 100644 src/core/net/TrustStore_test.cpp create mode 100644 src/core/net/darwin/DarwinChainVerifier.cpp create mode 100644 src/core/net/darwin/DarwinChainVerifier.hpp create mode 100644 src/core/net/darwin/DarwinChainVerifier_test.cpp create mode 100644 src/core/net/darwin/SystemTrust.cpp create mode 100644 src/core/net/detail/Alpn.hpp create mode 100644 src/core/net/detail/InFlightBudget.hpp create mode 100644 src/core/net/posix/SystemTrust.cpp create mode 100644 src/core/net/windows/SystemTrust.cpp create mode 100644 src/core/net/windows/WindowsChainVerifier.cpp create mode 100644 src/core/net/windows/WindowsChainVerifier.hpp create mode 100644 src/core/net/windows/WindowsChainVerifier_test.cpp diff --git a/.agent/reference/provenance.md b/.agent/reference/provenance.md index 4b94e388..9981259c 100644 --- a/.agent/reference/provenance.md +++ b/.agent/reference/provenance.md @@ -259,6 +259,7 @@ others in notes. | `src/core/net/AcceptLoopHealth.cpp` | origin: core-cpp | - | - | graduated from LASTRADA-Software/fastcached `src/FastCache/Transport/AcceptLoopHealth.cpp` at `a11f0c1a37ab317bd1dd7e9c82f2c4a78a5a4b55`, a commit not yet on its master: the row moves to that upstream once it is, [core-cpp#60](https://github.com/contour-terminal/core-cpp/issues/60); 0.6.0: camelBack; it records degraded loops as well as ones that gave up, removes a degraded one on recovery, and takes the accept loop's reports whole (`record`) where upstream had `Stopped(surface, reason)` | | `src/core/net/AcceptLoopHealth_test.cpp` | origin: core-cpp | - | - | graduated from LASTRADA-Software/fastcached `src/FastCache/Transport/AcceptLoopHealth_test.cpp` at `a11f0c1a37ab317bd1dd7e9c82f2c4a78a5a4b55`, a commit not yet on its master: the row moves to that upstream once it is, [core-cpp#60](https://github.com/contour-terminal/core-cpp/issues/60); 0.6.0: camelBack; it records degraded loops as well as ones that gave up, removes a degraded one on recovery, and takes the accept loop's reports whole (`record`) where upstream had `Stopped(surface, reason)` | | `src/core/net/CancelRead_test.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/CancelRead_test.cpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B6. Upstream's three cases, re-driven over `testing::BackendMatrix` and a socket pair on one loop rather than a blocking connector and threads -- which makes the park arranged rather than waited for. Each asserts that something really parked, so it cannot degenerate into the synchronous arm and pass having tested nothing | +| `src/core/net/ChainVerifierTestSupport.hpp` | origin: core-cpp | - | - | P13 Task 13 fix round 1: the refusals every platform chain verifier must make, as one table | | `src/core/net/ClockRefresh_test.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Async/ReactorClockRefresh_test.cpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B4. Rewritten into one case per refresh: upstream asserted only that a cached clock advanced at all, which passes with the pre-wait refresh removed. Here step 3's refresh is asserted through the TIMEOUT the backend is handed and step 5's through the turn a deadline fires in, so neither can be deleted without a red. Over `ScriptedBackend` rather than a platform reactor, so the clock moves by exactly what the loop asked to wait | | `src/core/net/ClosedParkIdle_test.cpp` | origin: core-cpp | - | - | v0.2.0: a turn that queues the waiters of a closed handle is not idle, so one `runUntilIdle` resolves an accept or a read parked on a handle that closes | | `src/core/net/CloseResumesThroughLoop_test.cpp` | origin: core-cpp | - | - | v0.2.1: close() and cancelRead() settle at once and the loop resumes (G2); contour's NativeClient::detach crash as a case | @@ -282,6 +283,11 @@ others in notes. | `src/core/net/SocketOption.cpp` | origin: core-cpp | - | - | P13 Task 9: the one interpreter of the option rows | | `src/core/net/TcpSocket.cpp` | origin: core-cpp | - | - | P13 Task 9: the `ITcpSocket` lifecycle, written once over the per-platform primitives | | `src/core/net/TcpSocket_test.cpp` | origin: core-cpp | - | - | P13 Task 9 | +| `src/core/net/darwin/DarwinChainVerifier.cpp` | origin: core-cpp | - | - | P13 Task 13: the macOS chain verifier, `SecTrustEvaluateWithError` with the SSL server policy, offloaded | +| `src/core/net/darwin/DarwinChainVerifier.hpp` | origin: core-cpp | - | - | P13 Task 13: its private factory | +| `src/core/net/darwin/DarwinChainVerifier_test.cpp` | origin: core-cpp | - | - | P13 Task 13 fix round 1: the macOS verifier refuses `ChainVerifierTestSupport.hpp`'s table | +| `src/core/net/darwin/SystemTrust.cpp` | origin: core-cpp | - | - | P13 Task 13: `makeSystemTlsClientContext` on macOS, over the platform verifier | +| `src/core/net/detail/Alpn.hpp` | origin: core-cpp | - | - | P13 Task 12: ALPN wire format and a server's choice, shared by the TLS layer and `StrictTlsPeer` | | `src/core/net/detail/SocketOptionAccess.hpp` | origin: core-cpp | - | - | P13 Task 9: option reads and writes through the rows, and the `int`-option calls beneath them | | `src/core/net/detail/TcpSocketPrimitives.hpp` | origin: core-cpp | - | - | P13 Task 9: socket creation, `bind` and `listen`, defined per platform | | `src/core/net/posix/PosixTcpSocket.cpp` | origin: core-cpp | - | - | P13 Task 9 | @@ -327,6 +333,7 @@ others in notes. | `src/core/net/detail/SshWire.hpp` | origin: core-cpp | - | - | the bounds-checked SSH wire reader and writer (RFC 4251 §5) `SshKeys.cpp` and the software security key share | | `src/core/net/posix/SshAgentEndpoint.cpp` | origin: core-cpp | - | - | the ssh-agent endpoint on POSIX: SSH_AUTH_SOCK, dialled as a Unix socket | | `src/core/net/posix/SshAgentEndpoint_test.cpp` | origin: core-cpp | - | - | defaultSshAgentEndpoint reading SSH_AUTH_SOCK through a fake environment | +| `src/core/net/posix/SystemTrust.cpp` | origin: core-cpp | - | - | P13 Task 13: `makeSystemTlsClientContext` on every POSIX system but macOS, over the file trust store | | `src/core/net/testing/SoftwareSecurityKey.cpp` | origin: core-cpp | - | - | a FIDO authenticator in software: OpenSSL signing the PROTOCOL.u2f layout, since `ssh-keygen` makes `sk-` signatures only with a device | | `src/core/net/testing/SoftwareSecurityKey.hpp` | origin: core-cpp | - | - | the software authenticator's interface, with no OpenSSL type | | `src/core/net/testdata/ssh/README.md` | origin: core-cpp | - | - | how the SSH fixtures were made | @@ -341,6 +348,10 @@ others in notes. | `src/core/net/testdata/ssh/message.txt` | origin: core-cpp | - | - | an ssh-keygen-made fixture of `SshKeys_test.cpp`; commands in `testdata/ssh/README.md` | | `src/core/net/windows/SshAgentEndpoint.cpp` | origin: core-cpp | - | - | the ssh-agent endpoint on Windows: the Win32-OpenSSH pipe, dialled with connectNamedPipe | | `src/core/net/windows/SshAgentEndpoint_test.cpp` | origin: core-cpp | - | - | defaultSshAgentEndpoint naming the Win32-OpenSSH pipe | +| `src/core/net/windows/SystemTrust.cpp` | origin: core-cpp | - | - | P13 Task 13: `makeSystemTlsClientContext` on Windows, over the platform verifier | +| `src/core/net/windows/WindowsChainVerifier.cpp` | origin: core-cpp | - | - | P13 Task 13: the Windows chain verifier, `CertGetCertificateChain` and `CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL)`, offloaded | +| `src/core/net/windows/WindowsChainVerifier.hpp` | origin: core-cpp | - | - | P13 Task 13: its private factory | +| `src/core/net/windows/WindowsChainVerifier_test.cpp` | origin: core-cpp | - | - | P13 Task 13 fix round 1: the Windows verifier refuses `ChainVerifierTestSupport.hpp`'s table | | `src/core/PosixRandom.cpp` | origin: core-cpp | - | - | `getentropy()` in chunks of at most 256 bytes: Linux, Apple, the BSDs, illumos and Emscripten; its header is chosen by `__has_include()` (Apple, illumos), else `` | | `src/core/platform/Clock.cpp` | origin: core-cpp | - | - | `defaultSystemWallClock()`'s instance, out of line so that a shared build has one | | `src/core/platform/PlatformTestSupport.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): `runsUnderWine` for the platform tests | @@ -399,7 +410,12 @@ others in notes. | `src/core/net/TlsContext_test.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/TlsContext_test.cpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B11: onto core-cpp's factories; certificates generated at run time rather than read from `testdata/tls/`, whose committed certificate expires; plus the common-name, chain, file-loading, `wrapTls` and `constantTimeEquals` cases | | `src/core/net/TlsLifetime_test.cpp` | origin: core-cpp | - | - | Task B11 fix round 1: the handshake and flush gates under a destroyed socket, a waiter that drops it, a stop token and `cancelRead` | | `src/core/net/TlsSocket_test.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/TlsSocket_test.cpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B11: the `WaitReadable` cases (#712) and the handshake over non-TLS input, over a real socket pair driven by the loop instead of hand-pumped pipes; plus the half-close, eager-handshake, stale-error-queue and single-flush cases | +| `src/core/net/TlsPeer_test.cpp` | origin: core-cpp | - | - | P13 Task 12: `wrapClient` fails closed -- SNI, IP-literal authorities, the verification failure classes, alerts, ALPN, the session seam | | `src/core/net/TlsSession_test.cpp` | origin: core-cpp | - | - | minimum version, channel binding, peer fingerprint, `sshStyleFingerprint` | +| `src/core/net/TlsTestSupport.hpp` | origin: core-cpp | - | - | P13 Task 12: `TlsLoopback`, a TLS socket against a `StrictTlsPeer` over a real socket pair, and the bounded two-ended handshake; Task 13: `ScriptedChainVerifier` | +| `src/core/net/TrustStore.cpp` | origin: core-cpp | - | - | P13 Task 13: the PEM and file trust stores and the trust-location table | +| `src/core/net/TrustStore.hpp` | origin: core-cpp | - | - | P13 Task 13: `ITrustStore`, `makePemTrustStore`, `makeFileTrustStore`, `trustBundleLocations`, `makeSystemTlsClientContext` | +| `src/core/net/TrustStore_test.cpp` | origin: core-cpp | - | - | P13 Task 13: trust fails closed -- the file store, the table, and verifier-checked clients | | `src/core/net/WaitReadable_test.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/WaitReadable_test.cpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B6: the #677 count semantics, over every backend. Upstream's off-thread flag machinery is gone -- both ends live on one loop, so the ordering is arranged. Upstream's MEASURED abortive-close case is deliberately not carried over: it records platform behaviour rather than asserting a contract, and core-cpp has no `SO_LINGER` fixture | | `src/core/net/WithTimeout.hpp` | contour-terminal/contour | `src/net/WithTimeout.hpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | namespaces and includes only | | `src/core/net/WithTimeout_test.cpp` | origin: core-cpp | - | - | Task B10: `withTimeout` over a real socket read, and what a lost race leaves in the read slot and the reader | @@ -412,6 +428,7 @@ others in notes. | `src/core/net/detail/ParkedCall.hpp` | origin: core-cpp | - | - | P13 Task 7: `ParkedCall`, extracted from `ThreadedAddressResolver.cpp` and shared with `ExecutorAddressResolver` | | `src/core/net/detail/SocketEndpoint.hpp` | origin: core-cpp | - | - | P13 Task 8: `getsockname`/`getpeername` into a `ResolvedEndpoint`, defined per platform | | `src/core/net/detail/ParkedCall_test.cpp` | origin: core-cpp | - | - | P13 Task 7 fix round 1: first answer wins, the late answer kept and taken once | +| `src/core/net/detail/InFlightBudget.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): `reserveSlot`, the in-flight cap shared by the resolver and the chain verifiers | | `src/core/net/detail/ParkId.hpp` | origin: core-cpp | - | - | Task B13: `ParkId` and its hash, moved out of `detail/ParkTable.hpp` so that `IoAwaitable.hpp` -- and so `ISocket.hpp` -- no longer includes the park table for one strong integer (core-cpp#43) | | `src/core/net/detail/ParkTable.hpp` | origin: core-cpp | - | - | Task B4: `ParkId`, `ParkEntry` and the table. fastcached had no unified one -- a submission queue, a timer heap and each reactor's own descriptor map -- and cancellation therefore meant something slightly different in each. One table, one id space that never wraps, and the id IS the generation check: a cancel for a park that has gone resolves to nothing Task B13: `ParkId` moves out to `detail/ParkId.hpp` Parity lane (v0.2.0): the parks are keyed in `ParkMap`, an open-addressing table with backward-shift deletion, instead of `std::unordered_map`; taken parks are recycled; a park on a handle's lifetime registration points at its `HandleWatch` rather than being filed by handle, and `fileByHandle` files one displaced from its slot | | `src/core/net/detail/ParkTable_test.cpp` | origin: core-cpp | - | - | Parity lane (v0.2.0): `ParkMap` against `std::unordered_map`, the zero id it must refuse, and park recycling; 0.4.3 (core-cpp#52): resident parks -- ids per operation, idle parks uncounted, slots freed with their watch or their last operation | diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 478fef1c..61cfeafc 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -897,6 +897,12 @@ jobs: name: windows (clang-tidy) runs-on: windows-2025 timeout-minutes: 60 + # core::net_tls is configured in, so its `windows/` sources (the system trust and the chain + # verifier) are in the database and counted; without it the script refuses 81 of 84. OpenSSL + # comes from vcpkg as in the cl-release-tls leg, sharing that leg's binary archives. + env: + VCPKG_COMMIT: e6f9e70a29a3e80a1fc510d8503304315447112f + VCPKG_ARCHIVES: ${{ github.workspace }}/.cache/vcpkg-archives steps: - uses: actions/checkout@v7 with: @@ -933,6 +939,30 @@ jobs: test -x "$tidy" || { echo "::error::the clang-tidy wheel has no $tidy"; exit 1; } echo "CLANG_TIDY_EXE=$tidy" >> "$GITHUB_ENV" + - name: Cache vcpkg binary archives + uses: actions/cache@v6 + with: + path: .cache/vcpkg-archives + key: vcpkg-archives-x64-windows-${{ env.VCPKG_COMMIT }}-${{ hashFiles('.github/vcpkg/vcpkg.json') }} + restore-keys: vcpkg-archives-x64-windows-${{ env.VCPKG_COMMIT }}- + + - name: vcpkg + uses: lukka/run-vcpkg@v11 + with: + vcpkgGitCommitId: ${{ env.VCPKG_COMMIT }} + + # As in the windows matrix: run-vcpkg's x-gha provider is gone, so a files provider in the + # cached directory replaces it. + - name: Use vcpkg's toolchain and binary archives + run: | + archives="${VCPKG_ARCHIVES//\\//}" + mkdir -p "$archives" + root="${VCPKG_ROOT//\\//}" + workspace="${GITHUB_WORKSPACE//\\//}" + echo "VCPKG_BINARY_SOURCES=clear;files,$archives,readwrite" >> "$GITHUB_ENV" + echo "TOOLCHAIN_FILE=$root/scripts/buildsystems/vcpkg.cmake" >> "$GITHUB_ENV" + echo "VCPKG_MANIFEST=$workspace/.github/vcpkg" >> "$GITHUB_ENV" + - name: MSVC developer environment uses: ilammy/msvc-dev-cmd@v1 @@ -944,7 +974,8 @@ jobs: # linkage findings). So the one target that generates them is built, and nothing else. - name: Configure, and generate libunicode's headers run: | - cmake --preset clangcl-release "-DCMAKE_CXX_COMPILER=$CXX_COMPILER_PATH" + cmake --preset clangcl-release "-DCMAKE_CXX_COMPILER=$CXX_COMPILER_PATH" -DCORE_CPP_WITH_TLS=ON \ + "-DCMAKE_TOOLCHAIN_FILE=$TOOLCHAIN_FILE" "-DVCPKG_MANIFEST_DIR=$VCPKG_MANIFEST" cmake --build out/build/clangcl-release --target unicode_ucd - name: clang-tidy over the clang-cl compile database diff --git a/docs/modules/net.md b/docs/modules/net.md index f75def5e..87fa22cb 100644 --- a/docs/modules/net.md +++ b/docs/modules/net.md @@ -42,7 +42,7 @@ directory `src/core/net/`. Three targets: | `` | `IoBackend`, the injected blocking wait the loop drives and the readiness dispatcher behind it: `ReadinessHandler` (a handle, an owner and the callbacks a backend invokes), `Interest`, `HandleKind`, `Readiness`, `selectReadinessCallback()`, `BackendKind`, `WaitResult`; and the factories `makeDefaultBackend()`, `makeBackend(BackendKind)` and `preferredBackendKind()`. Every backend's own header is private, so the factories are how a program gets one: poll(2) on POSIX, epoll on Linux, kqueue on macOS and the BSDs, and on Windows an I/O completion port, which `preferredBackendKind()` answers since Task B7b and which is Windows' only backend since 0.5.0: the `WSAEventSelect` + `WaitForMultipleObjects` one it replaced was removed ([core-cpp#6](https://github.com/contour-terminal/core-cpp/issues/6)). `completionPort()` answers non-null on a completion-based backend and `nullptr` on every other, which is how a socket factory knows whether to hand out a socket that issues overlapped operations or one that parks on readiness; `EventLoop::completionPort()` asks it for them. `HandleKind::Completion` is a park on an overlapped operation an owner issued, which is how a completion reaches the loop's turn | | `` | `IHostScheduler::callAfter()`, the one thing a host event loop has to lend core-cpp's, and `HostCallback` | | `` | `HostDrivenBackend`: the backend for a loop that is PUMPED rather than one that blocks. It has no readiness (`attach` and `setInterest` answer `Unsupported`), its `wait()` never blocks, `wake()` and `armWakeAt()` ask the host for a pump and coalesce, and `isHostDriven()` is true. Portable, and the browser is only one of its hosts | -| ``, `` | the transport interfaces. `read`, `readWithFd`, `write`, `writeVectored`, `waitReadable`, `handshakeIfNeeded`, `cancelRead`, `shutdownWrite`, `setReceiveDeadline`, `close`; `accept`, `boundPort`, `close` and `closeToken` -- a listener's `close()` is the base class's, fires the token (as its destructor does) and runs the implementation's `doClose()`. Every operation is a frame-free, stop-aware awaitable, not a `Task` | +| ``, `` | the transport interfaces. `read`, `readWithFd`, `write`, `writeVectored`, `waitReadable`, `handshakeIfNeeded`, `cancelRead`, `shutdownWrite`, `setReceiveDeadline`, `tlsSession` (null but for a TLS socket, forwarded by every decorator), `close`; `accept`, `boundPort`, `close` and `closeToken` -- a listener's `close()` is the base class's, fires the token (as its destructor does) and runs the implementation's `doClose()`. Every operation is a frame-free, stop-aware awaitable, not a `Task` | | `` | `ResultAwaitable` and its byte-count alias `IoAwaitable`: what a socket operation resolves through, and why it allocates nothing. `core::async::asTask` is the escape hatch for a caller that must store one | | `` | `core::net::contract` — the socket contract's tripwires: `claimReadSlot` and `claimWriteSlot`, which end the process in every build, and the Debug assertions `requireReadBuffer` and `assertTeardownIsSerialisedWithDispatch`; public so a transport outside this library gets them too | | `` | `listen()`, `connect()`, `listenUnix()`, `connectUnix()`, `adoptFd()`, `appendReadChunk()` | @@ -68,9 +68,10 @@ directory `src/core/net/`. Three targets: | `` | `FailingListener`, an `IListener` decorator whose first accepts answer scripted `NetError`s and then accept from the listener it decorates, owned or not; `repeatedFailures()` | | ``, `` | `SocketDecorator`, which forwards every verb so a double overrides only the one it stages; `ParkingReadableSocket` and `ParkingWritableSocket`, which park until the test decides and count how each parked operation ended | | `` | `setDiagnosticSink()`: where a failure nobody can be handed goes (a wait that fails mid-sweep); discarded by default | -| `` (`core::net`) | `ITlsContext`, the seam a TLS implementation plugs in behind, and `wrapTls(socket, context, loop)`, which hands a socket back unchanged for a null context -- so an accept path compiles identically in a build without TLS | -| `` (`core::net_tls`) | a TLS `ISocket` over any other, driven through memory BIOs on the same loop, with an eager `handshakeIfNeeded()`, a `waitReadable()` that tells `close_notify` from data and a `shutdownWrite()` that sends `close_notify` before the FIN; `makeTlsServerContext()` and `makeTlsServerContextFromFiles()` (a chain and its key), `makeSelfSignedServerContext(SelfSignedOptions)`, `makeTlsClientContext()` (a pinned CA and a host name, or trust on first use), `generateSelfSignedCertificate(SelfSignedOptions)`, `certificateFingerprint()`, `constantTimeEquals()`; `TlsOptions` (a minimum protocol version), `tlsSessionOf()`, which finds the `ITlsSession` behind an `ISocket`, and `sshStyleFingerprint()`, a SHA-256 as `SHA256:` | -| `` (`core::net`) | `ITlsSession`: what a finished handshake answers -- `channelBinding()` (RFC 9266, TLS 1.3 only), `peerCertificateDigest()` (the raw SHA-256, empty without a peer certificate) and `negotiatedVersion()` (empty before the handshake) -- and `TlsVersion` | +| `` (`core::net`) | `ITlsContext`, the seam a TLS implementation plugs in behind -- `wrap()`, and `wrapClient(inner, loop, TlsPeer)`, which binds one client connection to the host it was dialled for and whose default refuses a name (`Unsupported`) rather than drop it -- and `wrapTls(socket, context, loop)`, which hands a socket back unchanged for a null context -- so an accept path compiles identically in a build without TLS | +| `` (`core::net_tls`) | a TLS `ISocket` over any other, driven through memory BIOs on the same loop, with an eager `handshakeIfNeeded()`, a `waitReadable()` that tells `close_notify` from data and a `shutdownWrite()` that sends `close_notify` before the FIN; `makeTlsServerContext()` and `makeTlsServerContextFromFiles()` (a chain and its key), `makeSelfSignedServerContext(SelfSignedOptions)`, `makeTlsClientContext()` (a pinned CA and a host name, or trust on first use), `makeTlsClientContext(TrustSource, TlsClientOptions)` (a verifying client that fails closed: SNI and a host check for a DNS `TlsPeer`, an IP-SAN check and no SNI for an address literal, the chain alone for an empty name; no option disables it). `TrustSource` is `TrustAnchors`, which OpenSSL checks during the handshake, or an `IChainVerifier`, asked after the handshake and before any application byte moves, once the leaf's name has passed the same RFC 9525 check, the socket staying unestablished (and its `ITlsSession` answering as unfinished) until it answers, `trustAnchorsFromPem()`, `generateSelfSignedCertificate(SelfSignedOptions)`, `certificateFingerprint()`, `constantTimeEquals()`; `TlsOptions` (a minimum protocol version, and the ALPN names a server selects from or a client offers), `TlsClientOptions`, `tlsSessionOf()`, which is `ISocket::tlsSession()`, and `sshStyleFingerprint()`, a SHA-256 as `SHA256:` | +| `` (`core::net_tls`) | where a verifying client's trust comes from, failing closed: `ITrustStore::load()`, `makePemTrustStore()`, `makeFileTrustStore(files, environment, home, blocking)` (`SSL_CERT_FILE`, then `SSL_CERT_DIR` as one hashed directory, then the first existing `trustBundleLocations()` row; a named but missing file, an empty store, an unreadable file, a malformed bundle, a bundle over `MaxTrustBundleBytes` or a directory over `MaxTrustDirectoryBytes` (16 MiB each) is an error; files read through `async::offload`), `TrustBundleLocation`/`TrustBundleKind`, and `makeSystemTlsClientContext()`: the platform verifier on macOS (`SecTrustEvaluateWithError`) and Windows (`CertGetCertificateChain` + `CERT_CHAIN_POLICY_SSL`), the file store elsewhere, chosen by one CMake-selected `SystemTrust.cpp` | +| `` (`core::net`) | `ITlsSession`: what a finished handshake answers -- `channelBinding()` (RFC 9266, TLS 1.3 only), `peerCertificateDigest()` (the raw SHA-256, empty without a peer certificate) `negotiatedVersion()` (empty before the handshake), `negotiatedProtocol()` (ALPN) and `failure()`, the first TLS failure as a `TlsFailure` (`Certificate`, `AlertReceived` with the alert byte, or `Protocol`) -- and `TlsVersion` | | `` (`core::net_tls`) | OpenSSH public keys and SSHSIG verification: `SshPublicKey`, `parseSshPublicKey()`, `parseSshPublicKeyBlob()`, `parseAuthorizedKeysLine()`, `sshFingerprintOf()`, `verifySshSignature()`, `sshsigSignedData()`, `assembleSshsig()`; `ssh-ed25519`, `ecdsa-sha2-nistp256` and their `sk-` forms | | `` (`core::net_tls`) | the ssh-agent client: `ISshAgent` (`identities()`, `sign()`), `makeSshAgent()` and its `SshAgentError`; one connection per request | | `` | `defaultSshAgentEndpoint()`: `SSH_AUTH_SOCK` on POSIX, the OpenSSH named pipe on Windows. In `core::net`, so every build has it | diff --git a/src/core/net/CMakeLists.txt b/src/core/net/CMakeLists.txt index 10fc8cd2..e651b4b8 100644 --- a/src/core/net/CMakeLists.txt +++ b/src/core/net/CMakeLists.txt @@ -168,6 +168,7 @@ core_cpp_add_module(net KIND STATIC WithTimeout.hpp WriteQueue.hpp detail/CompletionHook.hpp + detail/InFlightBudget.hpp detail/ParkedCall.hpp detail/ParkId.hpp detail/ParkTable.hpp @@ -326,22 +327,46 @@ core_cpp_add_module(net KIND STATIC # software because ssh-keygen makes sk signatures only with a device attached. Both are permitted # units of the seam, and neither header names an OpenSSL type. SshAgent is the ssh-agent protocol # over a socket: no OpenSSL, here only for SshPublicKey. +# +# The system trust is one CMake-selected SystemTrust.cpp, never an #ifdef: macOS and Windows hand +# every chain to the platform's verifier (Security.framework; CryptoAPI's chain engine), so the +# operating system's own trust settings decide, and every other system reads its bundle or hashed +# directory through the portable file store in TrustStore.cpp. +if(APPLE) + set(_coreCppNetSystemTrust darwin/SystemTrust.cpp darwin/DarwinChainVerifier.cpp darwin/DarwinChainVerifier.hpp) + set(_coreCppNetTlsPlatformLibs "-framework Security" "-framework CoreFoundation") + set(_coreCppNetTlsPlatformTests darwin/DarwinChainVerifier_test.cpp) +elseif(WIN32) + set(_coreCppNetSystemTrust windows/SystemTrust.cpp windows/WindowsChainVerifier.cpp windows/WindowsChainVerifier.hpp) + set(_coreCppNetTlsPlatformLibs crypt32) + set(_coreCppNetTlsPlatformTests windows/WindowsChainVerifier_test.cpp) +else() + set(_coreCppNetSystemTrust posix/SystemTrust.cpp) + set(_coreCppNetTlsPlatformLibs "") + # No platform verifier here: the file store's cases run on every OS from TrustStore_test.cpp. + set(_coreCppNetTlsPlatformTests "") +endif() + core_cpp_add_module(net_tls KIND STATIC HEADERS SshAgent.hpp SshKeys.hpp Tls.hpp + TrustStore.hpp testing/SoftwareSecurityKey.hpp testing/StrictTlsPeer.hpp SOURCES SshAgent.cpp SshKeys.cpp Tls.cpp + TrustStore.cpp + ${_coreCppNetSystemTrust} + detail/Alpn.hpp detail/SshWire.hpp testing/SoftwareSecurityKey.cpp testing/StrictTlsPeer.cpp PUBLIC_LIBS core::net - PRIVATE_LIBS OpenSSL::SSL OpenSSL::Crypto) + PRIVATE_LIBS OpenSSL::SSL OpenSSL::Crypto ${_coreCppNetTlsPlatformLibs}) # The error vocabulary alone, in every build: under Emscripten this is what proves net_types builds. core_cpp_add_test(net NAME net_types SOURCES NetError_test.cpp) @@ -496,14 +521,19 @@ endif() # core::net_tls, and OpenSSL stays PRIVATE to it. core_cpp_add_test(net NAME net_tls SOURCES + ChainVerifierTestSupport.hpp SshAgent_test.cpp SshKeys_test.cpp TlsContext_test.cpp TlsLifetime_test.cpp TlsCancelRead_test.cpp + TlsPeer_test.cpp + TlsTestSupport.hpp TlsSession_test.cpp TlsSocket_test.cpp Tls_test.cpp + TrustStore_test.cpp + ${_coreCppNetTlsPlatformTests} LABELS loopback # The keys and signatures ssh-keygen made, read where they are checked in (testdata/ssh/README.md). DEFINITIONS "CORE_CPP_SSH_TESTDATA_DIR=\"${CMAKE_CURRENT_SOURCE_DIR}/testdata/ssh\"" diff --git a/src/core/net/ChainVerifierTestSupport.hpp b/src/core/net/ChainVerifierTestSupport.hpp new file mode 100644 index 00000000..a82973c8 --- /dev/null +++ b/src/core/net/ChainVerifierTestSupport.hpp @@ -0,0 +1,118 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// The refusals every platform `IChainVerifier` must make, as one table, and the case that runs it. +/// +/// A verifier answering `{}` for everything would pass every TLS case that uses the scripted one, +/// so the real verifiers are held to this directly. None of the rows needs the network: an empty +/// chain, bytes that are no certificate, and a self-signed certificate no trust store holds, asked +/// for its own name, for no name and for another name. Each must be refused as a certificate +/// failure, from the blocking executor. +/// +/// Test-only, beside the tests, because it needs Catch2: it is compiled into no module. + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace core::net::testing +{ + +/// What a refusal row presents. +enum class PresentedChain : std::uint8_t +{ + Empty = 0, ///< No certificate at all. + Garbage, ///< Bytes that start like DER and are no certificate. + SelfSigned, ///< A certificate for `localhost` that no trust store holds. +}; + +/// One chain a platform verifier must refuse. +struct VerifierRefusal +{ + std::string_view what; ///< The row, as a section name. + PresentedChain chain; ///< What is presented. + std::string_view name; ///< The name it is asked for. +}; + +/// The refusals, in the order they are run. +inline constexpr auto VerifierRefusals = std::array { + VerifierRefusal { .what = "an empty chain", .chain = PresentedChain::Empty, .name = "localhost" }, + VerifierRefusal { .what = "garbage DER", .chain = PresentedChain::Garbage, .name = "localhost" }, + VerifierRefusal { .what = "an untrusted self-signed certificate, its own name", + .chain = PresentedChain::SelfSigned, + .name = "localhost" }, + VerifierRefusal { .what = "an untrusted self-signed certificate, no name", + .chain = PresentedChain::SelfSigned, + .name = "" }, + VerifierRefusal { .what = "an untrusted self-signed certificate, another name", + .chain = PresentedChain::SelfSigned, + .name = "other.test" }, +}; + +/// A self-signed certificate for `localhost`, DER-encoded; generated once. +[[nodiscard]] inline DerCertificate const& untrustedLocalhost() +{ + static auto const der = [] { + auto material = + generateSelfSignedCertificate({ .commonName = "localhost", .subjectNames = { "localhost" } }); + REQUIRE(material.has_value()); + auto anchors = trustAnchorsFromPem(material->certPem); + REQUIRE(anchors.has_value()); + REQUIRE(anchors->certificates.size() == 1); + return anchors->certificates.front(); + }(); + return der; +} + +/// @return The chain @p kind names. +[[nodiscard]] inline std::vector presented(PresentedChain kind) +{ + switch (kind) + { + case PresentedChain::Empty: return {}; + case PresentedChain::Garbage: return { DerCertificate(16, std::byte { 0x30 }) }; + case PresentedChain::SelfSigned: return { untrustedLocalhost() }; + } + return {}; +} + +/// Runs every row of @c VerifierRefusals against the verifier @p make builds, each in its own +/// section: the verification must park on the blocking executor, and answer a certificate failure +/// with a reason. +/// @param make Builds the verifier under test from a blocking executor. +template +void requireVerifierRefusals(MakeVerifier make) +{ + for (auto const& row: VerifierRefusals) + { + DYNAMIC_SECTION(row.what) + { + auto blocking = async::testing::ManualExecutor {}; + std::shared_ptr const verifier = make(blocking); + REQUIRE(verifier != nullptr); + auto task = verifier->verify(presented(row.chain), std::string { row.name }); + task.handle().resume(); + CHECK(blocking.pending() == 1); + blocking.drain(); + // Finished on the blocking executor: nothing is handed anywhere else. + REQUIRE(task.done()); + auto const verdict = task.result(); + REQUIRE_FALSE(verdict.has_value()); + CHECK(verdict.error().kind == TlsFailureKind::Certificate); + CHECK_FALSE(verdict.error().message.empty()); + } + } +} + +} // namespace core::net::testing diff --git a/src/core/net/ExecutorAddressResolver.cpp b/src/core/net/ExecutorAddressResolver.cpp index 7a28a07c..f11fe556 100644 --- a/src/core/net/ExecutorAddressResolver.cpp +++ b/src/core/net/ExecutorAddressResolver.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include @@ -26,33 +27,6 @@ namespace /// One lookup's rendezvous between the executor that runs it and the parked flow. using ResolveCall = detail::ParkedCall; - /// Whether a lookup got one of the budget's slots. - enum class SlotReservation : std::uint8_t - { - Refused, ///< The budget was full; nothing was taken. - Reserved, ///< One slot is the caller's, to be given back exactly once. - }; - - /// Takes one slot of @p inFlight's budget, if one is free. - /// - /// A loop of compare-exchange rather than an add and a take-back, so that a full budget is never - /// exceeded even for a moment -- several loops may resolve through one resolver at once. - /// @param inFlight The slots taken. - /// @param maxInFlight How many there are. - /// @return Whether one was taken. - [[nodiscard]] SlotReservation reserveSlot(std::atomic& inFlight, - std::size_t maxInFlight) noexcept - { - auto current = inFlight.load(std::memory_order_relaxed); - do - { - if (current >= maxInFlight) - return SlotReservation::Refused; - } while (!inFlight.compare_exchange_weak( - current, current + 1, std::memory_order_acq_rel, std::memory_order_relaxed)); - return SlotReservation::Reserved; - } - /// One lookup's slot and its answer, owned by the detached flow that runs it. /// /// **Its destructor is the guard of the slot rule.** A lookup that finishes gives the slot back @@ -197,7 +171,7 @@ async::Task ExecutorAddressResolver::resolve(std::string host, // Allocated before the slot is taken, so a failed allocation has no slot to give back. auto call = std::make_shared(loop); - if (reserveSlot(*_inFlight, _options.maxInFlight) == SlotReservation::Refused) + if (detail::reserveSlot(*_inFlight, _options.maxInFlight) == detail::SlotReservation::Refused) { _refused.fetch_add(1, std::memory_order_relaxed); co_return std::unexpected( diff --git a/src/core/net/ISocket.hpp b/src/core/net/ISocket.hpp index 528be82c..47a76be9 100644 --- a/src/core/net/ISocket.hpp +++ b/src/core/net/ISocket.hpp @@ -19,6 +19,7 @@ /// Merged from contour's `net::ISocket` and fastcached's `FastCache::ISocket` /// (`FastCache/Net/ISocket.hpp` at `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21`). +#include #include #include #include @@ -368,6 +369,15 @@ class CORE_NET_API ISocket /// @return Nothing, or as @c option. [[nodiscard]] virtual std::expected setOption(SocketOption option, std::uint64_t value); + /// The TLS session this socket carries, so code that reads a TLS failure or the negotiated ALPN + /// protocol needs no link to `core::net_tls`. + /// + /// **The default answers null**: a transport that is not TLS has no session. The TLS layer + /// answers its own; every decorator in this library forwards it, so a TLS socket under a + /// decorator is still seen as one (@c SplitSocket answers from its read half, as @c option). + /// @return The session, valid for as long as this socket lives; null for a plaintext socket. + [[nodiscard]] virtual ITlsSession const* tlsSession() const noexcept { return nullptr; } + /// Closes the socket. Idempotent; a subsequent read or write resolves with /// @c NetErrorCode::BadHandle. /// diff --git a/src/core/net/ITlsContext.hpp b/src/core/net/ITlsContext.hpp index 63f108b5..0657088b 100644 --- a/src/core/net/ITlsContext.hpp +++ b/src/core/net/ITlsContext.hpp @@ -17,7 +17,9 @@ #include #include +#include +#include #include #include #include @@ -25,6 +27,21 @@ namespace core::net { +/// Who one client connection is for: what @c ITlsContext::wrapClient binds the connection to. +struct TlsPeer +{ + /// The host the connection was dialled for, as the caller spelled it: a DNS name, or an IP + /// literal -- a dotted quad, or IPv6 text with or without the brackets a URL authority puts + /// around it, and with or without a zone (`fe80::1%eth0`). Brackets around anything but IPv6, + /// and a zone on anything but IPv6, are refused. + /// + /// A DNS name is sent as SNI and the certificate must name it in a DNS subjectAltName; an IP + /// literal is sent as nothing (RFC 6066 forbids an address in SNI) and the certificate must carry + /// it, without its zone, as an IP subjectAltName. A verifying context (@c makeTlsClientContext over + /// a @c TrustSource) refuses an empty one: the chain alone proves nothing about who the peer is. + std::string serverName; +}; + /// A configured TLS role: a SERVER context holds the certificate and private key; a CLIENT context /// holds the peer-verification policy. `wrap()` layers TLS onto an already-connected transport. /// @@ -54,6 +71,35 @@ class ITlsContext [[nodiscard]] virtual std::unique_ptr wrap(std::unique_ptr inner, async::IExecutor& executor) = 0; + /// Wraps @p inner as a CLIENT connection to @p peer: SNI and the certificate check bound to the + /// one name this connection was dialled for. + /// + /// **A context never discards a requested name.** The default -- for a context with no + /// per-connection check, a server context or one written before this member existed -- refuses + /// a non-empty @c TlsPeer::serverName with @c NetErrorCode::Unsupported, because wrapping without + /// it would hand back a connection that is not verified for the host asked for. With an empty + /// name it is @c wrap. A context that does bind the name refuses one the wire cannot carry (an + /// embedded NUL, brackets around something that is no IPv6 literal), and an empty one, with + /// @c NetErrorCode::AddressError. + /// @param inner The connected transport to encrypt (owned by the result). + /// @param executor As for @c wrap. + /// @param peer Who the connection is for. + /// @return The TLS socket, negotiating lazily as @c wrap's does; @c NetErrorCode::Unsupported for + /// a name this context cannot verify; @c NetErrorCode::ResourceExhausted when the socket + /// could not be allocated. + [[nodiscard]] virtual std::expected, NetError> wrapClient( + std::unique_ptr inner, async::IExecutor& executor, TlsPeer const& peer) + { + if (!peer.serverName.empty()) + return std::unexpected(makeNetError( + NetErrorCode::Unsupported, 0, "this TLS context cannot verify a per-connection server name")); + auto socket = wrap(std::move(inner), executor); + if (socket == nullptr) + return std::unexpected( + makeNetError(NetErrorCode::ResourceExhausted, 0, "the TLS socket could not be allocated")); + return socket; + } + /// The SHA-256 fingerprint of the certificate this context presents, as 64 lower-case hex /// digits. /// diff --git a/src/core/net/ITlsSession.hpp b/src/core/net/ITlsSession.hpp index 0bf563ed..04840b4a 100644 --- a/src/core/net/ITlsSession.hpp +++ b/src/core/net/ITlsSession.hpp @@ -2,13 +2,13 @@ #pragma once /// @file -/// `ITlsSession` -- what a finished TLS handshake lets a caller ask of its connection, and -/// `TlsVersion`, the protocol floor a context is built with. +/// `ITlsSession` -- what a TLS handshake lets a caller ask of its connection, `TlsFailure`, how one +/// that failed says why, and `TlsVersion`, the protocol floor a context is built with. /// /// **In `core::net` beside `ITlsContext`, with no OpenSSL in sight**, so code that authenticates a -/// user over a TLS connection compiles in a build that has no TLS. The implementation is the socket -/// `core::net_tls` returns; `tlsSessionOf` (``) finds the session behind an -/// `ISocket`. +/// user over a TLS connection, or maps a TLS failure to a protocol error, compiles in a build that +/// has no TLS. The implementation is the socket `core::net_tls` returns; `ISocket::tlsSession()` +/// finds the session behind an `ISocket`, through any decorator that forwards it. #include #include @@ -27,9 +27,30 @@ enum class TlsVersion : std::uint8_t Tls13, ///< TLS 1.3. }; -/// The facts about one TLS connection that are only known once its handshake has finished. +/// What kind of failure ended a TLS connection. +enum class TlsFailureKind : std::uint8_t +{ + Protocol = 0, ///< The TLS layer failed for any reason the two below do not name. + Certificate, ///< The peer's certificate was refused: an untrusted chain, an expired or not yet + ///< valid certificate, or one that does not name the host or address dialled. + AlertReceived, ///< The peer ended the handshake or the connection with a fatal alert. +}; + +/// Why a TLS connection failed, in the shape `wasi:http`'s `TLS-*` error cases carry it. +struct TlsFailure +{ + TlsFailureKind kind = TlsFailureKind::Protocol; ///< What failed. + std::optional alert; ///< The alert's description byte (RFC 8446 + ///< section 6), for @c TlsFailureKind::AlertReceived. + std::string message; ///< A human-readable reason; may be empty. +}; + +/// The facts about one TLS connection that are only known once its handshake has run. /// -/// Every query is valid after the handshake and answers an error (or empty) before it. +/// Every query but @c failure answers for an ESTABLISHED session only, and an error (or empty) +/// otherwise. A session whose handshake finished but whose chain a verifier has not yet accepted, +/// or refused, answers as one that never finished: a caller cannot read a refused peer's identity, +/// or bind to its channel, by asking before it checks @c failure. class ITlsSession { public: @@ -48,19 +69,38 @@ class ITlsSession /// Only a TLS 1.3 session has one: RFC 9266 defines tls-exporter for TLS 1.3, and under TLS 1.2 /// the exporter is not bound to the whole handshake (without extended master secret), so a 1.2 /// session answers an error rather than a binding that binds less than it claims. - /// @return The 32 bytes, or why they are not available (no handshake yet, a session below TLS 1.3, - /// or the export failed). + /// @return The 32 bytes, or why they are not available (a session not established -- its handshake + /// unfinished, its chain still being verified, or refused -- a session below TLS 1.3, or + /// the export failed). [[nodiscard]] virtual std::expected, std::string> channelBinding() const = 0; /// @return The SHA-256 of the peer's DER certificate, raw, so a caller may format it as it - /// likes (@c sshStyleFingerprint takes it as it is); no value if the handshake has not - /// finished or the peer presented no certificate. + /// likes (@c sshStyleFingerprint takes it as it is); no value until the session is + /// established (a refused peer's certificate is not reported), or if the peer presented + /// none. [[nodiscard]] virtual std::optional> peerCertificateDigest() const = 0; - /// @return The protocol version the handshake settled on; no value before the handshake has - /// finished, when nothing has been negotiated yet. + /// @return The protocol version the handshake settled on; no value until the session is + /// established -- before the handshake has finished, while its chain is being verified, + /// and after it was refused. [[nodiscard]] virtual std::optional negotiatedVersion() const = 0; + /// Why the TLS layer failed, once it has: the first failure of the handshake, or of a record the + /// peer sent after it. A failure of the transport under TLS (a reset, an end before the handshake + /// finished) is no TLS failure and answers nothing here; the operation's @c NetError says it. + /// + /// **Fails closed is what makes @c TlsFailureKind::Certificate mean something**: a socket that + /// verifies its peer refuses every certificate the check rejects, so this kind is reported for + /// exactly the connections that check ended. + /// @return The failure, or no value while the connection works. The default never fails, for a + /// session that cannot. + [[nodiscard]] virtual std::optional failure() const { return std::nullopt; } + + /// @return The application protocol ALPN (RFC 7301) settled on, e.g. `"http/1.1"`; empty until the + /// session is established (as @c negotiatedVersion), and when either end offered none. + /// The default is empty. + [[nodiscard]] virtual std::string negotiatedProtocol() const { return {}; } + protected: ITlsSession() = default; }; diff --git a/src/core/net/SocketEndpoints_test.cpp b/src/core/net/SocketEndpoints_test.cpp index d713b3ff..a1dc782d 100644 --- a/src/core/net/SocketEndpoints_test.cpp +++ b/src/core/net/SocketEndpoints_test.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -19,11 +20,14 @@ #include #include #include +#include #include #include #include +#include +#include #include #include #include @@ -105,6 +109,41 @@ Task dialAndAccept(EventLoop* loop, std::string host, IListener* listener, return failedWith(result, NetErrorCode::BadHandle) && result.error().systemCode == 0; } +/// A session that answers nothing: what the forwarding case compares pointers against. +class FakeSession final: public core::net::ITlsSession +{ + public: + FakeSession() = default; + + [[nodiscard]] std::expected, std::string> channelBinding() const override + { + return std::unexpected(std::string { "fake" }); + } + [[nodiscard]] std::optional> peerCertificateDigest() const override + { + return std::nullopt; + } + [[nodiscard]] std::optional negotiatedVersion() const override + { + return std::nullopt; + } +}; + +/// A transport that reports @p session as its TLS session, as a TLS socket reports itself. +class SessionSocket final: public core::net::testing::SocketDecorator +{ + public: + SessionSocket(ISocket& inner, core::net::ITlsSession const& session) noexcept: + SocketDecorator { inner }, _session { session } + { + } + + [[nodiscard]] core::net::ITlsSession const* tlsSession() const noexcept override { return &_session; } + + private: + core::net::ITlsSession const& _session; +}; + } // namespace TEST_CASE("A loopback connection reports each end's port from both sides", "[net][endpoints][loopback]") @@ -242,3 +281,38 @@ TEST_CASE("A transport with no address answers Unsupported", "[net][endpoints][i CHECK(failedWith(socket.remoteEndpoint(), NetErrorCode::Unsupported)); } } + +TEST_CASE("A decorator forwards the TLS session of the socket it decorates", + "[net][socket][decorator][tls-session]") +{ + // `http` reads a connection's TLS failure and ALPN through `ISocket::tlsSession()`, whatever + // decorates the TLS socket by then. A decorator that answered the base's null would make a + // TLS connection look like a plaintext one. + auto backend = core::net::makeDefaultBackend(); + auto loop = EventLoop { *backend }; + auto pair = core::net::testing::makeSocketPair(loop); + REQUIRE(pair.has_value()); + auto const session = FakeSession {}; + CHECK(pair->first->tlsSession() == nullptr); // a plain transport has none + + SECTION("SocketDecorator") + { + auto tls = SessionSocket { *pair->first, session }; + auto& transport = static_cast(tls); // not a copy of the decorator + auto const decorated = core::net::testing::SocketDecorator { transport }; + CHECK(decorated.tlsSession() == &session); + } + + SECTION("SplitSocket answers from its read half") + { + auto const split = + core::net::combineHalves(std::make_unique(*pair->first, session), + std::make_unique(*pair->second)); + CHECK(split->tlsSession() == &session); + + auto const reversed = + core::net::combineHalves(std::make_unique(*pair->second), + std::make_unique(*pair->first, session)); + CHECK(reversed->tlsSession() == nullptr); + } +} diff --git a/src/core/net/SplitSocket.hpp b/src/core/net/SplitSocket.hpp index cedf3d7f..13208f26 100644 --- a/src/core/net/SplitSocket.hpp +++ b/src/core/net/SplitSocket.hpp @@ -10,6 +10,7 @@ /// other, closing both together. #include +#include #include #include #include @@ -140,6 +141,9 @@ class SplitSocket final: public ISocket return _readHalf->setOption(option, value); } + /// From the read half, as @c option reads it: the half whose bytes a session would decrypt. + [[nodiscard]] ITlsSession const* tlsSession() const noexcept override { return _readHalf->tlsSession(); } + private: std::unique_ptr _readHalf; std::unique_ptr _writeHalf; diff --git a/src/core/net/Tls.cpp b/src/core/net/Tls.cpp index 52503505..a9d070be 100644 --- a/src/core/net/Tls.cpp +++ b/src/core/net/Tls.cpp @@ -1,16 +1,21 @@ // SPDX-License-Identifier: Apache-2.0 #include +#include #include #include #include #include +#include #include #include #include #include #include #include +#include +#include +#include #include #include @@ -27,19 +32,24 @@ #include #include +#include #include #include #include #include +#include #include #include #include #include #include +#include #include #include +#include #include #include +#include #include namespace core::net @@ -66,6 +76,7 @@ namespace } using SslCtxPtr = std::unique_ptr; + using SslPtr = std::unique_ptr; using BioPtr = std::unique_ptr; using X509Ptr = std::unique_ptr; @@ -81,6 +92,18 @@ namespace return digest; } + /// @p cert, DER-encoded. + [[nodiscard]] std::expected derOf(X509* cert) + { + auto* der = static_cast(nullptr); + auto const length = i2d_X509(cert, &der); + if (length <= 0) + return std::unexpected("i2d_X509: " + opensslError()); + auto const release = detail::ScopeGuard { [der]() noexcept { OPENSSL_free(der); } }; + auto const* const begin = reinterpret_cast(der); + return DerCertificate(begin, begin + length); + } + /// The SHA-256 fingerprint of @p cert as lower-case hex, or empty if it cannot be computed. [[nodiscard]] std::string fingerprintOf(X509 const* cert) { @@ -116,6 +139,223 @@ namespace Client, ///< `SSL_set_connect_state`: verifies it, or trusts on first use. }; + /// Whether a client context binds each connection to the peer it was dialled for. + enum class PeerBinding : std::uint8_t + { + /// The context's own check, fixed at construction (or none, for trust on first use): + /// `wrapClient` refuses a per-connection name rather than drop it. + Fixed = 0, + /// `wrapClient` sets SNI and the certificate check from its `TlsPeer`, per connection. + PerConnection, + }; + + using detail::AlpnWire; + using detail::alpnWireFormat; + + /// What one session's OpenSSL callbacks read and record: reached through the SSL's app data, + /// owned by the socket that owns the SSL. + struct SessionNotes + { + /// The description byte of the first fatal alert the peer sent. + std::optional alertReceived; + /// A server's ALPN names, its order of preference; null for a client or a server with none. + /// Shared with the context, and held here because the SSL may outlive it. + std::shared_ptr alpnSelection; + }; + + /// What a peer name is, once @c classifyPeerName has read it. + enum class PeerNameKind : std::uint8_t + { + Dns = 0, ///< A DNS name: checked against the certificate's DNS entries, and sent as SNI. + Address, ///< An IP literal: checked against its IP entries, and sent as nothing. + }; + + /// A peer name as the certificate check reads it. + struct PeerName + { + PeerNameKind kind = PeerNameKind::Dns; + /// The DNS name as given, or the address without its brackets and zone. + std::string checked; + }; + + /// The verifications a context's sockets started and its verifier has not answered, shared by + /// the context, its sockets and every detached evaluation; @c TlsClientOptions::maxVerificationsInFlight. + class VerificationBudget + { + public: + /// @param slots How many slots there are. + explicit VerificationBudget(std::size_t slots) noexcept: _maxInFlight { slots } {} + + /// @return How many slots there are. + [[nodiscard]] std::size_t maxInFlight() const noexcept { return _maxInFlight; } + + std::atomic inFlight { 0 }; ///< Slots taken. + + private: + std::size_t _maxInFlight; + }; + + /// What a client session asks after its handshake, where an @c IChainVerifier checks its peer. + struct ChainVerification + { + /// Null: OpenSSL checked the chain during the handshake, and nothing is asked after it. + std::shared_ptr verifier; + /// The name the connection is for, as the certificate check reads it; none to check the + /// chain alone. + std::optional peer; + /// The context's budget; non-null wherever @c verifier is. + std::shared_ptr budget; + }; + + /// One verification's rendezvous between the detached evaluation and the handshake waiting for it. + using VerifyCall = detail::ParkedCall>; + + /// One verification's slot and its answer, owned by the detached flow that runs it. + /// + /// **Its destructor is the guard of the slot rule**, as @c ExecutorAddressResolver's lease is: an + /// evaluation that never answers -- its frame freed unrun by an executor shutting down -- gives + /// the slot back and answers the waiter with a refusal, so neither is stranded. + class VerificationLease + { + public: + VerificationLease(std::shared_ptr budget, + std::shared_ptr call) noexcept: + _budget(std::move(budget)), _call(std::move(call)) + { + } + + VerificationLease(VerificationLease&&) noexcept = default; + VerificationLease(VerificationLease const&) = delete; + VerificationLease& operator=(VerificationLease const&) = delete; + VerificationLease& operator=(VerificationLease&&) = delete; + + ~VerificationLease() { fail(); } + + /// Gives the slot back, THEN answers the waiter, so a resumed handshake never finds its own + /// slot still taken. At most once; a later call does nothing. + /// @param verdict What the verifier answered. + void finish(std::expected verdict) noexcept + { + auto const call = std::exchange(_call, nullptr); + auto const budget = std::exchange(_budget, nullptr); + if (!call) + return; + budget->inFlight.fetch_sub(1, std::memory_order_acq_rel); + call->settle(std::move(verdict)); + } + + /// Finishes with a refusal that allocates nothing, for the paths that cannot take a throw. + void fail() noexcept + { + if (!_call) + return; + finish(std::unexpected( + TlsFailure { .kind = TlsFailureKind::Certificate, .alert = std::nullopt, .message = {} })); + } + + private: + std::shared_ptr _budget; + std::shared_ptr _call; + }; + + /// Asks @p verifier about @p chain and answers @p lease's call. + /// + /// Detached, because nobody may own it: the handshake waiting for it can be stopped, and its + /// socket destroyed, long before the platform answers. It holds what it touches by value or by + /// share, never the socket, and never its loop: the verifier finishes on its own executor, and + /// the answer reaches the socket only through @p lease's call, which hands a PARKED waiter back to + /// its loop -- a waiter that a stop took away, with its socket and loop gone since, is handed + /// nowhere. It runs with no stop token, so a stop never reaches the evaluation. + /// Whatever is thrown is answered as a refusal: an exception escaping a detached flow ends the + /// process, and an unanswered waiter would be stranded. + /// @param verifier Who decides. + /// @param chain The presented chain, leaf first. + /// @param serverName The name to check it for; empty for the chain alone. + /// @param lease The verification's slot and call. + async::DetachedTask runVerification(std::shared_ptr verifier, + std::vector chain, + std::string serverName, + VerificationLease lease) + { + try + { + lease.finish(co_await verifier->verify(std::move(chain), std::move(serverName))); + } + catch (...) + { + lease.fail(); + } + } + + /// The flags every name check here uses: a wildcard stands for one whole leftmost label, and + /// the subject's common name is never a name (RFC 9525 section 6.3). + constexpr auto NameCheckFlags = static_cast(X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS) + | static_cast(X509_CHECK_FLAG_NEVER_CHECK_SUBJECT); + + /// Whether @p leaf names @p peer: a DNS subjectAltName for a DNS name, an IP one for an address. + [[nodiscard]] bool certificateNames(X509* leaf, PeerName const& peer) + { + if (peer.kind == PeerNameKind::Address) + return X509_check_ip_asc(leaf, peer.checked.c_str(), NameCheckFlags) == 1; + return X509_check_host(leaf, peer.checked.data(), peer.checked.size(), NameCheckFlags, nullptr) == 1; + } + + /// Where a session stands. One state rather than flags, so "verified" cannot be read off a + /// finished handshake: with a verifier, the handshake finishing is only `Verifying`. + enum class SessionState : std::uint8_t + { + Handshaking = 0, ///< Not finished; the next operation drives it (again, after a cancel). + Verifying, ///< Finished, and the verifier has not answered: nothing moves yet. + Established, ///< Finished and trusted: reads and writes move application bytes. + Failed, ///< Refused, or broken; sticky, and `_handshakeError` says why. + }; + + [[nodiscard]] SessionNotes* notesOf(SSL const* ssl) noexcept + { + return static_cast(SSL_get_app_data(ssl)); + } + + /// Records the first FATAL alert the peer sends, for `TlsFailureKind::AlertReceived`. + /// + /// A warning is not what ended the connection: TLS 1.2 lets a server warn (`unrecognized_name`, + /// 112) and carry on, and the fatal alert that follows, if any, is the one that names the + /// failure. + void recordAlert(SSL const* ssl, int where, int value) + { + auto* const notes = notesOf(ssl); + // Both bits: SSL_CB_READ_ALERT and SSL_CB_WRITE_ALERT share SSL_CB_ALERT, so a mask test + // against the first alone also matches every alert this end sends. + if ((where & SSL_CB_READ_ALERT) != SSL_CB_READ_ALERT || notes == nullptr || notes->alertReceived) + return; + // The value is the level in the high byte and the description in the low one. + auto const bits = static_cast(value); + if ((bits >> 8U) != SSL3_AL_FATAL) + return; + notes->alertReceived = static_cast(bits & 0xFFU); + } + + /// A server's ALPN choice: the first of its own names the client offered. None in common is + /// refused with `no_application_protocol`, as RFC 7301 section 3.2 requires. + /// + /// Installed only on a context with names to select from, whose every session the socket gives + /// them to: a session reaching it without is a defect, not a client to serve without ALPN. + int selectAlpn(SSL* ssl, + unsigned char const** out, + unsigned char* outLength, + unsigned char const* offered, + unsigned int offeredLength, + void* /*argument*/) + { + auto const* const notes = notesOf(ssl); + Require(notes != nullptr && notes->alpnSelection != nullptr); + auto const chosen = detail::selectAlpn(*notes->alpnSelection, std::span { offered, offeredLength }); + if (!chosen) + return SSL_TLSEXT_ERR_ALERT_FATAL; + *out = chosen->data(); + *outLength = static_cast(chosen->size()); + return SSL_TLSEXT_ERR_OK; + } + /// Whether a caller of the outbound flush needs it FINISHED or only needs it to HAPPEN. enum class FlushWait : std::uint8_t { @@ -420,14 +660,25 @@ namespace /// @param ssl The session, its BIOs attached (owned). /// @param executor The loop a waiter parked on one of the gates is resumed on; must outlive /// every operation on this socket. - TlsSocket(std::unique_ptr inner, SSL* ssl, async::IExecutor& executor): + /// @param alpnSelection A server's ALPN names, or null. + /// @param verification For a client checked by an @c IChainVerifier, the verifier and the + /// name; empty where OpenSSL checks the chain, or nothing is checked. + TlsSocket(std::unique_ptr inner, + SslPtr ssl, + async::IExecutor& executor, + std::shared_ptr alpnSelection, + ChainVerification verification = {}): _inner(std::move(inner)), - _ssl(ssl), - _rbio(SSL_get_rbio(ssl)), - _wbio(SSL_get_wbio(ssl)), + _ssl(ssl.release()), + _rbio(SSL_get_rbio(_ssl)), + _wbio(SSL_get_wbio(_ssl)), + _notes { .alertReceived = std::nullopt, .alpnSelection = std::move(alpnSelection) }, + _verification(std::move(verification)), + _executor(&executor), _handshaking(std::make_shared(executor)), _flushing(std::make_shared(executor)) { + SSL_set_app_data(_ssl, &_notes); } /// Abandons every operation parked on this socket, and only then frees the session. @@ -491,8 +742,8 @@ namespace [[nodiscard]] std::expected, std::string> channelBinding() const override { - if (SSL_is_init_finished(_ssl) != 1) - return std::unexpected("the TLS handshake has not finished"); + if (_state != SessionState::Established) + return std::unexpected("the TLS session is not established"); if (SSL_version(_ssl) < TLS1_3_VERSION) return std::unexpected("the tls-exporter channel binding needs TLS 1.3 (RFC 9266)"); ERR_clear_error(); @@ -513,7 +764,7 @@ namespace [[nodiscard]] std::optional> peerCertificateDigest() const override { - if (SSL_is_init_finished(_ssl) != 1) + if (_state != SessionState::Established) return std::nullopt; auto const peer = X509Ptr { SSL_get1_peer_certificate(_ssl), X509_free }; return certificateDigest(peer.get()); @@ -521,11 +772,28 @@ namespace [[nodiscard]] std::optional negotiatedVersion() const override { - if (SSL_is_init_finished(_ssl) != 1) + if (_state != SessionState::Established) return std::nullopt; return SSL_version(_ssl) >= TLS1_3_VERSION ? TlsVersion::Tls13 : TlsVersion::Tls12; } + [[nodiscard]] std::optional failure() const override { return _failure; } + + [[nodiscard]] std::string negotiatedProtocol() const override + { + if (_state != SessionState::Established) + return {}; + auto const* selected = static_cast(nullptr); + auto length = 0U; + SSL_get0_alpn_selected(_ssl, &selected, &length); + if (selected == nullptr) + return {}; + return std::string { reinterpret_cast(selected), length }; + } + + /// @see ISocket::tlsSession: this socket is its own session. + [[nodiscard]] ITlsSession const* tlsSession() const noexcept override { return this; } + /// Reports whether the peer has finished sending, decrypting whatever records that takes /// and consuming no plaintext. /// @@ -550,7 +818,7 @@ namespace { if (_peerClosed) return IoAwaitable { IoResult { std::size_t { 0 } } }; - if (_handshakeDone) + if (_state == SessionState::Established) if (auto const pending = SSL_pending(_ssl); pending > 0) return IoAwaitable { IoResult { static_cast(pending) } }; return IoAwaitable { probeReadable() }; @@ -651,6 +919,52 @@ namespace [[nodiscard]] bool isClosed() const noexcept override { return _peerClosed || _inner->isClosed(); } private: + /// Classifies the TLS layer's first failure for @c failure -- of the handshake, or of a record + /// the peer sent; a write fails only on this end's own state, which is no peer's failure -- + /// as the peer's certificate refused + /// (only where it was checked: trust on first use completes with a failed verification + /// result that nothing acted on), a fatal alert received, or anything else. + /// @param reason OpenSSL's reason, read when the failing call returned. + void recordFailure(std::string reason) + { + if (_failure) + return; + if (auto const verdict = SSL_get_verify_result(_ssl); + verdict != X509_V_OK && (SSL_get_verify_mode(_ssl) & SSL_VERIFY_PEER) != 0) + _failure = TlsFailure { .kind = TlsFailureKind::Certificate, + .alert = std::nullopt, + .message = X509_verify_cert_error_string(verdict) }; + else if (_notes.alertReceived) + _failure = TlsFailure { .kind = TlsFailureKind::AlertReceived, + .alert = _notes.alertReceived, + .message = SSL_alert_desc_string_long(*_notes.alertReceived) }; + else + _failure = TlsFailure { .kind = TlsFailureKind::Protocol, + .alert = std::nullopt, + .message = std::move(reason) }; + } + + /// Defence in depth for a session that verifies its peer: a finished handshake is only + /// established with a peer certificate and a verification result of OK. OpenSSL refuses + /// the handshake before either could be otherwise; this holds if it ever did not. + /// @return Nothing, or the failure, classified as @c TlsFailureKind::Certificate. + [[nodiscard]] std::expected confirmVerified() + { + if ((SSL_get_verify_mode(_ssl) & SSL_VERIFY_PEER) == 0) + return {}; + auto const peer = X509Ptr { SSL_get1_peer_certificate(_ssl), X509_free }; + auto const verdict = SSL_get_verify_result(_ssl); + if (peer && verdict == X509_V_OK) + return {}; + auto const message = std::string { peer ? X509_verify_cert_error_string(verdict) + : "the peer presented no certificate" }; + if (!_failure) + _failure = TlsFailure { .kind = TlsFailureKind::Certificate, + .alert = std::nullopt, + .message = message }; + return std::unexpected(makeNetError(NetErrorCode::SystemError, 0, "TLS handshake: " + message)); + } + async::Task readPlain(std::span buffer) { if (auto const handshaken = co_await handshake(Direction::Read); !handshaken) @@ -684,9 +998,12 @@ namespace } break; } - default: + default: { + auto reason = opensslError(); + recordFailure(reason); co_return std::unexpected( - makeNetError(NetErrorCode::SystemError, 0, "SSL_read: " + opensslError())); + makeNetError(NetErrorCode::SystemError, 0, "SSL_read: " + reason)); + } } } } @@ -773,9 +1090,12 @@ namespace co_return std::unexpected(truncated()); break; } - default: + default: { + auto reason = opensslError(); + recordFailure(reason); co_return std::unexpected( - makeNetError(NetErrorCode::SystemError, 0, "SSL_peek: " + opensslError())); + makeNetError(NetErrorCode::SystemError, 0, "SSL_peek: " + reason)); + } } } } @@ -783,7 +1103,7 @@ namespace /// Writes and flushes `close_notify`, then half-closes the inner transport. async::Task> closeNotify() { - if (_handshaking->busy() || _handshakeDone) + if (_handshaking->busy() || _state == SessionState::Established) { if (auto const handshaken = co_await handshake(Direction::Write); handshaken) { @@ -815,9 +1135,9 @@ namespace // this call the new driver. while (true) { - if (_handshakeDone) + if (_state == SessionState::Established) co_return std::expected {}; - if (_handshakeError) + if (_state == SessionState::Failed) co_return std::unexpected(*_handshakeError); if (!_handshaking->busy()) break; @@ -841,6 +1161,11 @@ namespace auto const reason = result == 1 || err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE ? std::string {} : opensslError(); + // Classified now too, for the same reason and one more: the flush may fail, and the + // failure that caused it must not be lost behind the transport's. + auto const failed = result != 1 && err != SSL_ERROR_WANT_READ && err != SSL_ERROR_WANT_WRITE; + if (failed) + recordFailure(reason); // Always flush whatever the last step queued (ClientHello, the server's flight, // Finished, ...) before deciding what to await. if (auto const flushed = co_await flushOut(FlushWait::Join); !flushed) @@ -850,7 +1175,22 @@ namespace } if (result == 1) { - _handshakeDone = true; + if (auto const verified = confirmVerified(); !verified) + { + outcome = std::unexpected(verified.error()); + break; + } + if (_verification.verifier) + { + _state = SessionState::Verifying; + auto const verified = co_await verifyChain(); + if (!verified) + { + outcome = std::unexpected(verified.error()); + break; + } + } + _state = SessionState::Established; break; } if (err == SSL_ERROR_WANT_READ) @@ -868,7 +1208,7 @@ namespace break; } } - else if (err != SSL_ERROR_WANT_WRITE) + else if (failed) { outcome = std::unexpected( makeNetError(NetErrorCode::SystemError, 0, "TLS handshake: " + reason)); @@ -876,16 +1216,110 @@ namespace } } - // A failure is sticky -- parked waiters and every later operation observe it -- with one - // exception: a cancelled inner read took no ciphertext, so the handshake can simply be - // driven again, and `cancelRead` is documented not to be a close. The reason travels in - // NetError::context ("TLS handshake: "); net RETURNS failures rather than - // logging them. - if (!outcome && outcome.error().code != NetErrorCode::Cancelled) + // A failure is sticky -- parked waiters and every later operation observe it -- with two + // exceptions. A cancelled inner read took no ciphertext, so the handshake can simply be + // driven again, and `cancelRead` is documented not to be a close. A full verifier budget, + // the one `ResourceExhausted` a `Verifying` socket answers, refused only the asking and + // not the peer: the socket stays `Verifying`, and a handshake driven again once a slot + // is free asks again. The reason travels in NetError::context ("TLS handshake: "); net RETURNS failures rather than logging them. + auto const retryable = !outcome + && (outcome.error().code == NetErrorCode::Cancelled + || (_state == SessionState::Verifying + && outcome.error().code == NetErrorCode::ResourceExhausted)); + if (!outcome && !retryable) + { _handshakeError = outcome.error(); + _state = SessionState::Failed; + } co_return outcome; } + /// Asks the verifier about the chain the peer presented, for the name the connection is for. + /// + /// Runs inside the handshake gate, so a read or a write that arrives meanwhile waits there, + /// and the socket is `Verifying` until it answers: nothing of the caller's moves first. + /// @return Nothing once the verifier accepted; otherwise the refusal, classified as + /// @c TlsFailureKind::Certificate. + async::Task> verifyChain() + { + // The client's view of the peer chain includes the leaf, first (`SSL_get_peer_cert_chain`; + // `SSL_get0_peer_certificates` is BoringSSL's). + auto const* const presented = SSL_get_peer_cert_chain(_ssl); + // Defence in depth, as `confirmVerified` is: a verifier is never asked to trust nothing. + if (presented == nullptr || sk_X509_num(presented) <= 0) + co_return refuseChain("the peer presented no certificate"); + + // The name is checked here, before any platform is asked, so it means the same on every + // one: Windows' SSL policy, for one, falls back to the common name, which RFC 9525 forbids. + if (_verification.peer && !certificateNames(sk_X509_value(presented, 0), *_verification.peer)) + { + ERR_clear_error(); + co_return refuseChain("the certificate is not valid for '" + _verification.peer->checked + + "'"); + } + + if (_pendingVerification == nullptr) + { + auto chain = std::vector {}; + for (auto const index: std::views::iota(0, sk_X509_num(presented))) + { + auto der = derOf(sk_X509_value(presented, index)); + if (!der) + co_return refuseChain(der.error()); + chain.push_back(std::move(*der)); + } + // Allocated before the slot is taken, as `ExecutorAddressResolver` does, so a failed + // allocation has no slot to give back. From the reservation on, the lease owns the + // slot: a frame that cannot be allocated destroys it, and its destructor gives it back. + auto call = std::make_shared(_executor); + auto& budget = *_verification.budget; + if (detail::reserveSlot(budget.inFlight, budget.maxInFlight()) + == detail::SlotReservation::Refused) + co_return std::unexpected( + makeNetError(NetErrorCode::ResourceExhausted, + 0, + std::format("the chain verifier budget is full ({} in flight)", + budget.maxInFlight()))); + _pendingVerification = std::move(call); + runVerification(_verification.verifier, + std::move(chain), + _verification.peer ? _verification.peer->checked : std::string {}, + VerificationLease { _verification.budget, _pendingVerification }); + } + else + _pendingVerification->rejoin(); + + // By value, not only through `this`: the socket may go while the verifier is answering. + auto const call = _pendingVerification; + auto const lifetime = std::weak_ptr { _lifetime }; + // A stop throws out of this wait and leaves the call where it is, for a retry to join. + auto verdict = co_await VerifyCall::wait(call); + // As `feedIn`: the socket may have been destroyed while the verifier was answering. + if (lifetime.expired()) + throw async::OperationCancelled {}; + _pendingVerification.reset(); + if (!verdict) + { + // Whatever the verifier called it, a refused chain is a certificate failure. + auto refused = std::move(verdict.error()); + refused.kind = TlsFailureKind::Certificate; + _failure = refused; + co_return std::unexpected(makeNetError( + NetErrorCode::SystemError, 0, "TLS certificate refused: " + refused.message)); + } + co_return std::expected {}; + } + + /// A refusal this end decided before asking the verifier, classified as a certificate failure. + [[nodiscard]] std::expected refuseChain(std::string const& message) + { + _failure = + TlsFailure { .kind = TlsFailureKind::Certificate, .alert = std::nullopt, .message = message }; + return std::unexpected( + makeNetError(NetErrorCode::SystemError, 0, "TLS certificate refused: " + message)); + } + /// Drains OpenSSL's outgoing BIO to the inner socket, one flush at a time. /// @param wait Whether to wait for a flush already in progress (see @c FlushWait). async::Task> flushOut(FlushWait wait) @@ -975,9 +1409,16 @@ namespace SSL* _ssl; BIO* _rbio; ///< Network -> SSL (owned by _ssl). BIO* _wbio; ///< SSL -> network (owned by _ssl). - bool _handshakeDone = false; - bool _peerClosed = false; ///< A read saw the peer's close_notify or inner EOF. - std::optional _handshakeError; ///< Set once the handshake fails (sticky). + SessionState _state = SessionState::Handshaking; + bool _peerClosed = false; ///< A read saw the peer's close_notify or inner EOF. + std::optional _handshakeError; ///< Why the session is `Failed` (sticky). + std::optional _failure; ///< The TLS layer's first failure, classified. + SessionNotes _notes; ///< What the session's callbacks record; its app data. + ChainVerification _verification; ///< Who is asked after the handshake, if anyone. + async::IExecutor* _executor; ///< Where this socket's waiters are resumed. + /// The verification this socket started and has not yet been answered: kept past a stop, so a + /// handshake driven again joins it rather than starting another. + std::shared_ptr _pendingVerification; Direction _innerReadOwner = Direction::Any; ///< Whose operation the latest inner read served. /// Held by the coroutine driving the handshake. Shared: see @c SerialGate. @@ -990,49 +1431,194 @@ namespace std::shared_ptr _lifetime = std::make_shared('\0'); }; + /// Decides what kind of name @p name is, and what of it is checked. + /// + /// **A literal is what `detail::isNumericHost` says it is** -- a dotted quad or IPv6 text, the + /// strict parse the dial path uses -- not what OpenSSL's looser parser accepts, so the two never + /// disagree about whether a host was an address. Brackets, as a URL authority writes them, hold + /// an IPv6 literal and nothing else. A zone (`fe80::1%eth0`) is local routing, not identity: the + /// address without it is checked, and nothing is sent as SNI. Everything else is a DNS name. + /// @param name The name the connection is for; non-empty. + /// @return What kind of name it is, or a reason it cannot be checked. + [[nodiscard]] std::expected classifyPeerName(std::string_view name) + { + // A NUL cuts a C string short: the check (and SNI) would be for a prefix of the host asked for. + if (name.contains('\0')) + return std::unexpected(std::string { "a TLS server name may not contain NUL" }); + auto const bracketed = name.size() >= 2 && name.front() == '[' && name.back() == ']'; + auto const unbracketed = bracketed ? name.substr(1, name.size() - 2) : name; + auto const address = unbracketed.substr(0, unbracketed.find('%')); + auto const zoned = address.size() != unbracketed.size(); + auto const isIpv6 = detail::isNumericHost(address) && address.contains(':'); + if (detail::isNumericHost(address) && (isIpv6 || (!bracketed && !zoned))) + return PeerName { .kind = PeerNameKind::Address, .checked = std::string { address } }; + if (bracketed || zoned) + return std::unexpected("a bracketed or zoned TLS server name must be an IPv6 literal: '" + + std::string { name } + "'"); + return PeerName { .kind = PeerNameKind::Dns, .checked = std::string { name } }; + } + + /// Points @p param's certificate check at @p name, as @c classifyPeerName reads it: an address + /// against the certificate's IP entries, a DNS name by whole labels (no wildcard inside a label) + /// against its DNS entries alone -- never the subject's common name (RFC 9525 section 6.3). + /// @param param The verification parameters of a context or a session. + /// @param name The name the connection is for; non-empty. + /// @return The name as checked, or a reason it cannot be checked. + [[nodiscard]] std::expected setVerificationName(X509_VERIFY_PARAM* param, + std::string_view name) + { + auto peer = classifyPeerName(name); + if (!peer) + return peer; + X509_VERIFY_PARAM_set_hostflags(param, NameCheckFlags); + ERR_clear_error(); + if (peer->kind == PeerNameKind::Address) + { + if (X509_VERIFY_PARAM_set1_ip_asc(param, peer->checked.c_str()) != 1) + return std::unexpected("X509_VERIFY_PARAM_set1_ip_asc: " + opensslError()); + return peer; + } + if (X509_VERIFY_PARAM_set1_host(param, peer->checked.data(), peer->checked.size()) != 1) + return std::unexpected("TLS server name '" + peer->checked + "': " + opensslError()); + return peer; + } + + /// Binds @p ssl to @p name: the check @c setVerificationName sets, and SNI for a DNS name. + /// + /// The check is set on a verifier context's session too, where `SSL_VERIFY_NONE` means OpenSSL + /// acts on no result: the name the verifier is asked about is the same one, read the same way. + /// @param ssl A client session, before its handshake. + /// @param name A non-empty @c TlsPeer::serverName. + /// @return The name as checked, or @c NetErrorCode::AddressError for a name the wire cannot carry. + [[nodiscard]] std::expected bindPeer(SSL* ssl, std::string_view name) + { + auto peer = setVerificationName(SSL_get0_param(ssl), name); + if (!peer) + return std::unexpected(makeNetError(NetErrorCode::AddressError, 0, peer.error())); + if (peer->kind == PeerNameKind::Address) + return std::move(*peer); // RFC 6066 section 3: no literal address in server_name + // SSL_set_tlsext_host_name, spelled out: the macro casts the name to `void*` C-style. The + // name is a DNS name here, so it has no NUL and the check above already accepted it. + auto host = peer->checked; + if (SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name, host.data()) != 1) + return std::unexpected(makeNetError( + NetErrorCode::AddressError, 0, "TLS server name '" + host + "': " + opensslError())); + return std::move(*peer); + } + /// The DI context: a configured SSL_CTX plus its handshake role. class TlsContext final: public ITlsContext { public: - TlsContext(SslCtxPtr ctx, TlsRole role): _ctx(std::move(ctx)), _role(role) {} + /// @param ctx The configured context (owned). + /// @param role The end of the handshake its sockets play. + /// @param binding For a client, whether `wrapClient` honours a @c TlsPeer. + /// @param alpnSelection For a server, the ALPN names it selects from; null for none. + /// @param verifier For a client, the verifier asked after every handshake; null where OpenSSL + /// checks the chain, or nothing does. + /// @param maxVerificationsInFlight With @p verifier, its sockets' shared budget of unanswered + /// verifications (@c TlsClientOptions::maxVerificationsInFlight). + TlsContext(SslCtxPtr ctx, + TlsRole role, + PeerBinding binding = PeerBinding::Fixed, + std::shared_ptr alpnSelection = nullptr, + std::shared_ptr verifier = nullptr, + std::size_t maxVerificationsInFlight = 0): + _ctx(std::move(ctx)), + _role(role), + _binding(binding), + _alpnSelection(std::move(alpnSelection)), + _verifier(std::move(verifier)), + _budget(std::make_shared(maxVerificationsInFlight)) + { + } + /// A verifier context's session asks it too, about the chain alone. std::unique_ptr wrap(std::unique_ptr inner, async::IExecutor& executor) override { - auto* ssl = SSL_new(_ctx.get()); - if (ssl == nullptr) + auto ssl = newSession(); + if (!ssl) return nullptr; + return std::make_unique( + std::move(inner), + std::move(ssl), + executor, + _alpnSelection, + ChainVerification { .verifier = _verifier, .peer = std::nullopt, .budget = _budget }); + } + + /// A context built to bind connections sets each one's SNI and check from @p peer; any other + /// keeps the default, which refuses a name rather than drop it. + std::expected, NetError> wrapClient(std::unique_ptr inner, + async::IExecutor& executor, + TlsPeer const& peer) override + { + if (_binding != PeerBinding::PerConnection) + return ITlsContext::wrapClient(std::move(inner), executor, peer); + // A verifying context checks the leaf for a name; without one, any certificate its trust + // vouches for -- issued to anybody -- would be accepted for this connection. + if (peer.serverName.empty()) + return std::unexpected( + makeNetError(NetErrorCode::AddressError, + 0, + "a verifying TLS client needs the server name it dialled")); + auto ssl = newSession(); + if (!ssl) + return std::unexpected(makeNetError( + NetErrorCode::ResourceExhausted, 0, "the TLS session could not be allocated")); + auto bound = bindPeer(ssl.get(), peer.serverName); + if (!bound) + return std::unexpected(std::move(bound.error())); + auto checked = std::optional { std::move(*bound) }; + return std::make_unique( + std::move(inner), + std::move(ssl), + executor, + _alpnSelection, + ChainVerification { .verifier = _verifier, .peer = std::move(checked), .budget = _budget }); + } + + [[nodiscard]] std::string certificateFingerprint() const override + { + return fingerprintOf(SSL_CTX_get0_certificate(_ctx.get())); + } + + private: + /// A session of this context's role over two memory BIOs, or null if it could not be made. + [[nodiscard]] SslPtr newSession() const + { + auto ssl = SslPtr { SSL_new(_ctx.get()), SSL_free }; + if (!ssl) + return ssl; // Memory BIOs bridge OpenSSL and the coroutine transport; SSL_set_bio takes ownership // of both, so SSL_free later releases them. // // Checked like SSL_new above: handing a null BIO to SSL_set_bio yields a socket that // LOOKS constructed and dereferences null on its first read or write. Ownership has not - // transferred yet on this path, so both BIOs and the SSL are released here (BIO_free - // tolerates null, which is what makes the one-sided case work). + // transferred yet on this path, so both BIOs are released here (BIO_free tolerates + // null, which is what makes the one-sided case work). auto* const rbio = BIO_new(BIO_s_mem()); auto* const wbio = BIO_new(BIO_s_mem()); if (rbio == nullptr || wbio == nullptr) { BIO_free(rbio); BIO_free(wbio); - SSL_free(ssl); - return nullptr; + return SslPtr { nullptr, SSL_free }; } - SSL_set_bio(ssl, rbio, wbio); + SSL_set_bio(ssl.get(), rbio, wbio); if (_role == TlsRole::Server) - SSL_set_accept_state(ssl); + SSL_set_accept_state(ssl.get()); else - SSL_set_connect_state(ssl); - return std::make_unique(std::move(inner), ssl, executor); - } - - [[nodiscard]] std::string certificateFingerprint() const override - { - return fingerprintOf(SSL_CTX_get0_certificate(_ctx.get())); + SSL_set_connect_state(ssl.get()); + return ssl; } - private: SslCtxPtr _ctx; TlsRole _role; + PeerBinding _binding; + std::shared_ptr _alpnSelection; + std::shared_ptr _verifier; + std::shared_ptr _budget; }; /// A context with the floor every one of them shares: TLS 1.2 (or the version @p options asks for) @@ -1050,10 +1636,31 @@ namespace SSL_CTX_set_min_proto_version( ctx.get(), options.minimumVersion == TlsVersion::Tls13 ? TLS1_3_VERSION : TLS1_2_VERSION); SSL_CTX_set_options(ctx.get(), SSL_OP_NO_RENEGOTIATION); + // TLS 1.2 suites with no authentication or no encryption, refused whatever the build's + // default list holds: a handshake with one has no certificate to check. (TLS 1.3 has none.) + if (SSL_CTX_set_cipher_list(ctx.get(), "DEFAULT:!aNULL:!eNULL") != 1) + return SslCtxPtr { nullptr, SSL_CTX_free }; + // Every session records the fatal alert its peer sends, for `TlsFailureKind::AlertReceived`. + SSL_CTX_set_info_callback(ctx.get(), recordAlert); } return ctx; } + /// Makes a client context offer @p names through ALPN. + /// @return Nothing, or why the names cannot be offered. + [[nodiscard]] std::expected offerAlpn(SSL_CTX* ctx, + std::vector const& names) + { + auto wire = alpnWireFormat(names); + if (!wire) + return std::unexpected(std::move(wire.error())); + // Zero is success here, unlike every other SSL_CTX setter. + if (!wire->empty() + && SSL_CTX_set_alpn_protos(ctx, wire->data(), static_cast(wire->size())) != 0) + return std::unexpected("SSL_CTX_set_alpn_protos: " + opensslError()); + return {}; + } + /// Installs a PEM certificate chain and its key into a server context. /// @param ctx The context to fill. /// @param certPem The leaf, then any intermediates. @@ -1188,7 +1795,17 @@ std::expected, std::string> makeTlsServerContext(st return std::unexpected("SSL_CTX_new failed: " + opensslError()); if (auto used = useServerMaterial(ctx.get(), certPem, keyPem); !used) return std::unexpected(std::move(used.error())); - return std::make_shared(std::move(ctx), TlsRole::Server); + auto alpn = alpnWireFormat(options.alpn); + if (!alpn) + return std::unexpected(std::move(alpn.error())); + auto selection = std::shared_ptr {}; + if (!alpn->empty()) + { + selection = std::make_shared(std::move(*alpn)); + SSL_CTX_set_alpn_select_cb(ctx.get(), selectAlpn, nullptr); + } + return std::make_shared( + std::move(ctx), TlsRole::Server, PeerBinding::Fixed, std::move(selection)); } std::expected, std::string> makeTlsServerContextFromFiles( @@ -1320,6 +1937,8 @@ std::expected, std::string> makeTlsClientContext( auto ctx = newCtx(TLS_client_method(), options); if (!ctx) return std::unexpected("SSL_CTX_new failed: " + opensslError()); + if (auto offered = offerAlpn(ctx.get(), options.alpn); !offered) + return std::unexpected(std::move(offered.error())); if (caPem.empty()) { @@ -1353,27 +1972,120 @@ std::expected, std::string> makeTlsClientContext( // creates from it. if (!expectedHostName.empty()) { - auto* const param = SSL_CTX_get0_param(ctx.get()); - // An IP-literal host must be checked as an IP: X509_VERIFY_PARAM_set1_host would look - // for it in a dNSName, which a correct certificate does not carry. - auto const isIpLiteral = - X509_VERIFY_PARAM_set1_ip_asc(param, std::string { expectedHostName }.c_str()) == 1; - ERR_clear_error(); // a refused IP parse means "a DNS name", not a failure - if (!isIpLiteral - && X509_VERIFY_PARAM_set1_host(param, expectedHostName.data(), expectedHostName.size()) != 1) - return std::unexpected("X509_VERIFY_PARAM_set1_host: " + opensslError()); - // Never accept a wildcard as the LEFTMOST label of a partial match ("*.example.com" - // matching "a.b.example.com"); OpenSSL's default already refuses it, this pins it. - X509_VERIFY_PARAM_set_hostflags(param, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS); + // The same check a per-connection peer gets: an address against the IP entries, a + // name against the DNS entries by whole labels. + if (auto const kind = setVerificationName(SSL_CTX_get0_param(ctx.get()), expectedHostName); !kind) + return std::unexpected(kind.error()); } } return std::make_shared(std::move(ctx), TlsRole::Client); } +std::expected trustAnchorsFromPem(std::string_view pem) +{ + auto bio = memBio(pem); + auto anchors = TrustAnchors {}; + while (true) + { + ERR_clear_error(); + auto const cert = X509Ptr { PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr), X509_free }; + if (!cert) + { + // Running out of certificates is "no start line"; anything else is a block that is there + // and does not parse, which is not an end to skip quietly. + auto const code = ERR_peek_last_error(); + if (ERR_GET_LIB(code) == ERR_LIB_PEM && ERR_GET_REASON(code) == PEM_R_NO_START_LINE) + break; + return std::unexpected("invalid certificate PEM: " + opensslError()); + } + auto der = derOf(cert.get()); + if (!der) + return std::unexpected(std::move(der.error())); + anchors.certificates.push_back(std::move(*der)); + } + ERR_clear_error(); + if (anchors.certificates.empty()) + return std::unexpected(std::string { "no certificate in the PEM" }); + return anchors; +} + +namespace +{ + /// A verifying client context over its own SSL_CTX: the floor, and the ALPN names offered. + [[nodiscard]] std::expected newVerifyingCtx(TlsClientOptions const& options) + { + auto ctx = + newCtx(TLS_client_method(), TlsOptions { .minimumVersion = options.minimumVersion, .alpn = {} }); + if (!ctx) + return std::unexpected("SSL_CTX_new failed: " + opensslError()); + if (auto offered = offerAlpn(ctx.get(), options.alpn); !offered) + return std::unexpected(std::move(offered.error())); + return ctx; + } + + /// The context over anchors: OpenSSL checks every chain against them, during the handshake. + [[nodiscard]] std::expected, std::string> anchoredClientContext( + TrustAnchors const& anchors, TlsClientOptions const& options) + { + // Nothing trusted would refuse every server; refused here, where it is a configuration error. + if (anchors.certificates.empty()) + return std::unexpected( + std::string { "a verifying TLS client context needs at least one trust anchor" }); + auto ctx = newVerifyingCtx(options); + if (!ctx) + return std::unexpected(std::move(ctx.error())); + + auto* const store = SSL_CTX_get_cert_store(ctx->get()); + for (auto const& der: anchors.certificates) + { + auto const* cursor = reinterpret_cast(der.data()); + auto const cert = + X509Ptr { d2i_X509(nullptr, &cursor, static_cast(der.size())), X509_free }; + // The whole buffer must be the one certificate: trailing bytes are not an anchor's. + if (!cert || cursor != reinterpret_cast(der.data()) + der.size()) + return std::unexpected("invalid DER trust anchor: " + opensslError()); + if (X509_STORE_add_cert(store, cert.get()) != 1) + return std::unexpected("X509_STORE_add_cert: " + opensslError()); + } + // No option reaches past this: every connection's chain is checked, and a refusal fails it. + SSL_CTX_set_verify(ctx->get(), SSL_VERIFY_PEER, nullptr); + return std::make_shared(std::move(*ctx), TlsRole::Client, PeerBinding::PerConnection); + } + + /// The context over a verifier: OpenSSL completes the handshake without a chain check of its + /// own, and every session asks the verifier before it is established. + [[nodiscard]] std::expected, std::string> verifiedClientContext( + std::shared_ptr verifier, TlsClientOptions const& options) + { + if (!verifier) + return std::unexpected(std::string { "a verifying TLS client context needs a chain verifier" }); + auto ctx = newVerifyingCtx(options); + if (!ctx) + return std::unexpected(std::move(ctx.error())); + // VERIFY_NONE is OpenSSL's check only: the handshake still proves the server holds the leaf's + // key, and the socket refuses to be established until the verifier accepted the chain. + SSL_CTX_set_verify(ctx->get(), SSL_VERIFY_NONE, nullptr); + return std::make_shared(std::move(*ctx), + TlsRole::Client, + PeerBinding::PerConnection, + nullptr, + std::move(verifier), + options.maxVerificationsInFlight); + } +} // namespace + +std::expected, std::string> makeTlsClientContext(TrustSource trust, + TlsClientOptions const& options) +{ + if (auto const* const anchors = std::get_if(&trust)) + return anchoredClientContext(*anchors, options); + return verifiedClientContext(std::get>(std::move(trust)), options); +} + ITlsSession const* tlsSessionOf(ISocket const& socket) noexcept { - return dynamic_cast(&socket); + return socket.tlsSession(); } std::string sshStyleFingerprint(std::array const& sha256) diff --git a/src/core/net/Tls.hpp b/src/core/net/Tls.hpp index f498acfb..399ea271 100644 --- a/src/core/net/Tls.hpp +++ b/src/core/net/Tls.hpp @@ -30,6 +30,7 @@ /// produce. The material and context functions below return a human-readable string instead, /// because what fails there is configuration, not a connection. +#include #include #include #include @@ -43,6 +44,7 @@ #include #include #include +#include #include namespace core::net @@ -98,8 +100,52 @@ struct TlsOptions /// The oldest protocol version the context negotiates. @c TlsVersion::Tls13 refuses a peer that /// can only speak 1.2. TlsVersion minimumVersion = TlsVersion::Tls12; + + /// ALPN (RFC 7301) protocol names, e.g. `"http/1.1"`, each 1 to 255 bytes. A SERVER selects the + /// first of these, in this order of preference, that the client offered, and refuses a client + /// that offered only others with the `no_application_protocol` alert; a client that offers none + /// is served without ALPN. A CLIENT from the pinned-name @c makeTlsClientContext offers them. + /// Empty: no ALPN. + std::vector alpn {}; +}; + +/// What a verifying client context is built with. **There is no "do not verify" mode**: every +/// connection's peer certificate is checked, and trust on first use remains the pinned-name +/// @c makeTlsClientContext with an empty CA. +struct TlsClientOptions +{ + /// The oldest protocol version the context negotiates, as @c TlsOptions::minimumVersion. + TlsVersion minimumVersion = TlsVersion::Tls12; + + /// The ALPN protocol names the client offers, in its order of preference, each 1 to 255 bytes; + /// @c ITlsSession::negotiatedProtocol reports which one the server chose. Empty: no ALPN. + std::vector alpn {}; + + /// Over an @c IChainVerifier only: the most verifications the context's sockets have started and + /// the verifier has not answered yet, across every socket, whether or not anyone still waits for + /// one. A stop ends a socket's wait, not the evaluation, so this is what bounds the evaluations a + /// caller can leave running by starting and abandoning handshakes. A handshake past it fails with + /// @c NetErrorCode::ResourceExhausted, which is not sticky: the socket stays unestablished, and a + /// handshake driven again once a slot is free asks the verifier then. Zero refuses every one. + std::size_t maxVerificationsInFlight = 256; }; +/// One certificate, DER-encoded. +using DerCertificate = std::vector; + +/// The certificates a client trusts as roots: a chain is accepted when it leads to one of these. +struct TrustAnchors +{ + std::vector certificates; ///< The anchors, DER-encoded. +}; + +/// Reads every certificate out of a PEM bundle as a trust anchor. +/// @param pem One or more PEM certificates. +/// @return The anchors, in the bundle's order; a human-readable reason if it holds none, or a block +/// that does not parse. +[[nodiscard]] CORE_NET_TLS_API std::expected trustAnchorsFromPem( + std::string_view pem); + /// Builds a SERVER context from a PEM certificate chain and private key held in memory. /// @param certPem The leaf certificate followed by any intermediates, in PEM; every certificate in /// it is served, so a client can build the chain to its trust anchor. @@ -140,21 +186,116 @@ makeSelfSignedServerContext(SelfSignedOptions const& options = {}, TlsOptions co /// this peer, so any certificate that CA ever signed would be accepted for any endpoint. Empty skips /// the name check (and it is moot without a CA, where nothing is verified). /// -/// The name is matched against the certificate's subjectAltName / CN as X509_VERIFY_PARAM does, so -/// an IP-literal host only matches a certificate that carries that IP. No SNI is sent: SNI must not -/// carry an IP literal, and a server here presents one certificate per listener. +/// The name is checked as @c TlsPeer::serverName describes: an IP literal against the certificate's +/// IP subjectAltNames, a DNS name against its DNS ones by whole labels, never the common name. No +/// SNI is sent: SNI must not carry an IP literal, and a server here presents one certificate per +/// listener. +/// +/// **Its contexts bind no per-connection name**: @c ITlsContext::wrapClient refuses a non-empty +/// @c TlsPeer::serverName with @c NetErrorCode::Unsupported rather than drop it, so a connection +/// dialled for a host it cannot check for is never made. The verifying factory below is the one that +/// honours @c TlsPeer. /// /// @param caPem The trust-anchor certificate in PEM, or empty for trust on first use. /// @param expectedHostName The host the caller connected to, or empty to skip the name check. -/// @param options The protocol floor. +/// @param options The protocol floor, and the ALPN names offered. /// @return The context, or a human-readable reason if @p caPem is invalid. [[nodiscard]] CORE_NET_TLS_API std::expected, std::string> makeTlsClientContext( std::string_view caPem = {}, std::string_view expectedHostName = {}, TlsOptions const& options = {}); -/// Finds the TLS session behind @p socket. +/// Decides whether a server's certificate chain is good for the name a connection was dialled for: +/// what a platform's own trust evaluation answers (macOS `SecTrustEvaluateWithError`, Windows +/// `CertGetCertificateChain` and the SSL chain policy), so the operating system's trust settings -- +/// roots it fetched on demand, certificates an administrator distrusted -- are what decides. +/// +/// A context built over one (@c makeTlsClientContext with a @c TrustSource holding it) asks it +/// after the handshake and before any application byte moves: until it has answered, the socket is +/// not established, and every read and write waits. +class IChainVerifier +{ + public: + IChainVerifier() = default; + virtual ~IChainVerifier() = default; + IChainVerifier(IChainVerifier const&) = delete; + IChainVerifier& operator=(IChainVerifier const&) = delete; + IChainVerifier(IChainVerifier&&) = delete; + IChainVerifier& operator=(IChainVerifier&&) = delete; + + /// Verifies a presented chain for a name. + /// + /// **It must fail closed**: an empty chain, a certificate that does not parse, and an error + /// from the platform are each a refusal. It may block, so an implementation runs off the loop, + /// on its blocking executor, and **finishes there**: the task never resumes on the loop of the + /// socket that asked, which may be gone by the time the platform answers. The socket's own wait + /// is what is handed back to its loop. + /// + /// **The socket does not wait on it directly.** It runs detached, and the handshake waits for its + /// answer through a call a stop can abandon: a flow bounded by @c withTimeout or cancelled by its + /// owner gives up the wait at once, and the evaluation finishes on its own, holding one of the + /// context's @c TlsClientOptions::maxVerificationsInFlight slots until it answers. A handshake + /// driven again on the same socket joins the evaluation already running rather than starting a + /// second. The task is therefore never given a stop token. + /// + /// The TLS layer has already checked the leaf's name by RFC 9525's rules when it asks; a + /// verifier checks it again by its platform's, which can only refuse more. + /// @param chain The chain as the server sent it, leaf first, DER-encoded. + /// @param serverName The name to check the leaf against, as the certificate check reads it: a + /// DNS name, or an IP literal without brackets or zone; empty to check the chain alone. + /// @return Nothing if the chain is trusted for @p serverName, or a @c TlsFailure of kind + /// @c TlsFailureKind::Certificate saying why not; delivered on the verifier's own + /// executor. + [[nodiscard]] virtual async::Task> verify( + std::vector chain, std::string serverName) = 0; +}; + +/// What a verifying client trusts: anchors OpenSSL checks the chain against, or a platform verifier +/// that decides for it. +using TrustSource = std::variant>; + +/// Builds a verifying CLIENT context: every connection's chain is checked against @p trust, and +/// @c ITlsContext::wrapClient binds each connection to its @c TlsPeer. +/// +/// **It fails closed.** A DNS @c TlsPeer::serverName is sent as SNI and must be named by a DNS +/// subjectAltName (no partial wildcard: `*` matches one whole leftmost label; the common name is +/// never consulted); an IP literal, bracketed or zoned or neither, sends no SNI and must be an IP +/// subjectAltName; only @c ITlsContext::wrap, which takes no name, verifies the chain alone. An empty +/// name, and a name the wire cannot carry (a NUL, a bracketed name that is no IPv6 literal), is +/// refused by `wrapClient` with @c NetErrorCode::AddressError. +/// +/// - **Over @c TrustAnchors**, OpenSSL checks the chain and the name during the handshake. A +/// finished handshake also needs a peer certificate and an OK verification result, and no +/// anonymous or null TLS 1.2 suite is offered. +/// - **Over an @c IChainVerifier**, OpenSSL completes the handshake with its own chain check off. +/// The leaf's NAME is then checked here, by the rules above, so it means the same on every +/// platform (Windows' SSL policy would fall back to the common name); a mismatch fails without +/// asking the verifier. Only then is the verifier asked about the chain the server presented and +/// that name (an IP literal without its brackets and zone). Until it answers, the socket is not +/// established: a read, a write or @c ISocket::handshakeIfNeeded waits, and nothing of the +/// caller's reaches the wire. A refusal, or a server that presented no certificate, fails the +/// handshake. The verifier finishes on its own executor and is shared by every socket of the +/// context; each socket's wait is handed back to the loop that socket runs on. +/// +/// **The verification is bounded by nothing here.** It is not a read, so the receive deadline +/// (@c ISocket::setReceiveDeadline) does not cover it, and a platform evaluation that fetches an +/// intermediate or a root can take as long as the network does. A stop does not interrupt an +/// evaluation already running on the blocking executor (@c async::offload reads the stop token +/// once, before the hop), so a caller that needs a bound must keep its own, and expect the +/// evaluation to finish in the background after it gave up. +/// +/// Either way an untrusted, expired or mismatched certificate fails the handshake, the failure is +/// sticky, and @c ITlsSession::failure names it @c TlsFailureKind::Certificate. +/// @param trust The anchors, at least one; or the verifier, non-null. @c TrustAnchors converts to +/// it, so a call with anchors reads as one. +/// @param options The protocol floor and the ALPN names offered. +/// @return The context, or a human-readable reason: no anchor, an anchor that does not parse, a null +/// verifier, an ALPN name that is empty or longer than 255 bytes. +[[nodiscard]] CORE_NET_TLS_API std::expected, std::string> makeTlsClientContext( + TrustSource trust, TlsClientOptions const& options = {}); + +/// Finds the TLS session behind @p socket: @c ISocket::tlsSession. /// @param socket Any socket. -/// @return The session if @p socket is a TLS socket from this module, null for any other (a plain -/// TCP socket, a decorator that is not TLS). Valid for as long as @p socket lives. +/// @return The session if @p socket is a TLS socket, or a decorator that forwards one; null for any +/// other (a plain TCP socket). Valid for as long as @p socket lives. [[nodiscard]] CORE_NET_TLS_API ITlsSession const* tlsSessionOf(ISocket const& socket) noexcept; /// Spells a SHA-256 digest the way `ssh-keygen -l` does: `SHA256:` and the unpadded base64. diff --git a/src/core/net/TlsPeer_test.cpp b/src/core/net/TlsPeer_test.cpp new file mode 100644 index 00000000..26be3b3f --- /dev/null +++ b/src/core/net/TlsPeer_test.cpp @@ -0,0 +1,832 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The per-connection TLS peer, and that it fails closed. +// +// `ITlsContext::wrapClient` binds one connection to the name it was dialled for: SNI for a DNS +// name, the certificate check for a DNS name or an IP literal. Every way that check can fail is a +// failed handshake that `ITlsSession::failure()` names as a certificate failure -- an expired +// certificate, a wrong name, an untrusted root, an address the certificate does not carry -- and no +// option turns it off. The other end is `testing::StrictTlsPeer`, OpenSSL driven by hand, so what +// the server saw (the SNI, the ALPN offer) is reported by something that is not the code under +// test. +#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 "TlsTestSupport.hpp" + +using core::net::CertKeyPem; +using core::net::ISocket; +using core::net::ITlsContext; +using core::net::NetErrorCode; +using core::net::TlsClientOptions; +using core::net::TlsFailureKind; +using core::net::TlsPeer; +using core::net::testing::handshakeBoth; +using core::net::testing::makeTlsLoopback; +using core::net::testing::StrictTlsPeer; + +namespace +{ + +/// The certificate every case presents unless it says otherwise: a DNS name and an IP address. +CertKeyPem const& localhostMaterial() +{ + static auto const material = [] { + auto generated = core::net::generateSelfSignedCertificate( + { .commonName = "localhost", .subjectNames = { "localhost", "127.0.0.1" } }); + REQUIRE(generated.has_value()); + return *generated; + }(); + return material; +} + +/// A client context that trusts exactly the certificate in @p pem. +std::shared_ptr clientTrusting(std::string_view pem, TlsClientOptions const& options = {}) +{ + auto anchors = core::net::trustAnchorsFromPem(pem); + REQUIRE(anchors.has_value()); + auto context = core::net::makeTlsClientContext(*anchors, options); + REQUIRE(context.has_value()); + return std::move(*context); +} + +/// Wraps @p transport for @p serverName through @p context, which must accept it. +std::unique_ptr dial(ITlsContext& context, + std::unique_ptr transport, + core::async::IExecutor& executor, + std::string serverName) +{ + auto socket = + context.wrapClient(std::move(transport), executor, TlsPeer { .serverName = std::move(serverName) }); + REQUIRE(socket.has_value()); + REQUIRE(*socket != nullptr); + return std::move(*socket); +} + +/// An `ITlsContext` that implements only `wrap`, as a context written before `wrapClient` existed +/// does: it hands the transport back and counts how often it was asked. +/// What a `WrapOnlyContext` answers. +enum class WrapAnswer : std::uint8_t +{ + Inner = 0, ///< The transport, unwrapped. + Null, ///< Nothing, as a wrap that could not allocate. +}; + +class WrapOnlyContext final: public ITlsContext +{ + public: + explicit WrapOnlyContext(WrapAnswer answer = WrapAnswer::Inner): _answer { answer } {} + + [[nodiscard]] std::unique_ptr wrap(std::unique_ptr inner, + core::async::IExecutor& /*executor*/) override + { + ++wraps; + if (_answer == WrapAnswer::Null) + return nullptr; + return inner; + } + + int wraps = 0; + + private: + WrapAnswer _answer; +}; + +/// The session of a socket the case made TLS; a socket without one fails the case. +/// @param socket The socket a TLS context wrapped. +/// @return Its session. +[[nodiscard]] core::net::ITlsSession const& sessionOf(ISocket const& socket) +{ + auto const* const session = socket.tlsSession(); + REQUIRE(session != nullptr); + return *session; +} + +} // namespace + +TEST_CASE("the default wrapClient refuses a server name", "[net][tls][tlspeer]") +{ + auto loopback = makeTlsLoopback(StrictTlsPeer::client()); + + SECTION("a name is refused, and the transport is never wrapped without it") + { + auto context = WrapOnlyContext {}; + auto const socket = + context.wrapClient(std::move(loopback->transport), loopback->loop, { .serverName = "x" }); + REQUIRE_FALSE(socket.has_value()); + CHECK(socket.error().code == NetErrorCode::Unsupported); + CHECK(context.wraps == 0); + } + + SECTION("no name is wrap()") + { + auto context = WrapOnlyContext {}; + auto const* const raw = loopback->transport.get(); + auto const socket = context.wrapClient(std::move(loopback->transport), loopback->loop, {}); + REQUIRE(socket.has_value()); + CHECK(socket->get() == raw); + CHECK(context.wraps == 1); + } + + SECTION("a wrap that could not allocate is an error, not a null socket") + { + auto context = WrapOnlyContext { WrapAnswer::Null }; + auto const socket = context.wrapClient(std::move(loopback->transport), loopback->loop, {}); + REQUIRE_FALSE(socket.has_value()); + CHECK(socket.error().code == NetErrorCode::ResourceExhausted); + } +} + +TEST_CASE("contexts from the pinned-name factory refuse a per-connection name", "[net][tls][tlspeer]") +{ + // The legacy factory binds its name at construction (or verifies nothing, for trust on first + // use). A per-connection name it silently dropped would be a connection that is not checked for + // the host it was dialled for, so it is refused instead. + auto loopback = makeTlsLoopback(StrictTlsPeer::client()); + auto const pinned = core::net::makeTlsClientContext(localhostMaterial().certPem, "localhost"); + auto const trusting = core::net::makeTlsClientContext(); + REQUIRE(pinned.has_value()); + REQUIRE(trusting.has_value()); + + for (auto* const context: { pinned->get(), trusting->get() }) + { + auto pair = core::net::testing::makeSocketPair(loopback->loop); + REQUIRE(pair.has_value()); + auto const named = + context->wrapClient(std::move(pair->first), loopback->loop, { .serverName = "localhost" }); + REQUIRE_FALSE(named.has_value()); + CHECK(named.error().code == NetErrorCode::Unsupported); + + auto const unnamed = context->wrapClient(std::move(pair->second), loopback->loop, {}); + REQUIRE(unnamed.has_value()); + CHECK(*unnamed != nullptr); + } +} + +TEST_CASE("a DNS name is sent as SNI and verified", "[net][tls][tlspeer]") +{ + auto loopback = makeTlsLoopback(StrictTlsPeer::server(localhostMaterial())); + auto const context = clientTrusting(localhostMaterial().certPem); + auto const socket = dial(*context, std::move(loopback->transport), loopback->loop, "localhost"); + + auto const outcome = handshakeBoth(*loopback, *socket); + REQUIRE(outcome.finished); + CHECK(outcome.local.has_value()); + CHECK(outcome.peer.has_value()); + CHECK(loopback->peer->receivedServerName() == "localhost"); + + auto const* const session = socket->tlsSession(); + REQUIRE(session != nullptr); + CHECK_FALSE(session->failure().has_value()); + CHECK(session->negotiatedProtocol().empty()); // nothing was offered +} + +TEST_CASE("a verifying context refuses an empty server name", "[net][tls][tlspeer]") +{ + // With no name, a chain the anchors vouch for would be accepted whoever it was issued to. + auto loopback = makeTlsLoopback(StrictTlsPeer::server(localhostMaterial())); + auto const context = clientTrusting(localhostMaterial().certPem); + auto const refused = context->wrapClient(std::move(loopback->transport), loopback->loop, TlsPeer {}); + REQUIRE_FALSE(refused.has_value()); + CHECK(refused.error().code == NetErrorCode::AddressError); +} + +TEST_CASE("Tls.ipLiteralAuthority", "[net][tls][tlspeer]") +{ + // An https authority that is an IP literal is checked against the certificate's IP + // subjectAltNames (X509_VERIFY_PARAM_set1_ip_asc), never as a DNS name, and sends no SNI: RFC + // 6066 section 3 forbids a literal address in server_name. + SECTION("127.0.0.1 sends no SNI and verifies against the IP SAN") + { + auto loopback = makeTlsLoopback(StrictTlsPeer::server(localhostMaterial())); + auto const context = clientTrusting(localhostMaterial().certPem); + auto const socket = dial(*context, std::move(loopback->transport), loopback->loop, "127.0.0.1"); + + auto const outcome = handshakeBoth(*loopback, *socket); + REQUIRE(outcome.finished); + CHECK(outcome.local.has_value()); + CHECK(outcome.peer.has_value()); + CHECK(loopback->peer->receivedServerName().empty()); + } + + SECTION("a bracketed IPv6 literal, as a URL authority spells it, is an address too") + { + auto const material = + core::net::generateSelfSignedCertificate({ .commonName = "v6", .subjectNames = { "::1" } }); + REQUIRE(material.has_value()); + auto loopback = makeTlsLoopback(StrictTlsPeer::server(*material)); + auto const context = clientTrusting(material->certPem); + auto const socket = dial(*context, std::move(loopback->transport), loopback->loop, "[::1]"); + + auto const outcome = handshakeBoth(*loopback, *socket); + REQUIRE(outcome.finished); + CHECK(outcome.local.has_value()); + CHECK(loopback->peer->receivedServerName().empty()); + } + + SECTION("a zone is local routing: the address without it is verified, and no SNI is sent") + { + auto const material = + core::net::generateSelfSignedCertificate({ .commonName = "link", .subjectNames = { "fe80::1" } }); + REQUIRE(material.has_value()); + for (auto const* const name: { "fe80::1%eth0", "[fe80::1%eth0]" }) + { + auto loopback = makeTlsLoopback(StrictTlsPeer::server(*material)); + auto const context = clientTrusting(material->certPem); + auto const socket = dial(*context, std::move(loopback->transport), loopback->loop, name); + + auto const outcome = handshakeBoth(*loopback, *socket); + REQUIRE(outcome.finished); + CHECK(outcome.local.has_value()); + CHECK(loopback->peer->receivedServerName().empty()); + } + } + + SECTION("brackets or a zone around anything but IPv6 are refused before anything is sent") + { + for (auto const* const name: + { "[localhost]", "[127.0.0.1]", "127.0.0.1%eth0", "localhost%eth0", "[]" }) + { + auto loopback = makeTlsLoopback(StrictTlsPeer::server(localhostMaterial())); + auto const context = clientTrusting(localhostMaterial().certPem); + auto const socket = + context->wrapClient(std::move(loopback->transport), loopback->loop, { .serverName = name }); + CAPTURE(name); + REQUIRE_FALSE(socket.has_value()); + CHECK(socket.error().code == NetErrorCode::AddressError); + } + } +} + +TEST_CASE("a whole-label wildcard matches the one label it stands for", "[net][tls][tlspeer]") +{ + auto const material = core::net::generateSelfSignedCertificate( + { .commonName = "wildcard", .subjectNames = { "*.example.test" } }); + REQUIRE(material.has_value()); + auto loopback = makeTlsLoopback(StrictTlsPeer::server(*material)); + auto const context = clientTrusting(material->certPem); + auto const socket = dial(*context, std::move(loopback->transport), loopback->loop, "www.example.test"); + + auto const outcome = handshakeBoth(*loopback, *socket); + REQUIRE(outcome.finished); + CHECK(outcome.local.has_value()); + CHECK(loopback->peer->receivedServerName() == "www.example.test"); +} + +TEST_CASE("the pinned-name factory never accepts a name from the common name", "[net][tls][tlspeer]") +{ + // RFC 9525 section 6.3: a client checks the subjectAltNames only. This certificate names + // "localhost" in its subject and carries only an IP entry, which OpenSSL's default would let + // the common name stand in for. + auto const material = core::net::generateSelfSignedCertificate( + { .commonName = "localhost", .subjectNames = { "127.0.0.1" } }); + REQUIRE(material.has_value()); + auto loopback = makeTlsLoopback(StrictTlsPeer::server(*material)); + auto const pinned = core::net::makeTlsClientContext(material->certPem, "localhost"); + REQUIRE(pinned.has_value()); + auto const socket = (*pinned)->wrap(std::move(loopback->transport), loopback->loop); + REQUIRE(socket != nullptr); + + auto const outcome = handshakeBoth(*loopback, *socket); + REQUIRE(outcome.finished); + CHECK_FALSE(outcome.local.has_value()); + auto const failure = sessionOf(*socket).failure(); + REQUIRE(failure.has_value()); + CHECK(failure->kind == TlsFailureKind::Certificate); +} + +TEST_CASE("every verification failure fails the handshake as a certificate failure", "[net][tls][tlspeer]") +{ + auto const& material = localhostMaterial(); + auto const expired = core::net::testing::expiredCopyOf(material); + REQUIRE(expired.has_value()); + auto const stranger = core::net::generateSelfSignedCertificate({ .commonName = "localhost" }); + REQUIRE(stranger.has_value()); + auto const partial = core::net::generateSelfSignedCertificate( + { .commonName = "partial", .subjectNames = { "w*.example.test" } }); + REQUIRE(partial.has_value()); + auto const commonNameOnly = core::net::generateSelfSignedCertificate( + { .commonName = "localhost", .subjectNames = { "127.0.0.1" } }); + REQUIRE(commonNameOnly.has_value()); + + struct Row + { + std::string_view name; + CertKeyPem const* presented; ///< What the server serves. + std::string_view trusted; ///< What the client trusts. + std::string_view serverName; ///< What the client dialled. + std::string_view because; ///< A fragment of OpenSSL's verification reason. + }; + auto const rows = std::array { + Row { "expired", &*expired, expired->certPem, "localhost", "expired" }, + Row { "wrong name", &material, material.certPem, "other.test", "hostname mismatch" }, + Row { "untrusted root", &material, stranger->certPem, "localhost", "self" }, + Row { "IP mismatch", &material, material.certPem, "127.0.0.2", "IP address mismatch" }, + // OpenSSL's default would match a wildcard inside a label; an https client must not. + Row { "partial wildcard", &*partial, partial->certPem, "www.example.test", "hostname mismatch" }, + // RFC 9525: the subject's common name never stands in for a DNS subjectAltName. + Row { + "common name only", &*commonNameOnly, commonNameOnly->certPem, "localhost", "hostname mismatch" }, + // `127.1` is shorthand getaddrinfo accepts, and no literal by the strict parse the dial path + // uses: a name, which no DNS entry matches. + Row { "shorthand address", &material, material.certPem, "127.1", "hostname mismatch" }, + }; + + for (auto const& row: rows) + { + DYNAMIC_SECTION(row.name) + { + auto loopback = makeTlsLoopback(StrictTlsPeer::server(*row.presented)); + auto const context = clientTrusting(row.trusted); + auto const socket = dial( + *context, std::move(loopback->transport), loopback->loop, std::string { row.serverName }); + + auto const outcome = handshakeBoth(*loopback, *socket); + REQUIRE(outcome.finished); + CHECK_FALSE(outcome.local.has_value()); + CHECK_FALSE(outcome.peer.has_value()); + + auto const* const session = socket->tlsSession(); + REQUIRE(session != nullptr); + auto const failure = session->failure(); + REQUIRE(failure.has_value()); + CHECK(failure->kind == TlsFailureKind::Certificate); + CHECK_FALSE(failure->alert.has_value()); + CHECK(failure->message.contains(row.because)); + } + } +} + +TEST_CASE("a server's alert surfaces as AlertReceived with its id", "[net][tls][tlspeer]") +{ + constexpr auto AccessDenied = std::uint8_t { 49 }; + auto loopback = + makeTlsLoopback(StrictTlsPeer::server(localhostMaterial(), { .refuseWithAlert = AccessDenied })); + auto const context = clientTrusting(localhostMaterial().certPem); + auto const socket = dial(*context, std::move(loopback->transport), loopback->loop, "localhost"); + + auto const outcome = handshakeBoth(*loopback, *socket); + REQUIRE(outcome.finished); + CHECK_FALSE(outcome.local.has_value()); + + auto const failure = sessionOf(*socket).failure(); + REQUIRE(failure.has_value()); + CHECK(failure->kind == TlsFailureKind::AlertReceived); + CHECK(failure->alert == AccessDenied); + CHECK_FALSE(failure->message.empty()); +} + +TEST_CASE("a record-layer failure after a handshake that verified nothing is a protocol failure", + "[net][tls][tlspeer]") +{ + // Trust on first use completes the handshake with OpenSSL's verification result still saying the + // chain was not trusted. What breaks the connection afterwards is the record layer, and calling + // it a certificate failure would blame what nothing checked. + auto loopback = makeTlsLoopback(StrictTlsPeer::server(localhostMaterial())); + auto const trusting = core::net::makeTlsClientContext(); + REQUIRE(trusting.has_value()); + auto const socket = (*trusting)->wrap(std::move(loopback->transport), loopback->loop); + REQUIRE(socket != nullptr); + auto const outcome = handshakeBoth(*loopback, *socket); + REQUIRE(outcome.finished); + REQUIRE(outcome.local.has_value()); + + // An application-data record header and five bytes no key encrypted. + static constexpr auto Garbage = + std::array { 0x17, 0x03, 0x03, 0x00, 0x05, 'n', 'o', 'p', 'e', '!' }; + auto failed = false; + + SECTION("read") + { + auto const read = [](ISocket* tls, ISocket* wire, bool* out) -> core::async::Task { + std::ignore = co_await wire->write(std::as_bytes(std::span { Garbage })); + auto buffer = std::array {}; + *out = !(co_await tls->read(buffer)).has_value(); + }; + REQUIRE(core::net::testing::blockOnWithin(loopback->loop, + read(socket.get(), loopback->wire.get(), &failed), + core::net::testing::TlsExchangeBound)); + } + + SECTION("waitReadable") + { + auto const watch = [](ISocket* tls, ISocket* wire, bool* out) -> core::async::Task { + std::ignore = co_await wire->write(std::as_bytes(std::span { Garbage })); + *out = !(co_await tls->waitReadable()).has_value(); + }; + REQUIRE(core::net::testing::blockOnWithin(loopback->loop, + watch(socket.get(), loopback->wire.get(), &failed), + core::net::testing::TlsExchangeBound)); + } + + CHECK(failed); + auto const failure = sessionOf(*socket).failure(); + REQUIRE(failure.has_value()); + CHECK(failure->kind == TlsFailureKind::Protocol); + CHECK_FALSE(failure->message.empty()); +} + +TEST_CASE("a name the wire cannot carry is refused before anything is sent", "[net][tls][tlspeer]") +{ + auto loopback = makeTlsLoopback(StrictTlsPeer::server(localhostMaterial())); + auto const context = clientTrusting(localhostMaterial().certPem); + + SECTION("an embedded NUL") + { + // It would cut the name short in SNI and in the check: a certificate for "127.0.0.1" + // accepted for a host that was asked for as something else. + auto const socket = context->wrapClient(std::move(loopback->transport), + loopback->loop, + { .serverName = std::string { "127.0.0.1\0.evil", 15 } }); + REQUIRE_FALSE(socket.has_value()); + CHECK(socket.error().code == NetErrorCode::AddressError); + } + + SECTION("a name longer than SNI's 255 bytes") + { + auto const socket = context->wrapClient(std::move(loopback->transport), + loopback->loop, + { .serverName = std::string(300, 'a') + ".test" }); + REQUIRE_FALSE(socket.has_value()); + CHECK(socket.error().code == NetErrorCode::AddressError); + } +} + +TEST_CASE("a client offers ALPN and reports what the server selected", "[net][tls][tlspeer][alpn]") +{ + auto loopback = makeTlsLoopback(StrictTlsPeer::server(localhostMaterial(), { .alpn = { "http/1.1" } })); + auto const context = clientTrusting(localhostMaterial().certPem, { .alpn = { "h2", "http/1.1" } }); + auto const socket = dial(*context, std::move(loopback->transport), loopback->loop, "localhost"); + + auto const outcome = handshakeBoth(*loopback, *socket); + REQUIRE(outcome.finished); + REQUIRE(outcome.local.has_value()); + CHECK(loopback->peer->negotiatedProtocol() == "http/1.1"); + REQUIRE(socket->tlsSession() != nullptr); + CHECK(sessionOf(*socket).negotiatedProtocol() == "http/1.1"); +} + +TEST_CASE("a pinned-name client context offers the ALPN names it was built with", "[net][tls][tlspeer][alpn]") +{ + auto loopback = makeTlsLoopback(StrictTlsPeer::server(localhostMaterial(), { .alpn = { "http/1.1" } })); + auto const context = + core::net::makeTlsClientContext(localhostMaterial().certPem, "localhost", { .alpn = { "http/1.1" } }); + REQUIRE(context.has_value()); + auto const socket = (*context)->wrap(std::move(loopback->transport), loopback->loop); + REQUIRE(socket != nullptr); + + auto const outcome = handshakeBoth(*loopback, *socket); + REQUIRE(outcome.finished); + REQUIRE(outcome.local.has_value()); + CHECK(sessionOf(*socket).negotiatedProtocol() == "http/1.1"); +} + +TEST_CASE("a client context refuses an ALPN name the wire cannot carry", "[net][tls][tlspeer][alpn]") +{ + auto anchors = core::net::trustAnchorsFromPem(localhostMaterial().certPem); + REQUIRE(anchors.has_value()); + CHECK_FALSE(core::net::makeTlsClientContext(*anchors, { .alpn = { "" } }).has_value()); + CHECK_FALSE(core::net::makeTlsClientContext(*anchors, { .alpn = { std::string(256, 'a') } }).has_value()); + CHECK(core::net::makeTlsClientContext(*anchors, { .alpn = { std::string(255, 'a') } }).has_value()); + + auto const& material = localhostMaterial(); + CHECK_FALSE(core::net::makeTlsClientContext(material.certPem, "", { .alpn = { "" } }).has_value()); + CHECK_FALSE( + core::net::makeTlsServerContext(material.certPem, material.keyPem, { .alpn = { "" } }).has_value()); + CHECK_FALSE(core::net::makeTlsServerContext( + material.certPem, material.keyPem, { .alpn = { std::string(256, 'a') } }) + .has_value()); +} + +TEST_CASE("a client context needs a trust anchor", "[net][tls][tlspeer]") +{ + // No anchor trusts nothing; a context that accepted it would either refuse every server or -- + // were "nothing configured" ever read as "verify nothing" -- accept every one. + CHECK_FALSE(core::net::makeTlsClientContext(core::net::TrustAnchors {}).has_value()); + CHECK_FALSE(core::net::trustAnchorsFromPem("").has_value()); + CHECK_FALSE( + core::net::trustAnchorsFromPem("-----BEGIN CERTIFICATE-----\nnope\n-----END CERTIFICATE-----\n") + .has_value()); + + auto const two = + core::net::trustAnchorsFromPem(localhostMaterial().certPem + localhostMaterial().certPem); + REQUIRE(two.has_value()); + CHECK(two->certificates.size() == 2); + // A block that is there and does not parse is an error, not the end of the bundle. + CHECK_FALSE( + core::net::trustAnchorsFromPem(localhostMaterial().certPem + + "-----BEGIN CERTIFICATE-----\nnope\n-----END CERTIFICATE-----\n") + .has_value()); + + // An anchor is one whole DER certificate: a byte after it is not part of any. + auto trailing = *two; + trailing.certificates.resize(1); + CHECK(core::net::makeTlsClientContext(trailing).has_value()); + trailing.certificates.front().push_back(std::byte { 0 }); + CHECK_FALSE(core::net::makeTlsClientContext(trailing).has_value()); +} + +TEST_CASE("a server context selects ALPN in its own order of preference", "[net][tls][tlspeer][alpn]") +{ + auto const server = core::net::makeTlsServerContext( + localhostMaterial().certPem, localhostMaterial().keyPem, { .alpn = { "http/1.1", "h2" } }); + REQUIRE(server.has_value()); + + SECTION("the first of its own names the client offered") + { + auto loopback = makeTlsLoopback(StrictTlsPeer::client({ .alpn = { "h2", "http/1.1" } })); + auto const socket = (*server)->wrap(std::move(loopback->transport), loopback->loop); + REQUIRE(socket != nullptr); + + auto const outcome = handshakeBoth(*loopback, *socket); + REQUIRE(outcome.finished); + REQUIRE(outcome.local.has_value()); + CHECK(loopback->peer->negotiatedProtocol() == "http/1.1"); + CHECK(sessionOf(*socket).negotiatedProtocol() == "http/1.1"); + } + + SECTION("no name in common is refused with no_application_protocol (RFC 7301)") + { + auto loopback = makeTlsLoopback(StrictTlsPeer::client({ .alpn = { "spdy/3" } })); + auto const socket = (*server)->wrap(std::move(loopback->transport), loopback->loop); + REQUIRE(socket != nullptr); + + auto const outcome = handshakeBoth(*loopback, *socket); + REQUIRE(outcome.finished); + CHECK_FALSE(outcome.local.has_value()); + REQUIRE_FALSE(outcome.peer.has_value()); + // The alert, by its words or, where OpenSSL has none for it (3.0), by its reason code: + // SSL_AD_REASON_OFFSET (1000) plus no_application_protocol (120). + INFO("the peer's error: " << outcome.peer.error()); + CHECK((outcome.peer.error().contains("no application protocol") + || outcome.peer.error().contains("reason(1120)"))); + } + + SECTION("a client that offers nothing is served without ALPN") + { + auto loopback = makeTlsLoopback(StrictTlsPeer::client()); + auto const socket = (*server)->wrap(std::move(loopback->transport), loopback->loop); + REQUIRE(socket != nullptr); + + auto const outcome = handshakeBoth(*loopback, *socket); + REQUIRE(outcome.finished); + CHECK(outcome.local.has_value()); + CHECK(sessionOf(*socket).negotiatedProtocol().empty()); + } +} + +TEST_CASE("a decorator forwards the TLS session, and tlsSessionOf sees through it", "[net][tls][tlspeer]") +{ + auto loopback = makeTlsLoopback(StrictTlsPeer::server(localhostMaterial())); + auto const context = clientTrusting(localhostMaterial().certPem); + auto const socket = dial(*context, std::move(loopback->transport), loopback->loop, "localhost"); + auto const outcome = handshakeBoth(*loopback, *socket); + REQUIRE(outcome.finished); + REQUIRE(outcome.local.has_value()); + + auto const decorated = core::net::testing::SocketDecorator { *socket }; + REQUIRE(socket->tlsSession() != nullptr); + CHECK(decorated.tlsSession() == socket->tlsSession()); + CHECK(core::net::tlsSessionOf(decorated) == socket->tlsSession()); + CHECK(core::net::tlsSessionOf(*socket) == socket->tlsSession()); + CHECK(loopback->wire->tlsSession() == nullptr); + CHECK(core::net::tlsSessionOf(*loopback->wire) == nullptr); +} + +TEST_CASE("a warning before a fatal alert is not the alert that ended the handshake", "[net][tls][tlspeer]") +{ + // A TLS 1.2 server may warn `unrecognized_name` (112) and carry on; this one then finds no ALPN + // name in common and refuses with `no_application_protocol` (120). The fatal one is the failure. + constexpr auto UnrecognizedName = std::uint8_t { 112 }; + constexpr auto NoApplicationProtocol = std::uint8_t { 120 }; + auto loopback = makeTlsLoopback(StrictTlsPeer::server(localhostMaterial(), + { .maximumVersion = core::net::TlsVersion::Tls12, + .alpn = { "spdy/3" }, + .warnWithAlert = UnrecognizedName })); + auto const context = clientTrusting(localhostMaterial().certPem, { .alpn = { "http/1.1" } }); + auto const socket = dial(*context, std::move(loopback->transport), loopback->loop, "localhost"); + + auto const outcome = handshakeBoth(*loopback, *socket); + REQUIRE(outcome.finished); + CHECK_FALSE(outcome.local.has_value()); + auto const failure = sessionOf(*socket).failure(); + REQUIRE(failure.has_value()); + CHECK(failure->kind == TlsFailureKind::AlertReceived); + CHECK(failure->alert == NoApplicationProtocol); +} + +TEST_CASE("failure() keeps the first failure", "[net][tls][tlspeer]") +{ + // The record that broke the connection is the failure; what a later call on the broken session + // answers is a consequence of it, not a second cause. + auto loopback = makeTlsLoopback(StrictTlsPeer::server(localhostMaterial())); + auto const trusting = core::net::makeTlsClientContext(); + REQUIRE(trusting.has_value()); + auto const socket = (*trusting)->wrap(std::move(loopback->transport), loopback->loop); + REQUIRE(socket != nullptr); + REQUIRE(handshakeBoth(*loopback, *socket).local.has_value()); + + static constexpr auto Garbage = + std::array { 0x17, 0x03, 0x03, 0x00, 0x05, 'n', 'o', 'p', 'e', '!' }; + auto const readTwice = [](ISocket* tls, + ISocket* wire, + std::optional* first, + bool* secondFailed) -> core::async::Task { + std::ignore = co_await wire->write(std::as_bytes(std::span { Garbage })); + auto buffer = std::array {}; + std::ignore = co_await tls->read(buffer); + *first = sessionOf(*tls).failure(); + *secondFailed = !(co_await tls->read(buffer)).has_value(); + }; + auto first = std::optional {}; + auto secondFailed = false; + REQUIRE(core::net::testing::blockOnWithin( + loopback->loop, + readTwice(socket.get(), loopback->wire.get(), &first, &secondFailed), + core::net::testing::TlsExchangeBound)); + REQUIRE(first.has_value()); + CHECK(secondFailed); + auto const kept = sessionOf(*socket).failure(); + REQUIRE(kept.has_value()); + CHECK(kept->kind == first->kind); + CHECK(kept->message == first->message); +} + +TEST_CASE("a transport that ends mid-handshake is no TLS failure", "[net][tls][tlspeer]") +{ + // The peer read the ClientHello and went away: the operation's NetError says so, and failure() + // stays empty -- an https client maps it to a connection error, not a TLS one. + auto loopback = makeTlsLoopback(StrictTlsPeer::server(localhostMaterial())); + auto const context = clientTrusting(localhostMaterial().certPem); + auto const socket = dial(*context, std::move(loopback->transport), loopback->loop, "localhost"); + + auto result = std::expected {}; + auto const client = [](ISocket* tls, + std::expected* out) -> core::async::Task { + *out = co_await tls->handshakeIfNeeded(); + }; + + SECTION("an orderly end: the whole ClientHello read, then a FIN") + { + auto const hangUp = [](ISocket* wire) -> core::async::Task { + auto buffer = std::array {}; + std::ignore = co_await wire->read(buffer); // the whole flight, written at once + std::ignore = co_await wire->shutdownWrite(); + }; + REQUIRE(core::net::testing::blockOnWithin( + loopback->loop, + core::net::testing::allOf(client(socket.get(), &result), hangUp(loopback->wire.get())), + core::net::testing::TlsExchangeBound)); + REQUIRE_FALSE(result.has_value()); + CHECK(result.error().code == NetErrorCode::Eof); + } + + SECTION("a reset: closed with the ClientHello half read") + { + auto const hangUp = [](ISocket* wire) -> core::async::Task { + auto buffer = std::array {}; + std::ignore = co_await wire->read(buffer); + wire->close(); + }; + REQUIRE(core::net::testing::blockOnWithin( + loopback->loop, + core::net::testing::allOf(client(socket.get(), &result), hangUp(loopback->wire.get())), + core::net::testing::TlsExchangeBound)); + REQUIRE_FALSE(result.has_value()); + // A reset where the pair resets; where it only ends (macOS's AF_UNIX), the end it is. + if constexpr (core::net::testing::NativeUnreadClose == core::net::testing::UnreadClose::Resets) + CHECK(result.error().code != NetErrorCode::Eof); + else + CHECK(result.error().code == NetErrorCode::Eof); + } + + CHECK_FALSE(sessionOf(*socket).failure().has_value()); +} + +TEST_CASE("a server's ALPN choice is its own first name the client offered", "[net][tls][alpn]") +{ + auto const own = core::net::detail::alpnWireFormat(std::vector { "http/1.1", "h2" }); + REQUIRE(own.has_value()); + auto const chosen = [&](std::vector const& offered) -> std::string { + auto const name = core::net::detail::selectAlpn(*own, offered); + return name ? std::string { name->begin(), name->end() } : std::string { "" }; + }; + auto const wire = [](std::vector const& names) { + auto encoded = core::net::detail::alpnWireFormat(names); + REQUIRE(encoded.has_value()); + return *encoded; + }; + + CHECK(chosen(wire({ "h2", "http/1.1" })) == "http/1.1"); + CHECK(chosen(wire({ "h2" })) == "h2"); + CHECK(chosen(wire({ "spdy/3" })) == ""); + CHECK(chosen({}) == ""); + // A malformed list ends where it stops parsing: a length that runs past the end, or a zero + // length, hides what follows rather than being read through. + CHECK(chosen({ 9, 'h', 't', 't', 'p', '/', '1', '.', '1' }) == ""); + CHECK(chosen({ 0, 2, 'h', '2' }) == ""); + CHECK(chosen({ 255, 2, 'h', '2' }) == ""); + // A prefix of a name is not the name. + CHECK(chosen({ 4, 'h', 't', 't', 'p' }) == ""); + CHECK(core::net::detail::selectAlpn({}, wire({ "h2" })) == std::nullopt); +} + +namespace +{ + +/// A transport that breaks once the peer has spoken: every write after a read has returned bytes +/// fails. Keyed to that STATE, not to a count of writes, so however a TLS library splits its first +/// flight, what fails is the flight after the server's -- the alert a refused certificate queues. +class FailingOncePeerSpoke final: public core::net::testing::SocketDecorator +{ + public: + using SocketDecorator::SocketDecorator; + + [[nodiscard]] core::net::IoAwaitable read(std::span buffer) override + { + return core::net::IoAwaitable { observedRead(buffer) }; + } + + [[nodiscard]] core::net::IoAwaitable write(std::span buffer) override + { + if (!peerSpoke) + return SocketDecorator::write(buffer); + ++refusedWrites; + return core::net::IoAwaitable { std::unexpected( + core::net::makeNetError(NetErrorCode::ConnReset, 0, "the transport broke")) }; + } + + bool peerSpoke = false; + int refusedWrites = 0; + + private: + core::async::Task observedRead(std::span buffer) + { + auto const n = co_await SocketDecorator::read(buffer); + if (n && *n > 0) + peerSpoke = true; + co_return n; + } +}; + +} // namespace + +TEST_CASE("a handshake failure is classified even when its alert cannot be sent", "[net][tls][tlspeer]") +{ + // The client refuses an untrusted certificate and queues a fatal alert; flushing it fails. The + // refusal is what ended the handshake, and the transport's failure must not hide it. + auto const stranger = core::net::generateSelfSignedCertificate({ .commonName = "stranger" }); + REQUIRE(stranger.has_value()); + auto loopback = makeTlsLoopback(StrictTlsPeer::server(localhostMaterial())); + auto failing = std::make_unique(*loopback->transport); + auto const* const transport = failing.get(); + auto const context = clientTrusting(stranger->certPem); + auto const socket = dial(*context, std::move(failing), loopback->loop, "localhost"); + + auto result = std::expected {}; + auto const local = [](ISocket* tls, + std::expected* out) -> core::async::Task { + *out = co_await tls->handshakeIfNeeded(); + }; + // The server never hears the alert, so it waits for the client's Finished; it loses the race. + auto const remote = [](StrictTlsPeer* peer, ISocket* wire) -> core::async::Task { + std::ignore = co_await peer->handshake(wire); + }; + REQUIRE(core::net::testing::blockOnWithin( + loopback->loop, + core::net::testing::anyOf(local(socket.get(), &result), + remote(loopback->peer.get(), loopback->wire.get())), + core::net::testing::TlsExchangeBound)); + + CHECK(transport->refusedWrites >= 1); // the flush after the server's flight was refused + REQUIRE_FALSE(result.has_value()); + CHECK(result.error().code == NetErrorCode::ConnReset); + auto const failure = sessionOf(*socket).failure(); + REQUIRE(failure.has_value()); + CHECK(failure->kind == TlsFailureKind::Certificate); +} diff --git a/src/core/net/TlsSession_test.cpp b/src/core/net/TlsSession_test.cpp index 060b526a..76226119 100644 --- a/src/core/net/TlsSession_test.cpp +++ b/src/core/net/TlsSession_test.cpp @@ -50,7 +50,7 @@ struct Session std::unique_ptr client; core::net::CertKeyPem material; - Session(TlsOptions serverOptions, bool handshake) + Session(TlsOptions const& serverOptions, bool handshake) { auto generated = core::net::generateSelfSignedCertificate(); REQUIRE(generated.has_value()); @@ -100,7 +100,7 @@ TEST_CASE("a TLS 1.3-only server refuses a 1.2-only client", "[net][tls][session auto server = (*context)->wrap(std::move(pair->first), loop); auto wire = std::move(pair->second); REQUIRE(server != nullptr); - auto peer = StrictTlsPeer::client(TlsVersion::Tls12); + auto peer = StrictTlsPeer::client({ .maximumVersion = TlsVersion::Tls12 }); REQUIRE(peer.has_value()); auto serverOk = true; @@ -238,7 +238,7 @@ TEST_CASE("channelBinding of a TLS 1.2 session is an error", "[net][tls][session auto server = (*context)->wrap(std::move(pair->first), loop); auto wire = std::move(pair->second); REQUIRE(server != nullptr); - auto peer = StrictTlsPeer::client(TlsVersion::Tls12); + auto peer = StrictTlsPeer::client({ .maximumVersion = TlsVersion::Tls12 }); REQUIRE(peer.has_value()); auto const outcome = shakeWithPeer(loop, server.get(), peer->get(), wire.get()); @@ -265,7 +265,7 @@ TEST_CASE("a TLS 1.3-only client refuses a 1.2-only server", "[net][tls][session auto client = (*context)->wrap(std::move(pair->first), loop); auto wire = std::move(pair->second); REQUIRE(client != nullptr); - auto peer = StrictTlsPeer::server(*material, TlsVersion::Tls12); + auto peer = StrictTlsPeer::server(*material, { .maximumVersion = TlsVersion::Tls12 }); REQUIRE(peer.has_value()); auto const outcome = shakeWithPeer(loop, client.get(), peer->get(), wire.get()); diff --git a/src/core/net/TlsTestSupport.hpp b/src/core/net/TlsTestSupport.hpp new file mode 100644 index 00000000..ff1c94e4 --- /dev/null +++ b/src/core/net/TlsTestSupport.hpp @@ -0,0 +1,168 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// `TlsLoopback` -- a TLS socket under test on one end of a real socket pair, a +/// `testing::StrictTlsPeer` on the other, and the loop both run on -- the bounded handshake the +/// `net_tls` cases drive it with, and `ScriptedChainVerifier`, an `IChainVerifier` whose verdict +/// the case chooses. +/// +/// Test-only, beside the tests, because it needs Catch2: it is compiled into no module. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace core::net::testing +{ + +/// What the peer of a socket-pair end hears when that end is closed with bytes still unread. +enum class UnreadClose : std::uint8_t +{ + Ends, ///< An end of stream: an AF_UNIX pair on macOS and the BSDs. + Resets, ///< A reset: an AF_UNIX pair on Linux, and Windows' pair, which is TCP. +}; + +/// What closing with bytes unread is on this system's socket pair. +#if defined(__linux__) || defined(_WIN32) +inline constexpr auto NativeUnreadClose = UnreadClose::Resets; +#else +inline constexpr auto NativeUnreadClose = UnreadClose::Ends; +#endif + +/// How long one handshake may take before a case fails rather than hangs: a regression in a +/// handshake does not fail, it parks a peer waiting for a flight nobody sends. +inline constexpr auto TlsExchangeBound = std::chrono::milliseconds { 10'000 }; + +/// A real socket pair on a loop: @c transport for the code under test to wrap, @c wire for the +/// strict peer to speak TLS over. +struct TlsLoopback +{ + std::unique_ptr backend = makeDefaultBackend(); + EventLoop loop { *backend }; + std::unique_ptr transport; ///< The end the context under test wraps; moved out by it. + std::unique_ptr wire; ///< The strict peer's plaintext end. + std::unique_ptr peer; ///< The other end of the TLS conversation. +}; + +/// Builds a loopback around @p peer, connected and not yet handshaken. +/// @param peer The strict peer, as its factory answered. +/// @return The loopback; the case fails here if the pair or the peer could not be made. +[[nodiscard]] inline std::unique_ptr makeTlsLoopback( + std::expected, std::string> peer) +{ + REQUIRE(peer.has_value()); + auto loopback = std::make_unique(); + auto pair = makeSocketPair(loopback->loop); + REQUIRE(pair.has_value()); + loopback->transport = std::move(pair->first); + loopback->wire = std::move(pair->second); + loopback->peer = std::move(*peer); + return loopback; +} + +/// What each end of one handshake answered. +struct HandshakeOutcome +{ + bool finished = false; ///< Both ends answered in time. + std::expected local = std::unexpected(makeNetError(NetErrorCode::Timeout)); + std::expected peer = std::unexpected(std::string { "never answered" }); +}; + +/// Runs @p socket's handshake against the loopback's peer, both at once, bounded. +/// @param loopback The loopback @p socket was wrapped from. +/// @param socket The TLS socket under test. +/// @return What each end answered. +[[nodiscard]] inline HandshakeOutcome handshakeBoth(TlsLoopback& loopback, ISocket& socket) +{ + auto outcome = HandshakeOutcome {}; + auto const local = [](ISocket* tls, std::expected* out) -> async::Task { + *out = co_await tls->handshakeIfNeeded(); + }; + auto const remote = + [](StrictTlsPeer* peer, ISocket* wire, std::expected* out) -> async::Task { + *out = co_await peer->handshake(wire); + }; + outcome.finished = blockOnWithin(loopback.loop, + allOf(local(&socket, &outcome.local), + remote(loopback.peer.get(), loopback.wire.get(), &outcome.peer)), + TlsExchangeBound); + return outcome; +} + +/// What a @c ScriptedChainVerifier answers. +enum class ChainVerdict : std::uint8_t +{ + Refuse = 0, ///< Every chain is refused, as a platform verifier refuses an untrusted one. + RefuseAsProtocol, ///< Refused, but misclassified as @c TlsFailureKind::Protocol. + Accept, ///< Every chain is accepted. +}; + +/// An @c IChainVerifier whose verdict the case chooses, and which records what it was asked. +/// +/// It answers from the BLOCKING executor, and finishes there, as the platform verifiers do: +/// a case can therefore hold the verification open -- the blocking executor's @c pending() is 1 -- +/// and look at what the socket did meanwhile. +class ScriptedChainVerifier final: public IChainVerifier +{ + public: + /// The message a refusal carries. + static constexpr auto RefusalMessage = std::string_view { "scripted refusal" }; + + /// @param verdict What every verification answers. + /// @param blocking Where it runs; the case drains it. + ScriptedChainVerifier(ChainVerdict verdict, async::IExecutor& blocking) noexcept: + _verdict { verdict }, _blocking { &blocking } + { + } + + [[nodiscard]] async::Task> verify(std::vector chain, + std::string serverName) override + { + co_await async::ResumeOn { *_blocking }; + chains.push_back(std::move(chain)); + serverNames.push_back(std::move(serverName)); + co_return answer(); + } + + std::vector> chains; ///< Every chain it was asked about, in order. + std::vector serverNames; ///< The name each one was asked for. + + private: + [[nodiscard]] std::expected answer() const + { + if (_verdict == ChainVerdict::Accept) + return {}; + return std::unexpected(TlsFailure { .kind = _verdict == ChainVerdict::RefuseAsProtocol + ? TlsFailureKind::Protocol + : TlsFailureKind::Certificate, + .alert = std::nullopt, + .message = std::string { RefusalMessage } }); + } + + ChainVerdict _verdict; + async::IExecutor* _blocking; +}; + +} // namespace core::net::testing diff --git a/src/core/net/TrustStore.cpp b/src/core/net/TrustStore.cpp new file mode 100644 index 00000000..86acbaaf --- /dev/null +++ b/src/core/net/TrustStore.cpp @@ -0,0 +1,241 @@ +// SPDX-License-Identifier: Apache-2.0 +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace core::net +{ + +namespace +{ + /// Every place a system keeps its anchors, bundles first. A row is a fact about a distribution, + /// so a new one is a line here and nothing else. + constexpr auto Locations = std::array { + TrustBundleLocation { .path = "/etc/ssl/certs/ca-certificates.crt", + .distribution = "Debian, Ubuntu, Arch, Gentoo", + .kind = TrustBundleKind::Bundle }, + TrustBundleLocation { .path = "/etc/pki/tls/certs/ca-bundle.crt", + .distribution = "Fedora, RHEL", + .kind = TrustBundleKind::Bundle }, + TrustBundleLocation { .path = "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", + .distribution = "RHEL 7 and later", + .kind = TrustBundleKind::Bundle }, + TrustBundleLocation { + .path = "/etc/ssl/ca-bundle.pem", .distribution = "openSUSE", .kind = TrustBundleKind::Bundle }, + TrustBundleLocation { .path = "/etc/ssl/cert.pem", + .distribution = "Alpine, FreeBSD with ca_root_nss, OpenBSD", + .kind = TrustBundleKind::Bundle }, + TrustBundleLocation { .path = "/usr/local/share/certs/ca-root-nss.crt", + .distribution = "FreeBSD's ca_root_nss package", + .kind = TrustBundleKind::Bundle }, + TrustBundleLocation { .path = "/etc/ssl/certs", + .distribution = "FreeBSD's certctl, and any hashed system directory", + .kind = TrustBundleKind::HashedDirectory }, + }; + + /// The environment variables OpenSSL reads, in the order they decide. + struct TrustVariable + { + std::string_view name; + TrustBundleKind kind; + }; + + constexpr auto Variables = std::array { + TrustVariable { .name = "SSL_CERT_FILE", .kind = TrustBundleKind::Bundle }, + TrustVariable { .name = "SSL_CERT_DIR", .kind = TrustBundleKind::HashedDirectory }, + }; + + /// Whether @p name is what OpenSSL looks a certificate up by in a hashed directory: + /// `<8 lower-case hex digits>.`. + [[nodiscard]] bool isHashedCertificateName(std::string_view name) noexcept + { + constexpr auto HashDigits = std::size_t { 8 }; + if (name.size() < HashDigits + 2 || name[HashDigits] != '.') + return false; + auto const isLowerHex = [](char c) { + return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'); + }; + auto const isDecimal = [](char c) { + return c >= '0' && c <= '9'; + }; + return std::ranges::all_of(name.substr(0, HashDigits), isLowerHex) + && std::ranges::all_of(name.substr(HashDigits + 1), isDecimal); + } + + /// The store @c makePemTrustStore answers: its bundle, parsed on the caller's executor. + class PemTrustStore final: public ITrustStore + { + public: + explicit PemTrustStore(std::string pem) noexcept: _pem { std::move(pem) } {} + + [[nodiscard]] async::Task> load() override + { + co_return trustAnchorsFromPem(_pem); + } + + private: + std::string _pem; + }; + + /// The store @c makeFileTrustStore answers. + class FileTrustStore final: public ITrustStore + { + public: + FileTrustStore(platform::FileSystem const& files, + Environment const& environment, + async::IExecutor& home, + async::IExecutor& blocking) noexcept: + _files { &files }, _environment { &environment }, _home { &home }, _blocking { &blocking } + { + } + + [[nodiscard]] async::Task> load() override + { + co_return co_await async::offload(_home, _blocking, [this] { return loadNow(); }); + } + + private: + /// Decides the source and reads it, on the blocking executor. + [[nodiscard]] std::expected loadNow() const + { + for (auto const& variable: Variables) + { + auto value = _environment->get(variable.name); + if (!value || value->empty()) + continue; + // Named means chosen: a file that is not there is an error, never a fallback. + return read(*value, variable.kind, std::string { variable.name } + " names"); + } + for (auto const& location: Locations) + { + auto const path = std::filesystem::path { location.path }; + auto const present = location.kind == TrustBundleKind::Bundle ? _files->isRegularFile(path) + : _files->isDirectory(path); + if (present) + return read(std::string { location.path }, + location.kind, + "the trust store of " + std::string { location.distribution } + " at"); + } + return std::unexpected(std::string { + "no trust store: SSL_CERT_FILE and SSL_CERT_DIR are unset, and none of the known bundle " + "locations exists" }); + } + + /// Reads one source, prefixing a failure with @p origin and the path. + [[nodiscard]] std::expected read(std::string const& path, + TrustBundleKind kind, + std::string const& origin) const + { + auto anchors = kind == TrustBundleKind::Bundle ? readBundle(path, MaxTrustBundleBytes) + : readHashedDirectory(path); + if (!anchors) + return std::unexpected(origin + " '" + path + "': " + anchors.error()); + return anchors; + } + + /// The size of the regular file at @p path, refused above @p limit before anything is read. + [[nodiscard]] std::expected boundedSize( + std::filesystem::path const& path, std::uintmax_t limit) const + { + // A regular file and nothing else: a device or a FIFO named here would be read for ever. + if (!_files->isRegularFile(path)) + return std::unexpected(std::string { "not a readable regular file" }); + auto size = _files->fileSize(path); + if (!size) + return std::unexpected(std::move(size.error())); + if (*size > limit) + return std::unexpected( + std::format("{} bytes, more than the {} a trust store reads", *size, limit)); + return size; + } + + [[nodiscard]] std::expected readBundle(std::filesystem::path const& path, + std::uintmax_t limit) const + { + return boundedSize(path, limit) + .and_then([&](std::uintmax_t /*size*/) { return _files->readFile(path); }) + .and_then([](std::string const& pem) { return trustAnchorsFromPem(pem); }); + } + + [[nodiscard]] std::expected readHashedDirectory( + std::filesystem::path const& path) const + { + auto entries = _files->listDirectory(path); + if (!entries) + return std::unexpected(std::move(entries.error())); + auto names = std::vector {}; + for (auto const& entry: *entries) + if (!entry.isDirectory && isHashedCertificateName(core::pathToUtf8(entry.path.filename()))) + names.push_back(entry.path); + // Every size before any read, so a directory over its budget is refused unread. + auto total = std::uintmax_t { 0 }; + for (auto const& name: names) + { + auto const size = boundedSize(name, MaxTrustBundleBytes); + if (!size) + return std::unexpected(core::pathToUtf8(name.filename()) + ": " + size.error()); + total += *size; + if (total > MaxTrustDirectoryBytes) + return std::unexpected( + std::format("its hashed files hold more than the {} bytes a trust store reads", + MaxTrustDirectoryBytes)); + } + auto anchors = TrustAnchors {}; + for (auto const& name: names) + { + // Every hashed file, or none: one that does not read is a refusal, not a gap. + auto one = readBundle(name, MaxTrustBundleBytes); + if (!one) + return std::unexpected(core::pathToUtf8(name.filename()) + ": " + one.error()); + std::ranges::move(one->certificates, std::back_inserter(anchors.certificates)); + } + if (anchors.certificates.empty()) + return std::unexpected(std::string { "no hashed certificate (.) in the directory" }); + return anchors; + } + + platform::FileSystem const* _files; + Environment const* _environment; + async::IExecutor* _home; + async::IExecutor* _blocking; + }; +} // namespace + +std::unique_ptr makePemTrustStore(std::string pem) +{ + return std::make_unique(std::move(pem)); +} + +std::span trustBundleLocations() noexcept +{ + return Locations; +} + +std::unique_ptr makeFileTrustStore(platform::FileSystem const& files, + Environment const& environment, + async::IExecutor& home, + async::IExecutor& blocking) +{ + return std::make_unique(files, environment, home, blocking); +} + +} // namespace core::net diff --git a/src/core/net/TrustStore.hpp b/src/core/net/TrustStore.hpp new file mode 100644 index 00000000..273458d9 --- /dev/null +++ b/src/core/net/TrustStore.hpp @@ -0,0 +1,153 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// Where a verifying TLS client's trust comes from: a PEM bundle in memory, the bundle or hashed +/// directory a POSIX system keeps, or -- on macOS and Windows -- the platform's own verifier. +/// +/// **Every source fails closed.** An environment variable that names a file that is not there, an +/// empty store, a file that cannot be read and a bundle that does not parse are each an error, never +/// a quiet fallback to the next source and never a context that trusts nothing in particular. +/// +/// Reading files is blocking, so a store that reads them does it on an injected blocking executor +/// through @c async::offload, and answers on the home one: a caller on a loop never waits on a disk. + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace core::net +{ + +/// Loads the anchors a verifying client trusts. +class ITrustStore +{ + public: + ITrustStore() = default; + virtual ~ITrustStore() = default; + ITrustStore(ITrustStore const&) = delete; + ITrustStore& operator=(ITrustStore const&) = delete; + ITrustStore(ITrustStore&&) = delete; + ITrustStore& operator=(ITrustStore&&) = delete; + + /// Loads the anchors, off the loop where it reads files. The store must outlive the task. + /// @return The anchors, at least one; or a human-readable reason naming the source that failed. + [[nodiscard]] virtual async::Task> load() = 0; +}; + +/// A store over a PEM bundle held in memory; it reads no file, so it answers without a hop. +/// @param pem One or more PEM certificates. +/// @return The store. Its @c load answers what @c trustAnchorsFromPem answers for @p pem. +[[nodiscard]] CORE_NET_TLS_API std::unique_ptr makePemTrustStore(std::string pem); + +/// What a trust location on disk holds. +enum class TrustBundleKind : std::uint8_t +{ + /// One file of concatenated PEM certificates. + Bundle = 0, + /// A directory OpenSSL's `c_rehash`/`certctl` keeps: each certificate as `.` + /// (eight lower-case hex digits, a dot, a decimal number). Only files named so are read; the + /// PEM files they link to, CRLs (`.r`) and anything else are not. + HashedDirectory, +}; + +/// One place a system keeps its trust anchors. +struct TrustBundleLocation +{ + std::string_view path; ///< Where, absolute. + std::string_view distribution; ///< Which systems keep it there, for the reader of a failure. + TrustBundleKind kind = TrustBundleKind::Bundle; ///< A bundle file or a hashed directory. +}; + +/// The trust locations @c makeFileTrustStore looks in, in the order it looks. Every bundle comes +/// before any directory: where a system has both (Debian's `/etc/ssl/certs` holds its bundle), the +/// bundle is the one file to read. +/// @return The table; static, and the same on every OS. +[[nodiscard]] CORE_NET_TLS_API std::span trustBundleLocations() noexcept; + +/// The largest bundle file @c makeFileTrustStore reads: 16 MiB. A system bundle of every public +/// root is about 0.25 MiB, so this is room for a large private one, not a limit anyone meets; what +/// it stops is a misnamed file (a log, a disk image) being read whole into memory. +inline constexpr auto MaxTrustBundleBytes = std::uintmax_t { 16 } * 1024 * 1024; + +/// The most a hashed directory's files may hold together: 16 MiB, as @c MaxTrustBundleBytes. +inline constexpr auto MaxTrustDirectoryBytes = std::uintmax_t { 16 } * 1024 * 1024; + +/// A store over the files a POSIX system keeps its anchors in, as OpenSSL finds them. +/// +/// The first of these that is SET decides, and a later one is never consulted: +/// 1. `SSL_CERT_FILE`, a bundle. It must be a regular file that can be read. +/// 2. `SSL_CERT_DIR`, ONE hashed directory (a `:`-separated list is not split, so it names no +/// directory and is refused). It must hold at least one hashed file, and every one must be read. +/// 3. Otherwise, the first row of @c trustBundleLocations that exists -- a regular file for a +/// bundle, a directory for a hashed directory -- read as above; a row that exists but does not +/// read is the answer, not a reason to try the next. +/// +/// A bundle larger than @c MaxTrustBundleBytes, or a directory whose hashed files together exceed +/// @c MaxTrustDirectoryBytes, is refused before it is read; the sizes come from +/// @c platform::FileSystem::fileSize. +/// +/// **What refusing a whole directory costs.** OpenSSL skips a hashed file it cannot use; this +/// refuses the directory, so ONE broken link or corrupt file in `/etc/ssl/certs` -- a package +/// half-removed, a typo in a hand-added certificate -- takes away every anchor until it is fixed, +/// and every verifying connection fails rather than some. That is the price of the alternative's +/// failure being silent: a skipped file is an anchor the operator believes is trusted and is not, +/// or the one certificate that made a private service reachable. The error names the file. +/// +/// A variable set to the empty string counts as unset. Portable: it reads through @p files, so it +/// runs, and is tested, on every OS. +/// @param files Where the files are read; must outlive the store. +/// @param environment Where the two variables are read; must outlive the store. +/// @param home Where @c ITrustStore::load resumes; must outlive the store. +/// @param blocking Where the files are read; must outlive the store. +/// @return The store. +[[nodiscard]] CORE_NET_TLS_API std::unique_ptr makeFileTrustStore( + platform::FileSystem const& files, + Environment const& environment, + async::IExecutor& home, + async::IExecutor& blocking); + +/// Builds the verifying client context this operating system's own trust settings call for. +/// +/// - **macOS** (Security.framework) and **Windows** (CryptoAPI): a platform @c IChainVerifier, which +/// runs and finishes on @p blocking -- each socket's wait for it is handed back to that socket's +/// own loop -- so the Disallowed store and the user's trust settings are honoured. @p files and +/// @p environment are not read. +/// - **Every other system**: the anchors @c makeFileTrustStore loads over @p files and +/// @p environment, read on @p blocking. +/// +/// **An incomplete chain is refused everywhere.** No platform fetches a missing intermediate from +/// the Authority Information Access URL a server's certificate names: OpenSSL never does, and the +/// platform verifiers turn it off (`CERT_CHAIN_DISABLE_AIA` on Windows, +/// `SecTrustSetNetworkFetchAllowed(false)` on macOS), so verifying a chain sends no request to a host +/// the server chose. A server must send its intermediates. +/// +/// One CMake-selected `SystemTrust.cpp` decides, never an `#ifdef`. +/// @param files Where bundles are read; non-null where it is read, and outliving the task. +/// @param environment Where `SSL_CERT_FILE`/`SSL_CERT_DIR` are read; as @p files. +/// @param home Where THIS task resumes once the anchors are read, and nothing more: the factory's +/// own resume point, outliving the task. The context does not keep it, and its sockets' +/// verifications never resume on it; each socket's waiters go back to the loop it was +/// wrapped on. Non-null. +/// @param blocking Where files are read and chains verified. Non-null, and outliving the context. +/// @param options The protocol floor and the ALPN names offered. +/// @return The context, or why there is nothing to trust (no configuration found, a file that does +/// not read). +[[nodiscard]] CORE_NET_TLS_API async::Task, std::string>> +makeSystemTlsClientContext(platform::FileSystem const* files, + Environment const* environment, + async::IExecutor* home, + async::IExecutor* blocking, + TlsClientOptions options); + +} // namespace core::net diff --git a/src/core/net/TrustStore_test.cpp b/src/core/net/TrustStore_test.cpp new file mode 100644 index 00000000..39c2228f --- /dev/null +++ b/src/core/net/TrustStore_test.cpp @@ -0,0 +1,1055 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// Trust, and that it fails closed. +// +// A file trust store reads its anchors from what the environment names, or else from the first +// bundle the distribution table finds; a name that is set but leads nowhere, an empty store, an +// unreadable file and a malformed bundle are each a refusal, never a quiet fallback to the next +// source. Every case runs over `platform::testing::InMemoryFileSystem` and +// `core::testing::FakeEnvironment`, so it runs the same on every OS and touches no real file. +// +// A context built over an `IChainVerifier` -- what macOS and Windows use, so the platform's own +// trust settings decide -- completes the TLS handshake with OpenSSL's chain check off and moves no +// application byte until the verifier has answered: `ScriptedChainVerifier` answers from a blocking +// executor the case drains by hand, so "before it answered" is a state the case can stand in. +#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 +#include +#include +#include + +#include "TlsTestSupport.hpp" + +using core::async::testing::ManualExecutor; +using core::net::CertKeyPem; +using core::net::IChainVerifier; +using core::net::ISocket; +using core::net::ITlsContext; +using core::net::NetErrorCode; +using core::net::TlsFailureKind; +using core::net::TrustAnchors; +using core::net::TrustBundleKind; +using core::net::testing::ChainVerdict; +using core::net::testing::makeTlsLoopback; +using core::net::testing::ScriptedChainVerifier; +using core::net::testing::StreamEnd; +using core::net::testing::StrictTlsPeer; +using core::platform::testing::InMemoryFileSystem; +using core::testing::FakeEnvironment; + +namespace +{ + +/// A certificate of its own for each of three indices, so a case can tell which bundle was read by +/// what it holds. Generated once: cheap, but not free. +CertKeyPem const& material(std::size_t index) +{ + static auto const materials = [] { + auto generated = std::array {}; + for (auto& one: generated) + { + auto made = core::net::generateSelfSignedCertificate( + { .commonName = "localhost", .subjectNames = { "localhost", "127.0.0.1" } }); + REQUIRE(made.has_value()); + one = std::move(*made); + } + return generated; + }(); + return materials.at(index); +} + +/// A certificate for every name the name table asks about: a DNS name and three addresses. +CertKeyPem const& everyNameMaterial() +{ + static auto const material = [] { + auto made = core::net::generateSelfSignedCertificate( + { .commonName = "localhost", .subjectNames = { "localhost", "127.0.0.1", "::1", "fe80::1" } }); + REQUIRE(made.has_value()); + return *made; + }(); + return material; +} + +/// A certificate whose only DNS-looking name is its common name: its one subjectAltName is an +/// address. RFC 9525 never reads the common name as a name. +CertKeyPem const& commonNameOnlyMaterial() +{ + static auto const material = [] { + auto made = core::net::generateSelfSignedCertificate( + { .commonName = "localhost", .subjectNames = { "127.0.0.1" } }); + REQUIRE(made.has_value()); + return *made; + }(); + return material; +} + +std::string const& pem(std::size_t index) +{ + return material(index).certPem; +} + +/// The DER of @p pemText's one certificate. +core::net::DerCertificate derOf(std::string_view pemText) +{ + auto anchors = core::net::trustAnchorsFromPem(pemText); + REQUIRE(anchors.has_value()); + REQUIRE(anchors->certificates.size() == 1); + return std::move(anchors->certificates.front()); +} + +/// What a file trust store's `load()` answered, and whether it went through the blocking executor. +struct LoadOutcome +{ + std::expected anchors = std::unexpected(std::string { "never answered" }); + bool offloaded = false; ///< The blocking executor held the work before anything was read. +}; + +/// Loads the file trust store over @p files and @p environment, draining both executors by hand. +LoadOutcome loadFileStore(core::platform::FileSystem const& files, core::Environment const& environment) +{ + auto home = ManualExecutor {}; + auto blocking = ManualExecutor {}; + auto const store = core::net::makeFileTrustStore(files, environment, home, blocking); + REQUIRE(store != nullptr); + auto task = store->load(); + task.handle().resume(); + auto outcome = LoadOutcome {}; + outcome.offloaded = !task.done() && blocking.pending() == 1 && home.pending() == 0; + blocking.drain(); + home.drain(); + REQUIRE(task.done()); + outcome.anchors = task.result(); + return outcome; +} + +/// The anchors' count, or -1 for a refusal -- so a refusal and a wrong count read differently. +int anchorCount(LoadOutcome const& outcome) +{ + return outcome.anchors ? static_cast(outcome.anchors->certificates.size()) : -1; +} + +/// Builds a verifying client over @p verifier. +std::shared_ptr clientOver(std::shared_ptr verifier, + core::net::TlsClientOptions const& options = {}) +{ + auto context = core::net::makeTlsClientContext(std::move(verifier), options); + REQUIRE(context.has_value()); + return std::move(*context); +} + +std::span asBytes(std::string_view text) +{ + return std::as_bytes(std::span { text.data(), text.size() }); +} + +/// What one exchange through a verifier-checked client saw. +struct VerifiedExchange +{ + bool finished = false; ///< All three parties answered within the bound. + bool verifierHeld = false; ///< The verification was parked on the blocking executor. + std::size_t receivedWhileHeld = 1; ///< Plaintext bytes the server had while it was parked. + std::expected written = + std::unexpected(core::net::makeNetError(NetErrorCode::Timeout)); + std::string received; ///< Every plaintext byte the server read. + StreamEnd end = StreamEnd::Failed; ///< How the server's stream ended. +}; + +/// Writes `hello` through @p socket to the loopback's server, holding the verification open until +/// the case has looked, then ends the stream: with `close_notify` if the write went through, by +/// closing the transport if it did not. +VerifiedExchange exchangeThroughVerifier(core::net::testing::TlsLoopback& loopback, + ISocket& socket, + ManualExecutor& blocking) +{ + auto outcome = VerifiedExchange {}; + auto const local = [](ISocket* tls, VerifiedExchange* out) -> core::async::Task { + out->written = co_await tls->write(asBytes("hello")); + if (out->written) + std::ignore = co_await tls->shutdownWrite(); + else + tls->close(); + }; + auto const remote = + [](StrictTlsPeer* peer, ISocket* wire, VerifiedExchange* out) -> core::async::Task { + if (auto const handshaken = co_await peer->handshake(wire); !handshaken) + co_return; + out->end = co_await peer->readToEnd(wire, &out->received); + }; + auto const hold = [](core::net::EventLoop* loop, + ManualExecutor* executor, + VerifiedExchange* out) -> core::async::Task { + out->verifierHeld = + co_await core::net::testing::waitUntil(loop, [executor] { return executor->pending() == 1; }); + out->receivedWhileHeld = out->received.size(); + executor->drain(); + }; + outcome.finished = core::net::testing::blockOnWithin( + loopback.loop, + core::net::testing::allOf(local(&socket, &outcome), + remote(loopback.peer.get(), loopback.wire.get(), &outcome), + hold(&loopback.loop, &blocking, &outcome)), + core::net::testing::TlsExchangeBound); + return outcome; +} + +} // namespace + +TEST_CASE("a file trust store reads the first bundle the table names, off the loop", "[net][tls][truststore]") +{ + auto const files = InMemoryFileSystem { { "/etc/pki/tls/certs/ca-bundle.crt", pem(0) + pem(1) } }; + auto const outcome = loadFileStore(files, FakeEnvironment {}); + CHECK(outcome.offloaded); + REQUIRE(outcome.anchors.has_value()); + CHECK(outcome.anchors->certificates.size() == 2); + CHECK(outcome.anchors->certificates.front() == derOf(pem(0))); +} + +TEST_CASE("the first existing table row wins, and a later one is never read", "[net][tls][truststore]") +{ + // Debian's bundle comes before Fedora's in the table, so the one certificate is what is read. + auto const files = InMemoryFileSystem { { "/etc/ssl/certs/ca-certificates.crt", pem(0) }, + { "/etc/pki/tls/certs/ca-bundle.crt", pem(0) + pem(1) } }; + CHECK(anchorCount(loadFileStore(files, FakeEnvironment {})) == 1); + + // The first EXISTING row: a malformed one is not skipped for the next. + auto const broken = InMemoryFileSystem { { "/etc/ssl/certs/ca-certificates.crt", "not a bundle" }, + { "/etc/pki/tls/certs/ca-bundle.crt", pem(0) } }; + CHECK(anchorCount(loadFileStore(broken, FakeEnvironment {})) == -1); +} + +TEST_CASE("SSL_CERT_FILE names the bundle, and a named but missing one is an error", "[net][tls][truststore]") +{ + auto const files = InMemoryFileSystem { { "/etc/pki/tls/certs/ca-bundle.crt", pem(0) + pem(1) }, + { "/present.pem", pem(2) } }; + + SECTION("a missing file is an error, not a fallback to the table") + { + auto const outcome = loadFileStore(files, FakeEnvironment { { { "SSL_CERT_FILE", "/custom.pem" } } }); + REQUIRE_FALSE(outcome.anchors.has_value()); + CHECK(outcome.anchors.error().contains("SSL_CERT_FILE")); + CHECK(outcome.anchors.error().contains("/custom.pem")); + } + + SECTION("a present file is what is read") + { + auto const outcome = + loadFileStore(files, FakeEnvironment { { { "SSL_CERT_FILE", "/present.pem" } } }); + REQUIRE(outcome.anchors.has_value()); + REQUIRE(outcome.anchors->certificates.size() == 1); + CHECK(outcome.anchors->certificates.front() == derOf(pem(2))); + } + + SECTION("it wins over SSL_CERT_DIR") + { + auto const environment = + FakeEnvironment { { { "SSL_CERT_FILE", "/present.pem" }, { "SSL_CERT_DIR", "/nowhere" } } }; + CHECK(anchorCount(loadFileStore(files, environment)) == 1); + } + + SECTION("a directory is not a bundle") + { + auto const withDirectory = InMemoryFileSystem { { .path = "/certs", .isDirectory = true } }; + CHECK(anchorCount(loadFileStore(withDirectory, FakeEnvironment { { { "SSL_CERT_FILE", "/certs" } } })) + == -1); + } + + SECTION("an empty value is unset") + { + CHECK(anchorCount(loadFileStore(files, FakeEnvironment { { { "SSL_CERT_FILE", "" } } })) == 2); + } +} + +TEST_CASE("SSL_CERT_DIR loads every hashed file, and only those", "[net][tls][truststore]") +{ + // OpenSSL looks a hashed directory up by `.`, the hash in lower case; a CRL is + // `.r`, and anything else -- the PEM files the links point at, a README, a directory + // that happens to be named like a certificate -- is not what it reads. + auto const files = InMemoryFileSystem { { "/certs/0123abcd.0", pem(0) }, + { "/certs/89abcdef.1", pem(1) }, + { "/certs/0123abcd.r0", "a CRL, not a certificate" }, + { "/certs/README", "not a certificate" }, + { "/certs/ca.pem", pem(2) }, + { "/certs/0123ABCD.0", pem(2) }, + { "/certs/0123abcd.0x", pem(2) }, + { .path = "/certs/abcdef01.0", .isDirectory = true } }; + + SECTION("both hashed files are read") + { + auto const outcome = loadFileStore(files, FakeEnvironment { { { "SSL_CERT_DIR", "/certs" } } }); + CHECK(outcome.offloaded); + REQUIRE(outcome.anchors.has_value()); + REQUIRE(outcome.anchors->certificates.size() == 2); + // Counted, not compared as a std::set: GCC 14 at -O3 reads the set's ordering of byte + // vectors as a memcmp beyond any object. + auto const& loaded = outcome.anchors->certificates; + CHECK(std::ranges::count(loaded, derOf(pem(0))) == 1); + CHECK(std::ranges::count(loaded, derOf(pem(1))) == 1); + } + + SECTION("a missing directory is an error") + { + CHECK(anchorCount(loadFileStore(files, FakeEnvironment { { { "SSL_CERT_DIR", "/elsewhere" } } })) + == -1); + } + + SECTION("a directory with no hashed file is an empty store, and refused") + { + auto const unhashed = InMemoryFileSystem { { "/certs/ca.pem", pem(0) } }; + CHECK(anchorCount(loadFileStore(unhashed, FakeEnvironment { { { "SSL_CERT_DIR", "/certs" } } })) + == -1); + } + + SECTION("one hashed file that does not parse refuses the whole directory") + { + auto const broken = + InMemoryFileSystem { { "/certs/0123abcd.0", pem(0) }, { "/certs/89abcdef.0", "garbage" } }; + CHECK(anchorCount(loadFileStore(broken, FakeEnvironment { { { "SSL_CERT_DIR", "/certs" } } })) == -1); + } +} + +TEST_CASE("a named file that is not a regular file is refused without being read", "[net][tls][truststore]") +{ + // A device has no end: reading /dev/zero as a bundle would never return. Through the native + // file system, because the in-memory one models no device. + auto const files = core::platform::NativeFileSystem {}; + if (!files.exists("/dev/zero")) + SKIP("this system has no /dev/zero"); + auto const outcome = loadFileStore(files, FakeEnvironment { { { "SSL_CERT_FILE", "/dev/zero" } } }); + REQUIRE_FALSE(outcome.anchors.has_value()); + CHECK(outcome.anchors.error().contains("not a readable regular file")); +} + +TEST_CASE("a bundle or a directory larger than a trust store reads is refused", "[net][tls][truststore]") +{ + // Padding after the certificate is text PEM skips, so the size is all that differs. + auto const padded = [](std::string body, std::uintmax_t size) { + body.resize(static_cast(size), '\n'); + return body; + }; + constexpr auto Limit = core::net::MaxTrustBundleBytes; + + SECTION("a bundle of exactly the limit is read, one byte more is not") + { + auto const atLimit = + InMemoryFileSystem { { "/etc/pki/tls/certs/ca-bundle.crt", padded(pem(0), Limit) } }; + CHECK(anchorCount(loadFileStore(atLimit, FakeEnvironment {})) == 1); + auto const over = + InMemoryFileSystem { { "/etc/pki/tls/certs/ca-bundle.crt", padded(pem(0), Limit + 1) } }; + auto const outcome = loadFileStore(over, FakeEnvironment {}); + REQUIRE_FALSE(outcome.anchors.has_value()); + CHECK(outcome.anchors.error().contains("more than")); + } + + SECTION("a directory's files are bounded together") + { + constexpr auto Half = core::net::MaxTrustDirectoryBytes / 2; + auto const atLimit = InMemoryFileSystem { { "/certs/0123abcd.0", padded(pem(0), Half) }, + { "/certs/89abcdef.0", padded(pem(1), Half) } }; + CHECK(anchorCount(loadFileStore(atLimit, FakeEnvironment { { { "SSL_CERT_DIR", "/certs" } } })) == 2); + auto const over = InMemoryFileSystem { { "/certs/0123abcd.0", padded(pem(0), Half) }, + { "/certs/89abcdef.0", padded(pem(1), Half + 1) } }; + auto const outcome = loadFileStore(over, FakeEnvironment { { { "SSL_CERT_DIR", "/certs" } } }); + REQUIRE_FALSE(outcome.anchors.has_value()); + CHECK(outcome.anchors.error().contains("more than")); + } +} + +TEST_CASE("an empty store, an unreadable file or a malformed bundle is a refusal", "[net][tls][truststore]") +{ + SECTION("nothing configured and no table row present") + { + auto const outcome = loadFileStore(InMemoryFileSystem {}, FakeEnvironment {}); + REQUIRE_FALSE(outcome.anchors.has_value()); + CHECK(outcome.anchors.error().contains("SSL_CERT_FILE")); + } + + SECTION("an empty bundle") + { + auto const files = InMemoryFileSystem { { "/etc/pki/tls/certs/ca-bundle.crt", "" } }; + CHECK(anchorCount(loadFileStore(files, FakeEnvironment {})) == -1); + } + + SECTION("a bundle that cannot be read") + { + auto files = InMemoryFileSystem { { "/etc/pki/tls/certs/ca-bundle.crt", pem(0) } }; + files.denyAccess("/etc/pki/tls/certs/ca-bundle.crt"); + CHECK(anchorCount(loadFileStore(files, FakeEnvironment {})) == -1); + } + + SECTION("a hashed file that cannot be read") + { + auto files = InMemoryFileSystem { { "/certs/0123abcd.0", pem(0) }, { "/certs/89abcdef.0", pem(1) } }; + files.denyAccess("/certs/89abcdef.0"); + CHECK(anchorCount(loadFileStore(files, FakeEnvironment { { { "SSL_CERT_DIR", "/certs" } } })) == -1); + } +} + +TEST_CASE("the trust-source table names each location once, every bundle before any directory", + "[net][tls][truststore]") +{ + auto const rows = core::net::trustBundleLocations(); + auto paths = std::set {}; + for (auto const& row: rows) + { + CHECK(paths.insert(row.path).second); + CHECK_FALSE(row.distribution.empty()); + } + for (auto const required: { "/etc/ssl/certs/ca-certificates.crt", + "/etc/pki/tls/certs/ca-bundle.crt", + "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", + "/etc/ssl/ca-bundle.pem", + "/etc/ssl/cert.pem", + "/usr/local/share/certs/ca-root-nss.crt", + "/etc/ssl/certs" }) + CHECK(paths.contains(required)); + + // A hashed directory is the fallback, never ahead of a bundle: on Debian `/etc/ssl/certs` exists + // beside the bundle in it, and reading its links instead would read the same anchors slower. + auto const firstDirectory = + std::ranges::find(rows, TrustBundleKind::HashedDirectory, &core::net::TrustBundleLocation::kind); + CHECK(std::ranges::none_of(std::ranges::subrange { firstDirectory, rows.end() }, + [](auto const& row) { return row.kind == TrustBundleKind::Bundle; })); +} + +TEST_CASE("every table row, alone on a machine, is what the store reads", "[net][tls][truststore]") +{ + for (auto const& row: core::net::trustBundleLocations()) + { + DYNAMIC_SECTION(row.path << " (" << row.distribution << ")") + { + auto const path = std::string { row.path }; + // Filled by calls rather than chosen between two initializer lists: GCC 14 reads the + // lists' backing arrays as dangling across the conditional (-Wdangling-pointer). + auto files = InMemoryFileSystem {}; + if (row.kind == TrustBundleKind::Bundle) + files.addFile(path, pem(0) + pem(1)); + else + { + files.addFile(path + "/0123abcd.0", pem(0)); + files.addFile(path + "/89abcdef.0", pem(1)); + } + CHECK(anchorCount(loadFileStore(files, FakeEnvironment {})) == 2); + } + } +} + +TEST_CASE("a PEM trust store answers the anchors of its bundle", "[net][tls][truststore]") +{ + auto const two = core::async::syncRun(core::net::makePemTrustStore(pem(0) + pem(1))->load()); + REQUIRE(two.has_value()); + CHECK(two->certificates.size() == 2); + + CHECK_FALSE(core::async::syncRun(core::net::makePemTrustStore("")->load()).has_value()); + CHECK_FALSE(core::async::syncRun(core::net::makePemTrustStore("garbage")->load()).has_value()); +} + +TEST_CASE("a client context over a trust store's anchors verifies through TrustSource", + "[net][tls][truststore]") +{ + auto anchors = core::async::syncRun(core::net::makePemTrustStore(pem(0))->load()); + REQUIRE(anchors.has_value()); + auto loopback = makeTlsLoopback(StrictTlsPeer::server(material(0), { .alpn = { "http/1.1" } })); + auto const context = core::net::makeTlsClientContext(std::move(*anchors), { .alpn = { "http/1.1" } }); + REQUIRE(context.has_value()); + auto socket = + (*context)->wrapClient(std::move(loopback->transport), loopback->loop, { .serverName = "localhost" }); + REQUIRE(socket.has_value()); + + auto const outcome = core::net::testing::handshakeBoth(*loopback, **socket); + REQUIRE(outcome.finished); + REQUIRE(outcome.local.has_value()); + auto const* const session = (*socket)->tlsSession(); + REQUIRE(session != nullptr); + // Guarded again: GCC 14 cannot see that REQUIRE leaves no null pointer behind it. + CHECK((session != nullptr && session->negotiatedProtocol() == "http/1.1")); +} + +TEST_CASE("a verifier-checked client moves no application byte until the verifier accepts", + "[net][tls][truststore][verifier]") +{ + auto loopback = makeTlsLoopback(StrictTlsPeer::server(material(0), { .alpn = { "http/1.1" } })); + auto blocking = ManualExecutor {}; + auto const verifier = std::make_shared(ChainVerdict::Accept, blocking); + auto const context = clientOver(verifier, { .alpn = { "http/1.1" } }); + auto socket = + context->wrapClient(std::move(loopback->transport), loopback->loop, { .serverName = "localhost" }); + REQUIRE(socket.has_value()); + + auto const outcome = exchangeThroughVerifier(*loopback, **socket, blocking); + REQUIRE(outcome.finished); + CHECK(outcome.verifierHeld); + CHECK(outcome.receivedWhileHeld == 0); + REQUIRE(outcome.written.has_value()); + CHECK(*outcome.written == 5); + CHECK(outcome.received == "hello"); + CHECK(outcome.end == StreamEnd::CloseNotify); + + // It was asked once, about the chain the server presented, for the name the connection was for. + REQUIRE(verifier->chains.size() == 1); + REQUIRE_FALSE(verifier->chains.front().empty()); + CHECK(verifier->chains.front().front() == derOf(pem(0))); + CHECK(verifier->serverNames == std::vector { "localhost" }); + CHECK(loopback->peer->receivedServerName() == "localhost"); + + auto const* const session = (*socket)->tlsSession(); + REQUIRE(session != nullptr); + CHECK_FALSE(session->failure().has_value()); + CHECK(session->negotiatedProtocol() == "http/1.1"); + CHECK(session->negotiatedVersion() == core::net::TlsVersion::Tls13); + CHECK(session->channelBinding().has_value()); + CHECK(session->peerCertificateDigest().has_value()); +} + +TEST_CASE("an operation that arrives while the chain is being verified waits for the verdict", + "[net][tls][truststore][verifier]") +{ + auto loopback = makeTlsLoopback(StrictTlsPeer::server(material(0))); + auto blocking = ManualExecutor {}; + auto const verifier = std::make_shared(ChainVerdict::Accept, blocking); + auto socket = clientOver(verifier)->wrapClient( + std::move(loopback->transport), loopback->loop, { .serverName = "localhost" }); + REQUIRE(socket.has_value()); + + struct Seen + { + bool held = false; + bool writeDoneWhileHeld = true; + std::size_t receivedWhileHeld = 1; + std::expected written = + std::unexpected(core::net::makeNetError(NetErrorCode::Timeout)); + std::string received; + StreamEnd end = StreamEnd::Failed; + }; + auto seen = Seen {}; + auto writeDone = false; + // The handshake is driven by one flow; the write arrives from another once the verifier holds. + auto const driver = [](ISocket* tls) -> core::async::Task { + std::ignore = co_await tls->handshakeIfNeeded(); + }; + auto const writer = [](core::net::EventLoop* loop, + ManualExecutor* executor, + ISocket* tls, + Seen* out, + bool* done) -> core::async::Task { + if (!co_await core::net::testing::waitUntil(loop, [executor] { return executor->pending() == 1; })) + co_return; + out->written = co_await tls->write(asBytes("early")); + *done = true; + if (out->written) + std::ignore = co_await tls->shutdownWrite(); + }; + auto const remote = [](StrictTlsPeer* peer, ISocket* wire, Seen* out) -> core::async::Task { + if (auto const handshaken = co_await peer->handshake(wire); !handshaken) + co_return; + out->end = co_await peer->readToEnd(wire, &out->received); + }; + auto const hold = [](core::net::EventLoop* loop, + ManualExecutor* executor, + Seen* out, + bool const* done) -> core::async::Task { + out->held = + co_await core::net::testing::waitUntil(loop, [executor] { return executor->pending() == 1; }); + // Time for the write to reach the wire, were it let through. + co_await loop->delay(std::chrono::milliseconds { 50 }); + out->writeDoneWhileHeld = *done; + out->receivedWhileHeld = out->received.size(); + executor->drain(); + }; + auto* const tls = socket->get(); + REQUIRE(core::net::testing::blockOnWithin( + loopback->loop, + core::net::testing::allOf(driver(tls), + writer(&loopback->loop, &blocking, tls, &seen, &writeDone), + remote(loopback->peer.get(), loopback->wire.get(), &seen), + hold(&loopback->loop, &blocking, &seen, &writeDone)), + core::net::testing::TlsExchangeBound)); + CHECK(seen.held); + CHECK_FALSE(seen.writeDoneWhileHeld); + CHECK(seen.receivedWhileHeld == 0); + REQUIRE(seen.written.has_value()); + CHECK(seen.received == "early"); + CHECK(verifier->chains.size() == 1); +} + +TEST_CASE("a refusing verifier fails the connection closed", "[net][tls][truststore][verifier]") +{ + // A refusal is a certificate failure whatever the verifier called it. + auto const verdict = GENERATE(ChainVerdict::Refuse, ChainVerdict::RefuseAsProtocol); + auto loopback = makeTlsLoopback(StrictTlsPeer::server(material(0), { .alpn = { "http/1.1" } })); + auto blocking = ManualExecutor {}; + auto const verifier = std::make_shared(verdict, blocking); + auto const context = clientOver(verifier, { .alpn = { "http/1.1" } }); + auto socket = + context->wrapClient(std::move(loopback->transport), loopback->loop, { .serverName = "localhost" }); + REQUIRE(socket.has_value()); + + auto const outcome = exchangeThroughVerifier(*loopback, **socket, blocking); + REQUIRE(outcome.finished); + CHECK(outcome.verifierHeld); + REQUIRE_FALSE(outcome.written.has_value()); + CHECK(outcome.received.empty()); + CHECK(verifier->chains.size() == 1); + + auto const* const session = (*socket)->tlsSession(); + REQUIRE(session != nullptr); + auto const failure = session->failure(); + REQUIRE(failure.has_value()); + CHECK(failure->kind == TlsFailureKind::Certificate); + CHECK(failure->message == ScriptedChainVerifier::RefusalMessage); + + // A refused peer's session answers as one that never finished: no identity, no channel to + // bind to, nothing negotiated -- though OpenSSL's handshake did finish under it. + CHECK_FALSE(session->channelBinding().has_value()); + CHECK_FALSE(session->peerCertificateDigest().has_value()); + CHECK_FALSE(session->negotiatedVersion().has_value()); + CHECK(session->negotiatedProtocol().empty()); + + // Sticky: the next operation answers the refusal again, and asks the verifier nothing more. + auto const again = core::net::testing::blockOnWithin( + loopback->loop, + core::net::testing::allOf( + [](ISocket* tls) -> core::async::Task { + auto const handshaken = co_await tls->handshakeIfNeeded(); + CHECK_FALSE(handshaken.has_value()); + }(socket->get()), + // Answers a second verification, should one be asked: a regression then fails the count + // below rather than parking the handshake on an executor nobody drains. + [](core::net::EventLoop* loop, ManualExecutor* executor) -> core::async::Task { + std::ignore = co_await core::net::testing::waitUntil( + loop, [executor] { return executor->pending() == 1; }, 50); + executor->drain(); + }(&loopback->loop, &blocking)), + core::net::testing::TlsExchangeBound); + CHECK(again); + CHECK(verifier->chains.size() == 1); +} + +TEST_CASE("a verifier is asked for the name as the certificate check reads it", + "[net][tls][truststore][verifier]") +{ + struct Row + { + std::string_view given; ///< `TlsPeer::serverName`. + std::string_view checked; ///< What the verifier is asked about. + std::string_view sni; ///< What the server received as SNI. + }; + auto const rows = std::vector { + { .given = "localhost", .checked = "localhost", .sni = "localhost" }, + { .given = "127.0.0.1", .checked = "127.0.0.1", .sni = "" }, + { .given = "[::1]", .checked = "::1", .sni = "" }, + { .given = "fe80::1%eth0", .checked = "fe80::1", .sni = "" }, + }; + for (auto const& row: rows) + { + DYNAMIC_SECTION("'" << row.given << "'") + { + auto loopback = makeTlsLoopback(StrictTlsPeer::server(everyNameMaterial())); + auto blocking = ManualExecutor {}; + auto const verifier = std::make_shared(ChainVerdict::Accept, blocking); + auto socket = clientOver(verifier)->wrapClient( + std::move(loopback->transport), loopback->loop, { .serverName = std::string { row.given } }); + REQUIRE(socket.has_value()); + auto const outcome = exchangeThroughVerifier(*loopback, **socket, blocking); + REQUIRE(outcome.finished); + CHECK(outcome.received == "hello"); + CHECK(verifier->serverNames == std::vector { std::string { row.checked } }); + CHECK(loopback->peer->receivedServerName() == row.sni); + } + } +} + +TEST_CASE("a verifier context checks the leaf's name itself, before any verifier is asked", + "[net][tls][truststore][verifier]") +{ + // The same rules on every platform -- whole-label wildcards, subjectAltNames only -- whatever + // the platform verifier would have said: none of these chains reaches it. + struct Row + { + std::string_view what; + CertKeyPem const* material; + std::string_view name; + }; + auto const rows = std::vector { + { .what = "another DNS name", .material = &everyNameMaterial(), .name = "other.test" }, + { .what = "another address", .material = &everyNameMaterial(), .name = "127.0.0.2" }, + { .what = "another IPv6 address", .material = &everyNameMaterial(), .name = "[::2]" }, + { .what = "a name only the common name carries", + .material = &commonNameOnlyMaterial(), + .name = "localhost" }, + }; + for (auto const& row: rows) + { + DYNAMIC_SECTION(row.what) + { + auto loopback = makeTlsLoopback(StrictTlsPeer::server(*row.material)); + auto blocking = ManualExecutor {}; + auto const verifier = std::make_shared(ChainVerdict::Accept, blocking); + auto socket = clientOver(verifier)->wrapClient( + std::move(loopback->transport), loopback->loop, { .serverName = std::string { row.name } }); + REQUIRE(socket.has_value()); + auto const outcome = exchangeThroughVerifier(*loopback, **socket, blocking); + REQUIRE(outcome.finished); + CHECK_FALSE(outcome.verifierHeld); + CHECK_FALSE(outcome.written.has_value()); + CHECK(outcome.received.empty()); + CHECK(verifier->chains.empty()); + auto const* const session = (*socket)->tlsSession(); + REQUIRE(session != nullptr); + auto const failure = session->failure(); + REQUIRE(failure.has_value()); + CHECK(failure->kind == TlsFailureKind::Certificate); + } + } +} + +TEST_CASE("a verifier context refuses a name it could not check, and wrap verifies the chain alone", + "[net][tls][truststore][verifier]") +{ + auto loopback = makeTlsLoopback(StrictTlsPeer::server(material(0))); + auto blocking = ManualExecutor {}; + auto const verifier = std::make_shared(ChainVerdict::Accept, blocking); + auto const context = clientOver(verifier); + + SECTION("a bracketed name that is no IPv6 literal") + { + auto refused = context->wrapClient( + std::move(loopback->transport), loopback->loop, { .serverName = "[localhost]" }); + REQUIRE_FALSE(refused.has_value()); + CHECK(refused.error().code == NetErrorCode::AddressError); + CHECK(verifier->chains.empty()); + } + + SECTION("an empty name, which would check the chain alone") + { + auto refused = context->wrapClient(std::move(loopback->transport), loopback->loop, {}); + REQUIRE_FALSE(refused.has_value()); + CHECK(refused.error().code == NetErrorCode::AddressError); + CHECK(verifier->chains.empty()); + } + + SECTION("wrap asks the verifier too, with no name") + { + auto socket = context->wrap(std::move(loopback->transport), loopback->loop); + REQUIRE(socket != nullptr); + auto const outcome = exchangeThroughVerifier(*loopback, *socket, blocking); + REQUIRE(outcome.finished); + CHECK(outcome.verifierHeld); + CHECK(outcome.received == "hello"); + CHECK(verifier->serverNames == std::vector { "" }); + } +} + +TEST_CASE("a client context needs a verifier to be one", "[net][tls][truststore][verifier]") +{ + CHECK_FALSE(core::net::makeTlsClientContext(std::shared_ptr {}).has_value()); + auto blocking = ManualExecutor {}; + auto const verifier = std::make_shared(ChainVerdict::Accept, blocking); + CHECK_FALSE(core::net::makeTlsClientContext(verifier, { .alpn = { "" } }).has_value()); +} + +TEST_CASE("a socket destroyed while its chain is being verified unwinds the handshake", + "[net][tls][truststore][verifier]") +{ + auto loopback = makeTlsLoopback(StrictTlsPeer::server(material(0))); + auto blocking = ManualExecutor {}; + auto const verifier = std::make_shared(ChainVerdict::Accept, blocking); + auto socket = clientOver(verifier)->wrapClient( + std::move(loopback->transport), loopback->loop, { .serverName = "localhost" }); + REQUIRE(socket.has_value()); + + auto unwound = false; + auto const local = [](ISocket* tls, bool* out) -> core::async::Task { + try + { + std::ignore = co_await tls->handshakeIfNeeded(); + } + catch (core::async::OperationCancelled const&) + { + *out = true; + } + }; + auto const remote = [](StrictTlsPeer* peer, ISocket* wire) -> core::async::Task { + std::ignore = co_await peer->handshake(wire); + }; + auto held = false; + auto const destroy = [](core::net::EventLoop* loop, + ManualExecutor* executor, + std::unique_ptr* tls, + bool* out) -> core::async::Task { + *out = co_await core::net::testing::waitUntil(loop, [executor] { return executor->pending() == 1; }); + tls->reset(); + executor->drain(); + }; + auto* const raw = socket->get(); + CHECK(core::net::testing::blockOnWithin( + loopback->loop, + core::net::testing::allOf(local(raw, &unwound), + remote(loopback->peer.get(), loopback->wire.get()), + destroy(&loopback->loop, &blocking, &*socket, &held)), + core::net::testing::TlsExchangeBound)); + CHECK(held); + CHECK(unwound); +} + +namespace +{ + +/// Drives @p tls's handshake, bounded by @p limit on @p loop's clock. +/// @param out Set to whether the bound ran out first; otherwise to false, with @p result set. +core::async::Task handshakeWithin(core::net::EventLoop* loop, + ISocket* tls, + std::chrono::milliseconds limit, + std::optional* timedOut, + std::optional>* result) +{ + auto const drive = [](ISocket* socket) -> core::async::Task> { + co_return co_await socket->handshakeIfNeeded(); + }; + auto answer = co_await core::net::withTimeout(loop, drive(tls), limit); + *timedOut = !answer.has_value(); + if (answer.has_value()) + *result = std::move(*answer); +} + +/// The server's half of a handshake, its outcome ignored. +core::async::Task serverHandshake(StrictTlsPeer* peer, ISocket* wire) +{ + std::ignore = co_await peer->handshake(wire); +} + +} // namespace + +TEST_CASE("a stop ends the wait for a verifier that has not answered, and a retry joins it", + "[net][tls][truststore][verifier]") +{ + // The verification runs on a blocking executor nobody drains, so only the bound can end the + // handshake: the stop must reach the wait, not the evaluation, which is left to finish alone. + auto loopback = makeTlsLoopback(StrictTlsPeer::server(material(0))); + auto blocking = ManualExecutor {}; + auto const verifier = std::make_shared(ChainVerdict::Accept, blocking); + auto socket = clientOver(verifier)->wrapClient( + std::move(loopback->transport), loopback->loop, { .serverName = "localhost" }); + REQUIRE(socket.has_value()); + + auto timedOut = std::optional {}; + auto result = std::optional> {}; + REQUIRE(core::net::testing::blockOnWithin( + loopback->loop, + core::net::testing::allOf( + handshakeWithin( + &loopback->loop, socket->get(), std::chrono::milliseconds { 50 }, &timedOut, &result), + serverHandshake(loopback->peer.get(), loopback->wire.get())), + core::net::testing::TlsExchangeBound)); + CHECK(timedOut == true); + CHECK(blocking.pending() == 1); + + // The evaluation answers while nobody waits; the retry is handed that answer rather than asking + // the verifier a second time. + blocking.drain(); + REQUIRE(core::net::testing::blockOnWithin( + loopback->loop, + handshakeWithin( + &loopback->loop, socket->get(), core::net::testing::TlsExchangeBound, &timedOut, &result), + core::net::testing::TlsExchangeBound)); + CHECK(timedOut == false); + REQUIRE(result.has_value()); + CHECK(result->has_value()); + CHECK(verifier->chains.size() == 1); +} + +TEST_CASE("a verification outlives the socket and the loop a stop left it running for", + "[net][tls][truststore][verifier]") +{ + // The evaluation finishes on the blocking executor and only settles the call: nothing of it + // resumes on the socket's loop, which is gone by the time the platform answers. + auto loopback = makeTlsLoopback(StrictTlsPeer::server(material(0))); + auto blocking = ManualExecutor {}; + auto const verifier = std::make_shared(ChainVerdict::Accept, blocking); + auto const context = clientOver(verifier); + auto socket = + context->wrapClient(std::move(loopback->transport), loopback->loop, { .serverName = "localhost" }); + REQUIRE(socket.has_value()); + + auto timedOut = std::optional {}; + auto result = std::optional> {}; + REQUIRE(core::net::testing::blockOnWithin( + loopback->loop, + core::net::testing::allOf( + handshakeWithin( + &loopback->loop, socket->get(), std::chrono::milliseconds { 50 }, &timedOut, &result), + serverHandshake(loopback->peer.get(), loopback->wire.get())), + core::net::testing::TlsExchangeBound)); + REQUIRE(timedOut == true); + REQUIRE(blocking.pending() == 1); + + socket->reset(); + loopback.reset(); + blocking.drain(); + CHECK(blocking.pending() == 0); + CHECK(verifier->chains.size() == 1); +} + +TEST_CASE("verifications a stop left running count against the context's cap", + "[net][tls][truststore][verifier]") +{ + auto first = makeTlsLoopback(StrictTlsPeer::server(material(0))); + auto second = makeTlsLoopback(StrictTlsPeer::server(material(0))); + auto blocking = ManualExecutor {}; + auto const verifier = std::make_shared(ChainVerdict::Accept, blocking); + auto const context = clientOver(verifier, { .maxVerificationsInFlight = 1 }); + + auto held = context->wrapClient(std::move(first->transport), first->loop, { .serverName = "localhost" }); + REQUIRE(held.has_value()); + auto timedOut = std::optional {}; + auto result = std::optional> {}; + REQUIRE(core::net::testing::blockOnWithin( + first->loop, + core::net::testing::allOf( + handshakeWithin(&first->loop, held->get(), std::chrono::milliseconds { 50 }, &timedOut, &result), + serverHandshake(first->peer.get(), first->wire.get())), + core::net::testing::TlsExchangeBound)); + REQUIRE(timedOut == true); + REQUIRE(blocking.pending() == 1); + + // The first evaluation still holds the only slot, though nobody waits for it any more. + auto refused = + context->wrapClient(std::move(second->transport), second->loop, { .serverName = "localhost" }); + REQUIRE(refused.has_value()); + REQUIRE(core::net::testing::blockOnWithin( + second->loop, + core::net::testing::allOf( + handshakeWithin( + &second->loop, refused->get(), core::net::testing::TlsExchangeBound, &timedOut, &result), + serverHandshake(second->peer.get(), second->wire.get())), + core::net::testing::TlsExchangeBound)); + CHECK(timedOut == false); + REQUIRE(result.has_value()); + REQUIRE_FALSE(result->has_value()); + CHECK(result->error().code == NetErrorCode::ResourceExhausted); + CHECK_FALSE(core::net::isDeadlineExpiry(result->error().code)); + CHECK(verifier->chains.empty()); // the held evaluation has not run; the refused one never started + + // The refusal is not sticky: once the slot is given back, the same socket verifies. + blocking.drain(); + CHECK(verifier->chains.size() == 1); + auto const drain = [](core::net::EventLoop* loop, ManualExecutor* executor) -> core::async::Task { + if (co_await core::net::testing::waitUntil(loop, [executor] { return executor->pending() == 1; })) + executor->drain(); + }; + REQUIRE(core::net::testing::blockOnWithin( + second->loop, + core::net::testing::allOf( + handshakeWithin( + &second->loop, refused->get(), core::net::testing::TlsExchangeBound, &timedOut, &result), + drain(&second->loop, &blocking)), + core::net::testing::TlsExchangeBound)); + CHECK(timedOut == false); + REQUIRE(result.has_value()); + CHECK(result->has_value()); + CHECK(verifier->chains.size() == 2); +} + +TEST_CASE("one verifier answers each socket on the loop that socket runs on", + "[net][tls][truststore][verifier]") +{ + // Two loops, one context: each handshake is driven by its own loop alone, so a verdict delivered + // to any other executor would never arrive. + auto first = makeTlsLoopback(StrictTlsPeer::server(material(0))); + auto second = makeTlsLoopback(StrictTlsPeer::server(material(0))); + auto blocking = ManualExecutor {}; + auto const verifier = std::make_shared(ChainVerdict::Accept, blocking); + auto const context = clientOver(verifier); + auto const drain = [](core::net::EventLoop* loop, ManualExecutor* executor) -> core::async::Task { + if (co_await core::net::testing::waitUntil(loop, [executor] { return executor->pending() == 1; })) + executor->drain(); + }; + for (auto* const loopback: { first.get(), second.get() }) + { + auto socket = context->wrapClient( + std::move(loopback->transport), loopback->loop, { .serverName = "localhost" }); + REQUIRE(socket.has_value()); + auto timedOut = std::optional {}; + auto result = std::optional> {}; + REQUIRE(core::net::testing::blockOnWithin( + loopback->loop, + core::net::testing::allOf( + handshakeWithin( + &loopback->loop, socket->get(), core::net::testing::TlsExchangeBound, &timedOut, &result), + serverHandshake(loopback->peer.get(), loopback->wire.get()), + drain(&loopback->loop, &blocking)), + core::net::testing::TlsExchangeBound)); + REQUIRE(result.has_value()); + CHECK(result->has_value()); + } + CHECK(verifier->chains.size() == 2); +} + +TEST_CASE("the system context verifies a public name", "[net][tls][truststore]") +{ + // Construction only, and no network: a context comes back that binds each connection to its + // name. Where the machine has no trust configuration at all, there is nothing to build it from. + auto const files = core::platform::NativeFileSystem {}; + auto const environment = core::LiveEnvironment {}; + auto home = ManualExecutor {}; + auto blocking = ManualExecutor {}; + auto task = core::net::makeSystemTlsClientContext(&files, &environment, &home, &blocking, {}); + task.handle().resume(); + blocking.drain(); + home.drain(); + REQUIRE(task.done()); + auto context = task.result(); + if (!context) + { + // As the store reads them: a variable set to the empty string is unset. + auto const isSet = [&environment](std::string_view name) { + auto const value = environment.get(name); + return value && !value->empty(); + }; + auto const configured = + isSet("SSL_CERT_FILE") || isSet("SSL_CERT_DIR") + || std::ranges::any_of(core::net::trustBundleLocations(), [&files](auto const& row) { + return files.exists(std::string { row.path }); + }); + if (!configured) + SKIP("this machine has no trust configuration: " << context.error()); + } + REQUIRE(context.has_value()); + REQUIRE(*context != nullptr); + + auto loopback = makeTlsLoopback(StrictTlsPeer::server(material(0))); + auto const socket = (*context)->wrapClient( + std::move(loopback->transport), loopback->loop, { .serverName = "example.com" }); + CHECK(socket.has_value()); +} diff --git a/src/core/net/darwin/DarwinChainVerifier.cpp b/src/core/net/darwin/DarwinChainVerifier.cpp new file mode 100644 index 00000000..9b10e4ba --- /dev/null +++ b/src/core/net/darwin/DarwinChainVerifier.cpp @@ -0,0 +1,182 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The macOS chain verifier. Every certificate the server presented goes into one SecTrust with the +// SSL server policy for the name, and `SecTrustEvaluateWithError` decides -- the keychains' trust +// settings, a root Apple distrusts -- on the blocking executor, because it may block. +// +// It never fetches what the server names: `SecTrustSetNetworkFetchAllowed(false)` keeps the +// evaluation from following a certificate's Authority Information Access URL to an intermediate, a +// request to a host of the server's choosing that no policy of the caller's saw. A server that sends +// an incomplete chain is refused here, as OpenSSL refuses it on every other system. +#include "DarwinChainVerifier.hpp" + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace core::net::detail +{ + +namespace +{ + /// Releases a Core Foundation reference; tolerates null. + struct CfRelease + { + void operator()(void const* reference) const noexcept + { + if (reference != nullptr) + CFRelease(reference); + } + }; + + /// Owns a Core Foundation reference of type @p Ref (a pointer typedef such as `CFDataRef`). + template + using CfPtr = std::unique_ptr, CfRelease>; + + /// A refusal, for any result type that carries a @c TlsFailure. + [[nodiscard]] std::unexpected refusal(std::string message) + { + return std::unexpected(TlsFailure { + .kind = TlsFailureKind::Certificate, .alert = std::nullopt, .message = std::move(message) }); + } + + /// @p text as UTF-8; empty where it cannot be converted. + [[nodiscard]] std::string utf8Of(CFStringRef text) + { + if (text == nullptr) + return {}; + auto const capacity = + CFStringGetMaximumSizeForEncoding(CFStringGetLength(text), kCFStringEncodingUTF8) + 1; + auto buffer = std::string(static_cast(capacity), '\0'); + if (CFStringGetCString(text, buffer.data(), capacity, kCFStringEncodingUTF8) == 0) + return {}; + buffer.resize(std::strlen(buffer.c_str())); + return buffer; + } + + /// What `SecTrustEvaluateWithError` said was wrong, for the refusal's message. + [[nodiscard]] std::string describe(CFErrorRef error) + { + auto const description = + CfPtr { error != nullptr ? CFErrorCopyDescription(error) : nullptr }; + auto text = utf8Of(description.get()); + return text.empty() ? std::string { "the platform's trust evaluation refused the chain" } : text; + } + + /// Builds the trust object @p chain is evaluated through, for @p serverName with the SSL server + /// policy, network fetching off. + [[nodiscard]] std::expected, TlsFailure> trustFor( + std::vector const& chain, std::string const& serverName) + { + if (chain.empty()) + return refusal("the peer presented no certificate"); + auto const certificates = CfPtr { CFArrayCreateMutable( + kCFAllocatorDefault, static_cast(chain.size()), &kCFTypeArrayCallBacks) }; + if (!certificates) + return refusal("CFArrayCreateMutable failed"); + for (auto const& der: chain) + { + auto const data = CfPtr { CFDataCreate(kCFAllocatorDefault, + reinterpret_cast(der.data()), + static_cast(der.size())) }; + if (!data) + return refusal("CFDataCreate failed"); + auto const certificate = + CfPtr { SecCertificateCreateWithData(kCFAllocatorDefault, data.get()) }; + if (!certificate) + return refusal("a certificate in the presented chain does not parse"); + CFArrayAppendValue(certificates.get(), certificate.get()); + } + + // An empty name checks the chain alone, as SecPolicyCreateSSL documents for a null hostname. + auto const name = CfPtr { + serverName.empty() ? nullptr + : CFStringCreateWithBytes(kCFAllocatorDefault, + reinterpret_cast(serverName.data()), + static_cast(serverName.size()), + kCFStringEncodingUTF8, + static_cast(false)) + }; + if (!serverName.empty() && !name) + return refusal("the server name is not UTF-8"); + auto const policy = + CfPtr { SecPolicyCreateSSL(static_cast(true), name.get()) }; + if (!policy) + return refusal("SecPolicyCreateSSL failed"); + + auto rawTrust = SecTrustRef { nullptr }; + if (auto const status = SecTrustCreateWithCertificates(certificates.get(), policy.get(), &rawTrust); + status != errSecSuccess) + return refusal("SecTrustCreateWithCertificates: OSStatus " + std::to_string(status)); + auto trust = CfPtr { rawTrust }; + if (auto const status = SecTrustSetNetworkFetchAllowed(trust.get(), static_cast(false)); + status != errSecSuccess) + return refusal("SecTrustSetNetworkFetchAllowed: OSStatus " + std::to_string(status)); + return trust; + } + + /// Evaluates @p chain for @p serverName with the SSL server policy. Blocking. + [[nodiscard]] std::expected evaluate(std::vector const& chain, + std::string const& serverName) + { + auto const trust = trustFor(chain, serverName); + if (!trust) + return std::unexpected(trust.error()); + auto rawError = CFErrorRef { nullptr }; + auto const trusted = SecTrustEvaluateWithError(trust->get(), &rawError); + auto const error = CfPtr { rawError }; + if (!trusted) + return refusal(describe(error.get())); + return {}; + } + + class DarwinChainVerifier final: public IChainVerifier + { + public: + explicit DarwinChainVerifier(async::IExecutor& blocking) noexcept: _blocking { &blocking } {} + + [[nodiscard]] async::Task> verify(std::vector chain, + std::string serverName) override + { + co_await async::ResumeOn { *_blocking }; + co_return evaluate(chain, serverName); + } + + private: + async::IExecutor* _blocking; + }; +} // namespace + +std::expected networkFetchAllowed(std::vector const& chain, + std::string const& serverName) +{ + auto const trust = trustFor(chain, serverName); + if (!trust) + return std::unexpected(trust.error().message); + auto allowed = Boolean {}; + if (auto const status = SecTrustGetNetworkFetchAllowed(trust->get(), &allowed); status != errSecSuccess) + return std::unexpected("SecTrustGetNetworkFetchAllowed: OSStatus " + std::to_string(status)); + return allowed != 0; +} + +std::shared_ptr makeDarwinChainVerifier(async::IExecutor& blocking) +{ + return std::make_shared(blocking); +} + +} // namespace core::net::detail diff --git a/src/core/net/darwin/DarwinChainVerifier.hpp b/src/core/net/darwin/DarwinChainVerifier.hpp new file mode 100644 index 00000000..f7018263 --- /dev/null +++ b/src/core/net/darwin/DarwinChainVerifier.hpp @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// The macOS chain verifier: Security.framework's trust evaluation, which honours the keychains' +/// trust settings and never fetches an intermediate a certificate's Authority Information Access +/// names. Private to `core::net_tls`. + +#include +#include + +#include +#include +#include +#include + +namespace core::net::detail +{ + +/// Builds the trust object a verification of @p chain evaluates, and reads back whether it may +/// fetch from the network; for the case that proves it may not. +/// @param chain The presented chain, leaf first. +/// @param serverName The name it is checked for. +/// @return Whether network fetching is allowed, or why the trust object could not be built. +[[nodiscard]] std::expected networkFetchAllowed(std::vector const& chain, + std::string const& serverName); + +/// Builds the verifier `SecTrustEvaluateWithError` decides for. +/// @param blocking Where the evaluation runs. Must outlive it. +/// @return The verifier. +[[nodiscard]] std::shared_ptr makeDarwinChainVerifier(async::IExecutor& blocking); + +} // namespace core::net::detail diff --git a/src/core/net/darwin/DarwinChainVerifier_test.cpp b/src/core/net/darwin/DarwinChainVerifier_test.cpp new file mode 100644 index 00000000..fe13563a --- /dev/null +++ b/src/core/net/darwin/DarwinChainVerifier_test.cpp @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The macOS chain verifier refuses what it must, without the network: the table in +// ChainVerifierTestSupport.hpp, against Security.framework's trust evaluation. +#include + +#include + +#include "../ChainVerifierTestSupport.hpp" +#include "DarwinChainVerifier.hpp" + +TEST_CASE("the macOS chain verifier refuses what no trust store vouches for", + "[net][tls][verifier][platform]") +{ + core::net::testing::requireVerifierRefusals([](core::async::IExecutor& blocking) { + return core::net::detail::makeDarwinChainVerifier(blocking); + }); +} + +TEST_CASE("the macOS chain verifier never follows a certificate's AIA URL", "[net][tls][verifier][platform]") +{ + // An intermediate fetched from a URL the server's certificate names is a request to a host the + // server chose; an incomplete chain is refused instead, as OpenSSL refuses it elsewhere. + auto const allowed = + core::net::detail::networkFetchAllowed({ core::net::testing::untrustedLocalhost() }, "localhost"); + REQUIRE(allowed.has_value()); + CHECK_FALSE(*allowed); +} diff --git a/src/core/net/darwin/SystemTrust.cpp b/src/core/net/darwin/SystemTrust.cpp new file mode 100644 index 00000000..17dfbb76 --- /dev/null +++ b/src/core/net/darwin/SystemTrust.cpp @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The system trust of macOS: Security.framework decides, so a root the keychain distrusts is +// refused and one it would fetch is trusted. No file is read. +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "DarwinChainVerifier.hpp" + +namespace core::net +{ + +async::Task, std::string>> makeSystemTlsClientContext( + platform::FileSystem const* /*files*/, + Environment const* /*environment*/, + async::IExecutor* home, + async::IExecutor* blocking, + TlsClientOptions options) +{ + Require(home != nullptr && blocking != nullptr); + co_return makeTlsClientContext(detail::makeDarwinChainVerifier(*blocking), options); +} + +} // namespace core::net diff --git a/src/core/net/detail/Alpn.hpp b/src/core/net/detail/Alpn.hpp new file mode 100644 index 00000000..ebae0ad2 --- /dev/null +++ b/src/core/net/detail/Alpn.hpp @@ -0,0 +1,79 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// ALPN (RFC 7301) protocol lists in their wire format, and a server's choice from one: the part of +/// ALPN that needs no OpenSSL, shared by `Tls.cpp` and `testing/StrictTlsPeer.cpp`, whose OpenSSL +/// callbacks are thin adapters over it. + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace core::net::detail +{ + +/// ALPN names in wire format: each one behind a length byte. +using AlpnWire = std::vector; + +/// @param names ALPN names, e.g. `"http/1.1"`. +/// @return @p names in wire format, or a reason if one is empty or longer than 255 bytes. +[[nodiscard]] inline std::expected alpnWireFormat(std::span names) +{ + auto wire = AlpnWire {}; + for (auto const& name: names) + { + if (name.empty() || name.size() > std::numeric_limits::max()) + return std::unexpected("an ALPN protocol name must be 1 to 255 bytes: '" + name + "'"); + wire.push_back(static_cast(name.size())); + wire.insert(wire.end(), name.begin(), name.end()); + } + return wire; +} + +/// Splits the next name off the front of a wire-format list. +/// @param list The rest of the list; advanced past the name. +/// @return The name, or no value at the end of the list and for a length byte that is zero or runs +/// past the end -- a malformed list ends there, it is not read beyond. +[[nodiscard]] inline std::optional> nextAlpnName( + std::span& list) noexcept +{ + if (list.empty()) + return std::nullopt; + auto const length = std::size_t { list.front() }; + if (length == 0 || length > list.size() - 1) + { + list = {}; + return std::nullopt; + } + auto const name = list.subspan(1, length); + list = list.subspan(1 + length); + return name; +} + +/// A server's ALPN choice: the first of its own names, in its order of preference, that the client +/// offered (RFC 7301 section 3.2). +/// @param own The server's names, wire format. +/// @param offered The client's names, wire format, as they arrived: possibly malformed. +/// @return The chosen name, a view into @p own; no value when nothing is in common. +[[nodiscard]] inline std::optional> selectAlpn( + std::span own, std::span offered) noexcept +{ + while (auto const candidate = nextAlpnName(own)) + { + auto rest = offered; + while (auto const name = nextAlpnName(rest)) + { + if (std::ranges::equal(*candidate, *name)) + return candidate; + } + } + return std::nullopt; +} + +} // namespace core::net::detail diff --git a/src/core/net/detail/InFlightBudget.hpp b/src/core/net/detail/InFlightBudget.hpp new file mode 100644 index 00000000..001528a6 --- /dev/null +++ b/src/core/net/detail/InFlightBudget.hpp @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// `detail::reserveSlot` -- one slot of a bounded budget of calls that are running and cannot be +/// interrupted: the lookups an @c ExecutorAddressResolver hands out, and the chain verifications a +/// verifying TLS context's sockets start. + +#include +#include +#include + +namespace core::net::detail +{ + +/// Whether a call got one of the budget's slots. +enum class SlotReservation : std::uint8_t +{ + Refused, ///< The budget was full; nothing was taken. + Reserved, ///< One slot is the caller's, to be given back exactly once. +}; + +/// Takes one slot of @p inFlight's budget, if one is free. +/// +/// A loop of compare-exchange rather than an add and a take-back, so that a full budget is never +/// exceeded even for a moment -- several loops may draw on one budget at once. +/// @param inFlight The slots taken. +/// @param maxInFlight How many there are. +/// @return Whether one was taken. +[[nodiscard]] inline SlotReservation reserveSlot(std::atomic& inFlight, + std::size_t maxInFlight) noexcept +{ + auto current = inFlight.load(std::memory_order_relaxed); + do + { + if (current >= maxInFlight) + return SlotReservation::Refused; + } while (!inFlight.compare_exchange_weak( + current, current + 1, std::memory_order_acq_rel, std::memory_order_relaxed)); + return SlotReservation::Reserved; +} + +} // namespace core::net::detail diff --git a/src/core/net/detail/ParkedCall.hpp b/src/core/net/detail/ParkedCall.hpp index 87cebf29..86f80775 100644 --- a/src/core/net/detail/ParkedCall.hpp +++ b/src/core/net/detail/ParkedCall.hpp @@ -6,14 +6,14 @@ /// coroutine on a loop that waits for its answer, with a stop that ends the wait and not the call. /// /// Shared by every resolver that hands `getaddrinfo` to somebody else's thread -/// (@c ThreadedAddressResolver, @c ExecutorAddressResolver), and shaped for any other call that -/// cannot be interrupted once it has started. +/// (@c ThreadedAddressResolver, @c ExecutorAddressResolver), by the TLS socket waiting for its chain +/// verifier, and shaped for any other call that cannot be interrupted once it has started. #include #include +#include #include #include -#include #include #include @@ -48,8 +48,12 @@ enum class SlotState : std::uint8_t /// been delivered into may already be gone. Such an answer is still stored, and an owner who keeps /// the call (a stream whose bytes must not be lost) takes it with @c takeLateAnswer. /// -/// **Nothing here resumes inline.** The waiter is SUBMITTED to the loop it parked on, so the flow -/// continues on the loop's thread and never on the runner's, or the stopper's. +/// **Nothing here resumes inline.** The waiter is SUBMITTED to the executor it parked on, so the +/// flow continues on the loop's thread and never on the runner's, or the stopper's. +/// +/// **A stopped wait can be joined again** (@c rejoin): an owner that keeps the call -- a TLS socket +/// whose handshake is driven again after a cancel -- waits for the same call rather than starting a +/// second one. /// /// **Settling never throws.** It runs where nothing can take an exception -- a detached flow, a /// destructor, a stop callback -- so the one call that can fail, the loop's `submit` running out of @@ -63,9 +67,10 @@ class ParkedCall "settling moves the answer where nothing can take a throw"); public: - /// @param loop Where the waiter is handed back. Null only where nothing ever parks on the call; - /// a waiter with nowhere to go is freed rather than leaked (@c async::detail::Parked). - explicit ParkedCall(EventLoop* loop) noexcept: _loop(loop) {} + /// @param executor Where the waiter is handed back: the loop the waiting flow runs on. Null only + /// where nothing ever parks on the call; a waiter with nowhere to go is freed rather than + /// leaked (@c async::detail::Parked). + explicit ParkedCall(async::IExecutor* executor) noexcept: _executor(executor) {} /// Publishes the answer and hands the waiter back to the loop. /// @@ -198,8 +203,20 @@ class ParkedCall return std::exchange(_answer, std::nullopt); } + /// Makes a call whose wait a stop ended waitable again, for an owner that joins it once more + /// rather than starting the work a second time. + /// + /// An answer that arrived after the stop is then delivered to the next @c wait at once; without + /// one, the next waiter parks as the first did. A call that was not stopped is left as it is. + void rejoin() noexcept + { + auto const guard = std::scoped_lock { _mutex }; + if (_state == SlotState::Cancelled) + _state = _answer.has_value() ? SlotState::Answered : SlotState::Pending; + } + private: - /// Hands @p waiter back to the loop, or frees it where there is nowhere to hand it. + /// Hands @p waiter back to the executor, or frees it where there is nowhere to hand it. /// /// An `async::detail::Parked` rather than a bare `ParkedWork`, so the branch that hands nothing /// on FREES an unowned chain instead of dropping it — `ParkedWork`'s contract, resumed or freed, @@ -208,11 +225,11 @@ class ParkedCall /// @param waiter What was taken out of the call; may be empty. void handBack(async::detail::Parked waiter) noexcept { - if (waiter.handle() && _loop != nullptr) - _loop->submit(waiter.take()); + if (waiter.handle() && _executor != nullptr) + _executor->submit(waiter.take()); } - EventLoop* _loop; + async::IExecutor* _executor; std::mutex _mutex; std::optional _answer; async::ParkedWork _waiter {}; diff --git a/src/core/net/detail/ParkedCall_test.cpp b/src/core/net/detail/ParkedCall_test.cpp index 370527a7..da0470ce 100644 --- a/src/core/net/detail/ParkedCall_test.cpp +++ b/src/core/net/detail/ParkedCall_test.cpp @@ -3,12 +3,14 @@ // `detail::ParkedCall`: the rendezvous both resolvers park on, and Task 11's stdin read will. // Whoever takes the waiter first decides; an answer after a stop is kept for the owner, not lost. #include +#include #include #include #include #include #include +#include #include #include @@ -119,3 +121,53 @@ TEST_CASE("a stop hands the flow back cancelled and keeps the late answer for it CHECK(call->takeLateAnswer() == 9); CHECK_FALSE(call->takeLateAnswer().has_value()); // taken once } + +TEST_CASE("a stopped wait rejoins the same call, before or after its late answer", "[net][parked-call]") +{ + auto clock = core::platform::ManualClock {}; + auto loop = TestLoop { clock }; + auto const answeredFirst = GENERATE(false, true); + CAPTURE(answeredFirst); + auto call = std::make_shared>(&loop); + + auto stopped = Outcome {}; + auto source = core::async::StopSource {}; + auto first = waitInto(call, &stopped); + first.handle().promise().setStopToken(source.get_token()); + first.handle().resume(); + source.request_stop(); + loop.drain(); + REQUIRE(stopped.isFinished); + CHECK(stopped.isCancelled); + + if (answeredFirst) + call->settle(5); + call->rejoin(); + auto joined = Outcome {}; + loop.spawn(waitInto(call, &joined)); + loop.drain(); + if (!answeredFirst) + { + CHECK_FALSE(joined.isFinished); // parked again, as the first waiter was + call->settle(5); + loop.drain(); + } + REQUIRE(joined.isFinished); + CHECK_FALSE(joined.isCancelled); + CHECK(joined.answer == 5); +} + +TEST_CASE("rejoining a call no stop ended changes nothing", "[net][parked-call]") +{ + auto clock = core::platform::ManualClock {}; + auto loop = TestLoop { clock }; + auto call = std::make_shared>(&loop); + call->settle(3); + call->rejoin(); + CHECK_FALSE(call->takeLateAnswer().has_value()); // answered, not late + auto outcome = Outcome {}; + loop.spawn(waitInto(call, &outcome)); + loop.drain(); + REQUIRE(outcome.isFinished); + CHECK(outcome.answer == 3); +} diff --git a/src/core/net/posix/SystemTrust.cpp b/src/core/net/posix/SystemTrust.cpp new file mode 100644 index 00000000..f3174be3 --- /dev/null +++ b/src/core/net/posix/SystemTrust.cpp @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The system trust of a POSIX system that is not Apple's: the anchors its bundle or hashed +// directory holds, found as OpenSSL finds them (`makeFileTrustStore`). +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace core::net +{ + +async::Task, std::string>> makeSystemTlsClientContext( + platform::FileSystem const* files, + Environment const* environment, + async::IExecutor* home, + async::IExecutor* blocking, + TlsClientOptions options) +{ + Require(files != nullptr && environment != nullptr && home != nullptr && blocking != nullptr); + auto const store = makeFileTrustStore(*files, *environment, *home, *blocking); + auto anchors = co_await store->load(); + if (!anchors) + co_return std::unexpected(std::move(anchors.error())); + co_return makeTlsClientContext(std::move(*anchors), options); +} + +} // namespace core::net diff --git a/src/core/net/testing/SocketDecorator.hpp b/src/core/net/testing/SocketDecorator.hpp index 817ffe55..029285b7 100644 --- a/src/core/net/testing/SocketDecorator.hpp +++ b/src/core/net/testing/SocketDecorator.hpp @@ -8,6 +8,7 @@ /// Origin: fastcached `src/tests/SocketDecorator.hpp` (`0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21`). #include +#include #include #include #include @@ -35,8 +36,8 @@ namespace core::net::testing /// **What hand-written copies get wrong is the part they did not write.** @c ISocket has virtuals /// with default implementations -- @c readWithFd, @c handshakeIfNeeded, @c waitReadable, /// @c cancelRead, @c shutdownWrite, @c setReceiveDeadline, @c armKeepAlive, @c peerAddress, -/// @c localEndpoint, @c remoteEndpoint, @c option, @c setOption -- and a decorator that overrides -/// none of them silently answers from the BASE rather than from the socket it decorates: a +/// @c localEndpoint, @c remoteEndpoint, @c option, @c setOption, @c tlsSession -- and a decorator that +/// overrides none of them silently answers from the BASE rather than from the socket it decorates: a /// decorated peer has no address, a half-close reaches nothing, a deadline bounds nothing. None of that is /// visible at a call site, because every one of those defaults succeeds, or answers @c /// NetErrorCode::Unsupported as though the socket had nothing to give. Forwarding them is a property of this @@ -117,6 +118,8 @@ class SocketDecorator: public ISocket return _inner.setOption(option, value); } + [[nodiscard]] ITlsSession const* tlsSession() const noexcept override { return _inner.tlsSession(); } + void close() noexcept override { _inner.close(); } [[nodiscard]] bool isClosed() const noexcept override { return _inner.isClosed(); } diff --git a/src/core/net/testing/StrictTlsPeer.cpp b/src/core/net/testing/StrictTlsPeer.cpp index 37ee2813..f07318cf 100644 --- a/src/core/net/testing/StrictTlsPeer.cpp +++ b/src/core/net/testing/StrictTlsPeer.cpp @@ -1,6 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 #include +#include + #include #include #include @@ -11,9 +13,13 @@ #include #include +#include #include +#include #include +#include #include +#include namespace core::net::testing { @@ -78,7 +84,10 @@ struct StrictTlsPeer::State SSL* ssl = nullptr; BIO* incoming = nullptr; ///< Network -> SSL; owned by `ssl`. std::array staging {}; - bool wireFailed = false; ///< The wire answered an ERROR, which is not an end of stream. + bool wireFailed = false; ///< The wire answered an ERROR, which is not an end of stream. + detail::AlpnWire alpn; ///< ALPN names in wire format: a length byte before each. + std::optional refusal; ///< The alert a server refuses every ClientHello with. + std::optional warning; ///< The warning a server sends on the ClientHello. State() = default; State(State const&) = delete; @@ -117,13 +126,57 @@ namespace } } // namespace +namespace +{ + /// A server's ALPN choice, through the one the TLS layer makes; @p argument is the peer's own + /// names in wire format, which its state owns. None in common: `no_application_protocol`. + int selectAlpn(SSL* /*ssl*/, + unsigned char const** out, + unsigned char* outLength, + unsigned char const* offered, + unsigned int offeredLength, + void* argument) + { + auto const& own = *static_cast(argument); + auto const chosen = detail::selectAlpn(own, std::span { offered, offeredLength }); + if (!chosen) + return SSL_TLSEXT_ERR_ALERT_FATAL; + *out = chosen->data(); + *outLength = static_cast(chosen->size()); + return SSL_TLSEXT_ERR_OK; + } + + /// Warns with the alert the peer was built with, then carries on: what a TLS 1.2 server does + /// for a name it does not serve (`unrecognized_name`). @p argument points at the alert. + int warnOnServerName(SSL* /*ssl*/, int* alert, void* argument) + { + *alert = *static_cast(argument); + return SSL_TLSEXT_ERR_ALERT_WARNING; + } + + /// Refuses every ClientHello with the alert the peer was built with; @p argument points at it. + int refuseClientHello(SSL* /*ssl*/, int* alert, void* argument) + { + *alert = *static_cast(argument); + return SSL_CLIENT_HELLO_ERROR; + } + + /// Caps a context at the newest version @p options allows. + void capVersion(SSL_CTX* ctx, StrictTlsPeerOptions const& options) + { + if (options.maximumVersion == TlsVersion::Tls12) + SSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION); + } +} // namespace + StrictTlsPeer::StrictTlsPeer(std::unique_ptr state) noexcept: _state(std::move(state)) { } StrictTlsPeer::~StrictTlsPeer() = default; -std::expected, std::string> StrictTlsPeer::client(TlsVersion maximumVersion) +std::expected, std::string> StrictTlsPeer::client( + StrictTlsPeerOptions const& options) { ERR_clear_error(); auto state = std::make_unique(); @@ -131,15 +184,24 @@ std::expected, std::string> StrictTlsPeer::client if (state->ctx == nullptr) return std::unexpected("SSL_CTX_new: " + opensslReason()); SSL_CTX_set_verify(state->ctx, SSL_VERIFY_NONE, nullptr); - if (maximumVersion == TlsVersion::Tls12) - SSL_CTX_set_max_proto_version(state->ctx, TLS1_2_VERSION); + capVersion(state->ctx, options); + auto alpn = detail::alpnWireFormat(options.alpn); + if (!alpn) + return std::unexpected(std::string { "an ALPN name must be 1 to 255 bytes" }); + state->alpn = std::move(*alpn); + // Zero is success here, unlike every other SSL_CTX setter. + if (!state->alpn.empty() + && SSL_CTX_set_alpn_protos( + state->ctx, state->alpn.data(), static_cast(state->alpn.size())) + != 0) + return std::unexpected("SSL_CTX_set_alpn_protos: " + opensslReason()); if (auto attached = attachSsl(*state, SSL_set_connect_state); !attached) return std::unexpected(attached.error()); return std::unique_ptr { new StrictTlsPeer(std::move(state)) }; } -std::expected, std::string> StrictTlsPeer::server(CertKeyPem const& material, - TlsVersion maximumVersion) +std::expected, std::string> StrictTlsPeer::server( + CertKeyPem const& material, StrictTlsPeerOptions const& options) { ERR_clear_error(); auto state = std::make_unique(); @@ -155,8 +217,24 @@ std::expected, std::string> StrictTlsPeer::server if (!cert || !key || SSL_CTX_use_certificate(state->ctx, cert.get()) != 1 || SSL_CTX_use_PrivateKey(state->ctx, key.get()) != 1) return std::unexpected("server material: " + opensslReason()); - if (maximumVersion == TlsVersion::Tls12) - SSL_CTX_set_max_proto_version(state->ctx, TLS1_2_VERSION); + capVersion(state->ctx, options); + auto alpn = detail::alpnWireFormat(options.alpn); + if (!alpn) + return std::unexpected(std::string { "an ALPN name must be 1 to 255 bytes" }); + state->alpn = std::move(*alpn); + if (!state->alpn.empty()) + SSL_CTX_set_alpn_select_cb(state->ctx, selectAlpn, &state->alpn); + state->refusal = options.refuseWithAlert; + if (state->refusal) + SSL_CTX_set_client_hello_cb(state->ctx, refuseClientHello, &*state->refusal); + state->warning = options.warnWithAlert; + if (state->warning) + { + // The two setter macros, spelled out: the first casts the callback C-style. + SSL_CTX_callback_ctrl( + state->ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, reinterpret_cast(&warnOnServerName)); + SSL_CTX_ctrl(state->ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, &*state->warning); + } if (auto attached = attachSsl(*state, SSL_set_accept_state); !attached) return std::unexpected(attached.error()); return std::unique_ptr { new StrictTlsPeer(std::move(state)) }; @@ -316,6 +394,46 @@ int StrictTlsPeer::peerChainLength() const return chain != nullptr ? sk_X509_num(chain) : 0; } +std::string StrictTlsPeer::receivedServerName() const +{ + auto const* const name = SSL_get_servername(_state->ssl, TLSEXT_NAMETYPE_host_name); + return name != nullptr ? std::string { name } : std::string {}; +} + +std::string StrictTlsPeer::negotiatedProtocol() const +{ + auto const* selected = static_cast(nullptr); + auto length = 0U; + SSL_get0_alpn_selected(_state->ssl, &selected, &length); + return selected != nullptr ? std::string { reinterpret_cast(selected), length } + : std::string {}; +} + +std::expected expiredCopyOf(CertKeyPem const& material) +{ + ERR_clear_error(); + auto const cert = parseCertificate(material.certPem); + auto keyBio = + BioPtr { BIO_new_mem_buf(material.keyPem.data(), clampToInt(material.keyPem.size())), BIO_free }; + auto const key = + PKeyPtr { keyBio ? PEM_read_bio_PrivateKey(keyBio.get(), nullptr, nullptr, nullptr) : nullptr, + EVP_PKEY_free }; + if (!cert || !key) + return std::unexpected("material: " + opensslReason()); + constexpr auto Day = long { 24L * 60 * 60 }; + if (X509_gmtime_adj(X509_getm_notBefore(cert.get()), -2 * Day) == nullptr + || X509_gmtime_adj(X509_getm_notAfter(cert.get()), -Day) == nullptr + || X509_sign(cert.get(), key.get(), EVP_sha256()) == 0) + return std::unexpected("re-signing: " + opensslReason()); + auto out = BioPtr { BIO_new(BIO_s_mem()), BIO_free }; + if (!out || PEM_write_bio_X509(out.get(), cert.get()) != 1) + return std::unexpected("PEM_write_bio_X509: " + opensslReason()); + auto* data = static_cast(nullptr); + auto const length = BIO_get_mem_data(out.get(), &data); + return CertKeyPem { .certPem = std::string { data, static_cast(length) }, + .keyPem = material.keyPem }; +} + std::string certificateCommonName(std::string_view certPem) { return commonNameOf(parseCertificate(certPem).get()); diff --git a/src/core/net/testing/StrictTlsPeer.hpp b/src/core/net/testing/StrictTlsPeer.hpp index aa3d353f..bc978737 100644 --- a/src/core/net/testing/StrictTlsPeer.hpp +++ b/src/core/net/testing/StrictTlsPeer.hpp @@ -25,8 +25,10 @@ #include #include #include +#include #include #include +#include namespace core::net::testing { @@ -39,24 +41,43 @@ enum class StreamEnd : std::uint8_t Failed, ///< Anything else went wrong. }; +/// What a strict peer offers, selects or refuses. +struct StrictTlsPeerOptions +{ + /// The newest protocol version it speaks; @c TlsVersion::Tls12 makes a peer that cannot speak + /// TLS 1.3. + TlsVersion maximumVersion = TlsVersion::Tls13; + + /// ALPN names. A client offers them; a server selects the first of them the client offered, + /// and refuses a client that offered only others with `no_application_protocol`. + std::vector alpn {}; + + /// A server only: answers every ClientHello with this fatal alert (RFC 8446 section 6), the way + /// a server refuses a client it will not serve. + std::optional refuseWithAlert {}; + + /// A server only: sends this alert as a WARNING when the ClientHello arrives and carries on, as + /// a TLS 1.2 server does with `unrecognized_name`. TLS 1.3 has no warnings, so OpenSSL drops it + /// there; pair it with @c maximumVersion @c TlsVersion::Tls12. + std::optional warnWithAlert {}; +}; + /// One TLS endpoint over the far end of a socket pair, pumped by hand. class CORE_NET_TLS_API StrictTlsPeer { public: /// A client that verifies nothing (the cases check identity by asking, not by failing). - /// @param maximumVersion The newest protocol version it offers; @c TlsVersion::Tls12 makes it a - /// client that cannot speak TLS 1.3. + /// @param options Its newest version and the ALPN names it offers. /// @return The peer, or why OpenSSL could not build it. [[nodiscard]] static std::expected, std::string> client( - TlsVersion maximumVersion = TlsVersion::Tls13); + StrictTlsPeerOptions const& options = {}); /// A server presenting @p material. /// @param material The certificate chain and key to serve. - /// @param maximumVersion The newest protocol version it accepts; @c TlsVersion::Tls12 makes it a - /// server that cannot speak TLS 1.3. + /// @param options Its newest version, the ALPN names it selects from, the alert it refuses with. /// @return The peer, or why OpenSSL refused the material. [[nodiscard]] static std::expected, std::string> server( - CertKeyPem const& material, TlsVersion maximumVersion = TlsVersion::Tls13); + CertKeyPem const& material, StrictTlsPeerOptions const& options = {}); ~StrictTlsPeer(); StrictTlsPeer(StrictTlsPeer const&) = delete; @@ -105,6 +126,13 @@ class CORE_NET_TLS_API StrictTlsPeer /// @return How many certificates the other end sent, leaf included. [[nodiscard]] int peerChainLength() const; + /// @return A server's view of the SNI the client sent (`SSL_get_servername`), or empty when it + /// sent none. + [[nodiscard]] std::string receivedServerName() const; + + /// @return The ALPN protocol the handshake settled on, or empty. + [[nodiscard]] std::string negotiatedProtocol() const; + private: struct State; explicit StrictTlsPeer(std::unique_ptr state) noexcept; @@ -133,6 +161,13 @@ class CORE_NET_TLS_API StrictTlsPeer /// @return Whether a client checking @p address would accept the certificate for it. [[nodiscard]] CORE_NET_TLS_API bool certificateMatchesIp(std::string_view certPem, std::string_view address); +/// Re-signs @p material's certificate with a validity that ended a day ago, so a client that checks +/// it refuses it as expired. The generator refuses to make one; this is what a case asks for instead. +/// @param material A certificate and the key that signed it. +/// @return The expired certificate and the same key, or why OpenSSL refused. +[[nodiscard]] CORE_NET_TLS_API std::expected expiredCopyOf( + CertKeyPem const& material); + /// Leaves an error on the calling thread's OpenSSL error queue, as another connection on the same /// loop thread might. CORE_NET_TLS_API void leaveStaleOpensslError(); diff --git a/src/core/net/windows/SystemTrust.cpp b/src/core/net/windows/SystemTrust.cpp new file mode 100644 index 00000000..2248e25b --- /dev/null +++ b/src/core/net/windows/SystemTrust.cpp @@ -0,0 +1,34 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The system trust of Windows: CryptoAPI's chain engine and SSL policy decide, so a certificate in +// the Disallowed store is refused and a root Automatic Root Update would fetch is trusted. No file +// is read. +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "WindowsChainVerifier.hpp" + +namespace core::net +{ + +async::Task, std::string>> makeSystemTlsClientContext( + platform::FileSystem const* /*files*/, + Environment const* /*environment*/, + async::IExecutor* home, + async::IExecutor* blocking, + TlsClientOptions options) +{ + Require(home != nullptr && blocking != nullptr); + co_return makeTlsClientContext(detail::makeWindowsChainVerifier(*blocking), options); +} + +} // namespace core::net diff --git a/src/core/net/windows/WindowsChainVerifier.cpp b/src/core/net/windows/WindowsChainVerifier.cpp new file mode 100644 index 00000000..7985243c --- /dev/null +++ b/src/core/net/windows/WindowsChainVerifier.cpp @@ -0,0 +1,180 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The Windows chain verifier. The certificates the server presented go into an in-memory store, the +// chain engine builds the leaf's chain from it and the system stores (`CertGetCertificateChain`, +// for server authentication), and the SSL policy checks it for the name +// (`CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL)`). On the blocking executor, because +// the engine may fetch a root through Automatic Root Update. +// +// It never fetches what the server names: `CERT_CHAIN_DISABLE_AIA` keeps the engine from following +// a certificate's Authority Information Access URL to an intermediate, a request to a host of the +// server's choosing that no policy of the caller's saw. A server that sends an incomplete chain is +// refused here, as OpenSSL refuses it on every other system. +// +// No revocation check is requested: an offline responder would then refuse every connection, and +// the soft-fail that avoids it would accept a revoked certificate whenever the answer is blocked. +#include "WindowsChainVerifier.hpp" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +// After , which declares the types it uses; every core-cpp target builds with +// WIN32_LEAN_AND_MEAN, under which does not include it. +#include + +namespace core::net::detail +{ + +namespace +{ + /// `SECURITY_FLAG_IGNORE_CERT_CN_INVALID`, from ``, which is not included for one + /// constant: the SSL policy checks no name. + constexpr auto IgnoreServerName = DWORD { 0x00001000 }; + + struct StoreClose + { + void operator()(void* store) const noexcept { CertCloseStore(store, 0); } + }; + using StorePtr = std::unique_ptr; + + struct ContextFree + { + void operator()(CERT_CONTEXT const* context) const noexcept { CertFreeCertificateContext(context); } + }; + using CertificatePtr = std::unique_ptr; + + struct ChainFree + { + void operator()(CERT_CHAIN_CONTEXT const* chain) const noexcept { CertFreeCertificateChain(chain); } + }; + using ChainPtr = std::unique_ptr; + + [[nodiscard]] std::expected refusal(std::string message) + { + return std::unexpected(TlsFailure { + .kind = TlsFailureKind::Certificate, .alert = std::nullopt, .message = std::move(message) }); + } + + /// A Win32 error or an HRESULT as `0x800B0109: `. + [[nodiscard]] std::string describe(std::string_view call, DWORD code) + { + return std::format("{}: 0x{:08X}: {}", call, code, core::systemErrorMessage(code)); + } + + /// Evaluates @p chain for @p serverName with the SSL chain policy. Blocking. + [[nodiscard]] std::expected evaluate(std::vector const& chain, + std::string const& serverName) + { + if (chain.empty()) + return refusal("the peer presented no certificate"); + auto const store = + StorePtr { CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0, CERT_STORE_CREATE_NEW_FLAG, nullptr) }; + if (!store) + return refusal(describe("CertOpenStore", GetLastError())); + + // The leaf is the first certificate; the rest are intermediates the engine may use. + auto leaf = CertificatePtr {}; + for (auto const& der: chain) + { + if (der.size() > std::numeric_limits::max()) + return refusal("a certificate in the presented chain is too large"); + auto added = PCCERT_CONTEXT { nullptr }; + if (CertAddEncodedCertificateToStore(store.get(), + X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, + reinterpret_cast(der.data()), + static_cast(der.size()), + CERT_STORE_ADD_ALWAYS, + leaf ? nullptr : &added) + == FALSE) + return refusal( + describe("a certificate in the presented chain does not parse", GetLastError())); + if (!leaf) + leaf = CertificatePtr { added }; + } + + // Built for server authentication: a certificate whose EKU says otherwise does not chain. + auto serverAuth = std::string { szOID_PKIX_KP_SERVER_AUTH }; + auto* usage = serverAuth.data(); + auto parameters = CERT_CHAIN_PARA {}; + parameters.cbSize = static_cast(sizeof(parameters)); + parameters.RequestedUsage.dwType = USAGE_MATCH_TYPE_AND; + parameters.RequestedUsage.Usage.cUsageIdentifier = 1; + parameters.RequestedUsage.Usage.rgpszUsageIdentifier = &usage; + auto rawChain = PCCERT_CHAIN_CONTEXT { nullptr }; + if (CertGetCertificateChain( + nullptr, leaf.get(), nullptr, store.get(), ¶meters, chainBuildFlags(), nullptr, &rawChain) + == FALSE) + return refusal(describe("CertGetCertificateChain", GetLastError())); + auto const built = ChainPtr { rawChain }; + + auto wideName = std::wstring {}; + if (!serverName.empty()) + { + auto converted = core::toUtf16(serverName); + if (!converted) + return refusal("the server name is not UTF-8"); + wideName = std::move(*converted); + } + auto ssl = SSL_EXTRA_CERT_CHAIN_POLICY_PARA {}; + ssl.cbSize = static_cast(sizeof(ssl)); + ssl.dwAuthType = AUTHTYPE_SERVER; + // An empty name checks the chain alone. + ssl.fdwChecks = serverName.empty() ? IgnoreServerName : 0; + ssl.pwszServerName = serverName.empty() ? nullptr : wideName.data(); + auto policy = CERT_CHAIN_POLICY_PARA {}; + policy.cbSize = static_cast(sizeof(policy)); + policy.pvExtraPolicyPara = &ssl; + auto status = CERT_CHAIN_POLICY_STATUS {}; + status.cbSize = static_cast(sizeof(status)); + if (CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL, built.get(), &policy, &status) == FALSE) + return refusal(describe("CertVerifyCertificateChainPolicy", GetLastError())); + if (status.dwError != 0) + return refusal(describe("the SSL chain policy refused the chain", status.dwError)); + return {}; + } + + class WindowsChainVerifier final: public IChainVerifier + { + public: + explicit WindowsChainVerifier(async::IExecutor& blocking) noexcept: _blocking { &blocking } {} + + [[nodiscard]] async::Task> verify(std::vector chain, + std::string serverName) override + { + co_await async::ResumeOn { *_blocking }; + co_return evaluate(chain, serverName); + } + + private: + async::IExecutor* _blocking; + }; +} // namespace + +std::uint32_t chainBuildFlags() noexcept +{ + return CERT_CHAIN_DISABLE_AIA; +} + +std::shared_ptr makeWindowsChainVerifier(async::IExecutor& blocking) +{ + return std::make_shared(blocking); +} + +} // namespace core::net::detail diff --git a/src/core/net/windows/WindowsChainVerifier.hpp b/src/core/net/windows/WindowsChainVerifier.hpp new file mode 100644 index 00000000..2b61b1c7 --- /dev/null +++ b/src/core/net/windows/WindowsChainVerifier.hpp @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// The Windows chain verifier: `CertGetCertificateChain` and the SSL chain policy, which honour the +/// Disallowed store and Automatic Root Update, and never fetch an intermediate a certificate's +/// Authority Information Access names. Private to `core::net_tls`. + +#include +#include + +#include +#include + +namespace core::net::detail +{ + +/// @return The flags every chain is built with: `CERT_CHAIN_DISABLE_AIA`, so the engine fetches no +/// intermediate from a URL the server's certificate names. +[[nodiscard]] std::uint32_t chainBuildFlags() noexcept; + +/// Builds the verifier `CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL)` decides for. +/// @param blocking Where the evaluation runs. Must outlive it. +/// @return The verifier. +[[nodiscard]] std::shared_ptr makeWindowsChainVerifier(async::IExecutor& blocking); + +} // namespace core::net::detail diff --git a/src/core/net/windows/WindowsChainVerifier_test.cpp b/src/core/net/windows/WindowsChainVerifier_test.cpp new file mode 100644 index 00000000..a503fa88 --- /dev/null +++ b/src/core/net/windows/WindowsChainVerifier_test.cpp @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The Windows chain verifier refuses what it must, without the network: the table in +// ChainVerifierTestSupport.hpp, against CryptoAPI's chain engine and SSL policy. +#include + +#include + +#include + +// After , which declares the types it uses; every core-cpp target builds with +// WIN32_LEAN_AND_MEAN, under which does not include it. +#include + +#include "../ChainVerifierTestSupport.hpp" +#include "WindowsChainVerifier.hpp" + +TEST_CASE("the Windows chain verifier refuses what no trust store vouches for", + "[net][tls][verifier][platform]") +{ + core::net::testing::requireVerifierRefusals([](core::async::IExecutor& blocking) { + return core::net::detail::makeWindowsChainVerifier(blocking); + }); +} + +TEST_CASE("the Windows chain verifier never follows a certificate's AIA URL", + "[net][tls][verifier][platform]") +{ + // An intermediate fetched from a URL the server's certificate names is a request to a host the + // server chose; an incomplete chain is refused instead, as OpenSSL refuses it elsewhere. + CHECK((core::net::detail::chainBuildFlags() & CERT_CHAIN_DISABLE_AIA) != 0); +} From 42afe6654b96de28bbb0580e9a305908dbd4a7b5 Mon Sep 17 00:00:00 2001 From: Christian Parpart Date: Fri, 27 Nov 2026 05:23:06 +0100 Subject: [PATCH 10/19] refactor(net): one accept loop, acceptLoop, for serve and the servers built on it serve's accept loop moves to net/AcceptLoop.hpp as acceptLoop, unchanged in what it does with a failed accept. It hands each accepted socket to an OnAccepted flow, which is awaited (serve's shape) or spawned, so a second server reuses the loop rather than copying it. AcceptLoopReporting moves with it; HttpServer.hpp includes the new header, so serve's API is unchanged. The backoff answers an enum, not a bool. Signed-off-by: Christian Parpart --- .agent/reference/provenance.md | 2 + docs/modules/net.md | 1 + src/core/net/AcceptLoop.cpp | 160 +++++++++++++++++++++++++++++++++ src/core/net/AcceptLoop.hpp | 80 +++++++++++++++++ src/core/net/CMakeLists.txt | 2 + src/core/net/HttpServer.cpp | 148 +++++------------------------- src/core/net/HttpServer.hpp | 13 +-- 7 files changed, 266 insertions(+), 140 deletions(-) create mode 100644 src/core/net/AcceptLoop.cpp create mode 100644 src/core/net/AcceptLoop.hpp diff --git a/.agent/reference/provenance.md b/.agent/reference/provenance.md index 9981259c..73b0eb0a 100644 --- a/.agent/reference/provenance.md +++ b/.agent/reference/provenance.md @@ -252,6 +252,8 @@ others in notes. | `src/core/net/BackendParity_test.cpp` | contour-terminal/contour | `src/net/EventSourceParity_test.cpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | Task B3: `EventSourceParity_test` renamed, and its direct-registration cases rewritten over `ReadinessHandler` -- a case now asserts which callback ran and how often, because that is what a dispatching backend gives it. The end-to-end cases (the `[closehang]` family above all) are unchanged but for the matrix they run over. New here: Rule 1 asserted from a resumed flow's own frame on every backend, the batch withdrawal on a real kernel (fastcached#475), `setInterest` reporting the kernel's refusal under descriptor pressure (fastcached#1054, #1057), `wake()` from another thread, a dead handle not blinding the backend to a live one, and `makeBackend` answering null for a kind this platform does not build Task B8: `localPort` is `boundPort` Task B7b: every backend without a completion port refuses a `HandleKind::Completion` registration by name, the host-driven one included. | | `src/core/net/CMakeLists.txt` | origin: core-cpp | - | - | replaces contour's `src/net/CMakeLists.txt`: the targets `core::net_types`, `core::net` and `core::net_tls`, and three test binaries; keeps its comment on the PUBLIC `Threads::Threads` Task B8: the dial, the connector and the two resolvers join `core::net`, with `DialPrimitives.cpp` per platform; five new test sources join the `net` binary. Task B9: the datagram, blocking-transport and in-memory-fake sources and their tests join `core::net` and the `net` binary, with `BlockingPrimitives.cpp`, `SocketErrors.cpp` and `UdpSocket.cpp` per platform | | `src/core/net/AcceptedHalfClose_test.cpp` | LASTRADA-Software/fastcached | `src/FastCache/Net/AcceptedHalfClose_test.cpp` | `0708dd54dc7ee72622c8c0783c2bd4a06f0e9b21` | Task B6: `shutdownWrite` from the ACCEPTED side, which no other case here drives. Upstream's two assertions are kept verbatim in meaning -- the peer sees EOF, AND the shutting-down socket's own next write fails -- because an implementation that gets only the first right passes a half-written port. Upstream's reactor thread plus blocking connector becomes one sequential flow on one loop: a loopback dial completes out of the backlog before anything accepts, so no step waits on a sibling that may have bailed, and the accepted end provably has not closed when the peer reads -- a close would send a FIN of its own and pass for the half-close's. Portable on purpose: the defect it pins was one platform's Task B8: `localPort` is `boundPort` | +| `src/core/net/AcceptLoop.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the accept loop `serve` had inline, one loop for it and `core::http::serveHttp`; the backoff answers an enum | +| `src/core/net/AcceptLoop.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): `acceptLoop`, `ConnectionFlow`, `OnAccepted`, `reportAcceptLoopEvent`; `AcceptLoopReporting` moves here from `HttpServer.hpp`, which includes it | | `src/core/net/AcceptPolicy.hpp` | origin: core-cpp | - | - | graduated from LASTRADA-Software/fastcached `src/FastCache/Transport/AcceptPolicy.hpp` at `a11f0c1a37ab317bd1dd7e9c82f2c4a78a5a4b55`, a commit not yet on its master: the row moves to that upstream once it is, [core-cpp#60](https://github.com/contour-terminal/core-cpp/issues/60); 0.6.0: camelBack; the table is a `std::array` sized by `NetErrorCode::Last` with a position check, where upstream used its `EnumTable`; `Stop` is split into `Closed` and `Dead`, and the verdict is an `AcceptAction` (accept again, stop, give up) where upstream had a `stop` bool; `SystemError` is `Unclassified`, backed off on without end and reported degraded after `UnclassifiedBeforeDegraded` (`AcceptConditionChange`), exhaustion is keyed on the new `ResourceExhausted`, and a poll tick counts toward the yield; the warning is a count the caller words (`describeAcceptFailure`), and `onError` takes the code alone; `WaitOutBackoff` not taken, since a loop here waits on its `EventLoop` timer; 0.24.0 (P13): rows for `NameNotFound` and `ResolverTemporaryFailure`, both `Unclassified` | | `src/core/net/AcceptPolicy.cpp` | origin: core-cpp | - | - | graduated from LASTRADA-Software/fastcached `src/FastCache/Transport/AcceptPolicy.cpp` at `a11f0c1a37ab317bd1dd7e9c82f2c4a78a5a4b55`, a commit not yet on its master: the row moves to that upstream once it is, [core-cpp#60](https://github.com/contour-terminal/core-cpp/issues/60); 0.6.0: as the header; the decision is one `switch` over the disposition | | `src/core/net/AcceptPolicy_test.cpp` | origin: core-cpp | - | - | graduated from LASTRADA-Software/fastcached `src/FastCache/Transport/AcceptPolicy_test.cpp` at `a11f0c1a37ab317bd1dd7e9c82f2c4a78a5a4b55`, a commit not yet on its master: the row moves to that upstream once it is, [core-cpp#60](https://github.com/contour-terminal/core-cpp/issues/60); 0.6.0: over `platform::ManualClock`; new: the unclassified give-up and the run that resets it, and exhaustion that never gives up | diff --git a/docs/modules/net.md b/docs/modules/net.md index 87fa22cb..da353c3c 100644 --- a/docs/modules/net.md +++ b/docs/modules/net.md @@ -51,6 +51,7 @@ directory `src/core/net/`. Three targets: | `` | one duplex `ISocket` from two simplex halves | | `` | `withTimeout()`: a task raced against a timer on the loop's clock | | `` | a minimal HTTP/1.1 server: `serve()`, `readRequest()`, `writeResponse()`; `Content-Length` bodies only, every response closes, and a refusal closes lingering (`HttpLimits::linger`). A failed accept is answered by `AcceptErrorPolicy` and reported through `AcceptLoopReporting` | +| `` | `acceptLoop()`: the accept loop `serve()` and `core::http::serveHttp()` share -- every failed accept answered by `AcceptErrorPolicy` and reported through `AcceptLoopReporting`, each connection's flow awaited or spawned (`ConnectionFlow`) | | `` | `AcceptErrorPolicy`, `AcceptErrorTable`, `acceptDispositionOf()`, `describeAcceptFailure()`, `describeAcceptLoopEnded()`: what an accept loop does about a failed accept (see [Accept loops](#accept-loops)) | | `` | `AcceptLoopHealth`: the accept loops of a process that gave up while they were meant to be serving, for a liveness probe | | `` | `closeLingering()`: half-close, drain the peer within `LingerBounds` (time, bytes, reads), then close, so a reply written over a request left unread is not destroyed by the reset a bare close sends | diff --git a/src/core/net/AcceptLoop.cpp b/src/core/net/AcceptLoop.cpp new file mode 100644 index 00000000..989ff125 --- /dev/null +++ b/src/core/net/AcceptLoop.cpp @@ -0,0 +1,160 @@ +// SPDX-License-Identifier: Apache-2.0 +#include + +#include +#include +#include +#include + +#include +#include + +namespace core::net +{ + +namespace +{ + + /// How a backoff ended. + enum class Backoff : std::uint8_t + { + Elapsed, ///< It ran its course: accept again. + Stopped, ///< The listener was closed (or destroyed) or the flow cancelled while it waited. + }; + + /// Waits out an accept backoff, unless the listener is closed or the flow is cancelled first. + /// @param loop The loop whose timer waits. + /// @param closed The listener's close token. + /// @param delay How long. + /// @return How the wait ended. + async::Task backOff(EventLoop* loop, async::StopToken closed, std::chrono::milliseconds delay) + { + try + { + auto const woke = co_await interruptibleSleepUntil(loop, closed, loop->clock().now() + delay); + co_return woke == WakeReason::Deadline ? Backoff::Elapsed : Backoff::Stopped; + } + catch (async::OperationCancelled const&) + { + // The flow's own stop, met in a backoff: the loop returns, as it does when the same stop + // meets it parked in an accept, which the listener answers `Cancelled`. + co_return Backoff::Stopped; + } + } + +} // namespace + +void reportAcceptLoopEvent(AcceptLoopReporting const& reporting, AcceptLoopEvent const& event) +{ + if (reporting.onEvent) + reporting.onEvent(event); + else + reportDiagnostic(event.line); +} + +async::Task acceptLoop(EventLoop* loop, + IListener* listener, + AcceptLoopReporting reporting, + ConnectionFlow flow, + OnAccepted onAccepted) +{ + // Taken while the listener is alive -- the caller's contract -- and kept: the token outlives the + // listener, so asking it before every accept is how this loop never calls into a listener its + // owner closed and destroyed while the loop was backing off or serving a connection. + auto const closed = listener->closeToken(); + auto policy = AcceptErrorPolicy {}; + // Set when the listener was closed or the flow cancelled where the loop could see it; the end + // that follows is the owner's, and only the way out below says anything about it. + auto stopping = false; + while (!stopping && !closed.stop_requested()) + { + auto accepted = AcceptResult {}; + try + { + accepted = co_await listener->accept(); + } + catch (async::OperationCancelled const&) + { + // The flow's own stop, met in an accept that answers it by THROWING `OperationCancelled` + // -- one parked on a loop timer, say, or any `ResultAwaitable` resumed without a value -- + // where core-cpp's socket listeners answer `Cancelled`. Either way the loop returns, and + // the way out still says whether a degraded loop stopped. + stopping = true; + continue; + } + if (!accepted.has_value()) + { + // One failed accept is almost never a failed listener: only a closed or dead one ends + // the loop, and everything else is accepted past (`AcceptPolicy.hpp`). + auto const& error = accepted.error(); + auto const verdict = policy.onError(error.code, loop->clock().now()); + switch (verdict.action) + { + case AcceptAction::Stop: stopping = true; continue; + case AcceptAction::GiveUp: + // A dead listener left open would go on queueing handshakes nobody accepts: the + // port is closed, so it refuses them, and then the end is reported. + if (!closed.stop_requested()) + listener->close(); + reportAcceptLoopEvent( + reporting, + AcceptLoopEvent { .surface = reporting.surface, + .line = describeAcceptLoopEnded(reporting.surface, error), + .error = error, + .kind = AcceptLoopEventKind::GaveUp }); + co_return; + case AcceptAction::AcceptAgain: break; + } + if (verdict.change == AcceptConditionChange::Degraded) + reportAcceptLoopEvent(reporting, + AcceptLoopEvent { .surface = reporting.surface, + .line = describeAcceptDegraded( + reporting.surface, error, verdict.streak), + .error = error, + .kind = AcceptLoopEventKind::Degraded }); + else if (verdict.change == AcceptConditionChange::Recovered) + reportAcceptLoopEvent( + reporting, + AcceptLoopEvent { .surface = reporting.surface, + .line = describeAcceptRecovered(reporting.surface, verdict.streak), + .error = {}, + .kind = AcceptLoopEventKind::Recovered }); + if (verdict.warning.has_value()) + reportAcceptLoopEvent( + reporting, + AcceptLoopEvent { .surface = reporting.surface, + .line = describeAcceptFailure(reporting.surface, error, verdict), + .error = error, + .kind = AcceptLoopEventKind::Warning }); + if (verdict.delay > std::chrono::milliseconds {}) + stopping = co_await backOff(loop, closed, verdict.delay) == Backoff::Stopped; + continue; + } + if (auto const recovered = policy.onAccepted(loop->clock().now()); + recovered.change == AcceptConditionChange::Recovered) + reportAcceptLoopEvent( + reporting, + AcceptLoopEvent { .surface = reporting.surface, + .line = describeAcceptRecovered(reporting.surface, recovered.streak), + .error = {}, + .kind = AcceptLoopEventKind::Recovered }); + auto connection = onAccepted(std::move(*accepted)); + switch (flow) + { + case ConnectionFlow::Awaited: co_await std::move(connection); break; + case ConnectionFlow::Spawned: loop->spawn(std::move(connection)); break; + } + } + // Every way out but giving up comes here: a closed listener, a destroyed one, a cancelled flow. + // A loop that was degraded says it has stopped, or a liveness registry goes on showing a surface + // that was shut down as degraded -- and, restarted under the same name, the new loop has a + // fresh policy that never reports the recovery that would clear it. + if (policy.degraded()) + reportAcceptLoopEvent(reporting, + AcceptLoopEvent { .surface = reporting.surface, + .line = describeAcceptLoopStopped(reporting.surface), + .error = {}, + .kind = AcceptLoopEventKind::Stopped }); +} + +} // namespace core::net diff --git a/src/core/net/AcceptLoop.hpp b/src/core/net/AcceptLoop.hpp new file mode 100644 index 00000000..950cfc82 --- /dev/null +++ b/src/core/net/AcceptLoop.hpp @@ -0,0 +1,80 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// `acceptLoop` -- accepts from a listener until it is closed, answering every failed accept through +/// @c AcceptErrorPolicy, and hands each accepted socket to the caller's flow: awaited before the next +/// accept, or started in a flow of its own. One loop, so `serve` (`HttpServer.hpp`) and `core::http`'s +/// server cannot drift apart in how they treat an `EMFILE` or a dead listener. + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace core::net +{ + +/// Where an accept loop reports what @c AcceptErrorPolicy decided (`AcceptPolicy.hpp`). +struct AcceptLoopReporting +{ + std::string surface = "http"; ///< What the loop serves, as its reports name it. + /// Told each report: a failed accept the loop went on past (rate-limited), the loop becoming + /// degraded on a long run of unclassified failures, recovering from one, and giving up on a dead + /// listener. @c AcceptLoopHealth::record is written to be handed these. **When empty, each + /// report's line goes to @c reportDiagnostic instead**, so a loop that degrades or gives up is + /// never silent by default -- the shape of the incident `AcceptPolicy.hpp` opens with. + std::function onEvent; +}; + +/// Hands one report to where @p reporting says, or to @c reportDiagnostic when it names nowhere. +/// @param reporting Where reports go. +/// @param event The report. +CORE_NET_API void reportAcceptLoopEvent(AcceptLoopReporting const& reporting, AcceptLoopEvent const& event); + +/// What an accept loop does with the flow that serves a connection. +enum class ConnectionFlow : std::uint8_t +{ + Awaited, ///< Awaited before the next accept: one connection at a time, on the loop's own flow. + Spawned, ///< Started with @c EventLoop::spawn: each connection in a flow of its own. +}; + +/// What an accept loop calls with each socket it accepts: the flow that serves it. A socket it does +/// not want, it drops (which closes it) and returns a flow that does nothing. +using OnAccepted = std::function(std::unique_ptr)>; + +/// Accepts from @p listener until it is closed, handing each socket to @p onAccepted. +/// +/// **A failed accept is answered by @c AcceptErrorPolicy, and only a closed or dead listener ends +/// the loop.** A connection that failed before it was handed over is accepted past; exhaustion +/// backs off on @p loop's timer and accepts again; a failure nothing classifies is backed off on for +/// as long as it lasts, and a long run of them is reported as the loop being degraded. A listener +/// found dead (@c NetErrorCode::BadHandle) is CLOSED before the loop reports giving up, so its port +/// refuses rather than queues. A loop that stops while degraded says it stopped. +/// +/// **When it returns.** At its next accept after the listener is closed, at once when the close lands +/// during a backoff, when the listener is dead, and when the flow is cancelled -- parked in an accept +/// or in a backoff, it returns rather than throwing. The close token is taken while the listener is +/// alive and asked before every call into it, so its owner may close and destroy it at any time on +/// @p loop's thread. +/// @param loop The loop @p listener runs on, never null: its timer waits out a backoff, its clock +/// paces the reports, and a @c ConnectionFlow::Spawned flow runs on it (not owned). +/// @param listener The bound listener (not owned); alive when the flow is first resumed. +/// @param reporting Where the loop's reports go. +/// @param flow Whether each connection's flow is awaited or spawned. +/// @param onAccepted The flow for each accepted socket. +/// @return A task that completes when the loop ends. +[[nodiscard]] CORE_NET_API async::Task acceptLoop(EventLoop* loop, + IListener* listener, + AcceptLoopReporting reporting, + ConnectionFlow flow, + OnAccepted onAccepted); + +} // namespace core::net diff --git a/src/core/net/CMakeLists.txt b/src/core/net/CMakeLists.txt index e651b4b8..8e99fbb2 100644 --- a/src/core/net/CMakeLists.txt +++ b/src/core/net/CMakeLists.txt @@ -119,6 +119,7 @@ endif() core_cpp_add_module(net KIND STATIC HEADERS AcceptLoopHealth.hpp + AcceptLoop.hpp AcceptPolicy.hpp AsyncBufferedReader.hpp BlockingConnector.hpp @@ -197,6 +198,7 @@ core_cpp_add_module(net KIND STATIC SOURCES ${_coreCppNetSubset} AcceptLoopHealth.cpp + AcceptLoop.cpp AcceptPolicy.cpp AsyncBufferedReader.cpp AsyncDatagramSocket.cpp diff --git a/src/core/net/HttpServer.cpp b/src/core/net/HttpServer.cpp index 9c2ff0b7..743b3fe4 100644 --- a/src/core/net/HttpServer.cpp +++ b/src/core/net/HttpServer.cpp @@ -2,11 +2,9 @@ #include #include -#include -#include +#include #include #include -#include #include #include @@ -334,37 +332,17 @@ async::Task writeResponse(ISocket* socket, HttpResponse response) namespace { - /// Hands one report of the accept loop to where @p reporting says, or to @c reportDiagnostic when - /// it names nowhere: a loop that degrades or gives up is never silent by default. - /// @param reporting Where reports go. - /// @param event The report. - void report(AcceptLoopReporting const& reporting, AcceptLoopEvent const& event) + /// One accepted connection, as `serve` serves it: the handshake first, once, before anything frames + /// the stream -- a transport that negotiates (TLS) has finished by the first request byte. A + /// connection whose handshake fails has no channel to answer on, so it is dropped unanswered, and + /// closed by `conn`'s destructor, as every connection not refused mid-request is. + async::Task serveAccepted(std::unique_ptr conn, + HttpHandler const* handler, + HttpLimits limits) { - if (reporting.onEvent) - reporting.onEvent(event); - else - reportDiagnostic(event.line); - } - - /// Waits out an accept backoff, unless the listener is closed or the flow is cancelled first. - /// @param loop The loop whose timer waits. - /// @param closed The listener's close token. - /// @param delay How long. - /// @return Whether the loop may accept again: false when the listener was closed (or destroyed) - /// or the flow was cancelled while it waited. - async::Task backOff(EventLoop* loop, async::StopToken closed, std::chrono::milliseconds delay) - { - try - { - auto const woke = co_await interruptibleSleepUntil(loop, closed, loop->clock().now() + delay); - co_return woke == WakeReason::Deadline; - } - catch (async::OperationCancelled const&) - { - // The flow's own stop, met in a backoff: `serve` returns, as it does when the same stop - // meets it parked in an accept, which the listener answers `Cancelled`. - co_return false; - } + if (auto const handshaken = co_await conn->handshakeIfNeeded(); !handshaken.has_value()) + co_return; + co_await handleConnection(conn.get(), handler, limits); } } // namespace @@ -375,101 +353,15 @@ async::Task serve(EventLoop* loop, HttpLimits limits, AcceptLoopReporting reporting) { - // Taken while the listener is alive -- the caller's contract -- and kept: the token outlives the - // listener, so asking it before every accept is how this loop never calls into a listener its - // owner closed and destroyed while the loop was backing off or serving a connection. - auto const closed = listener->closeToken(); - auto policy = AcceptErrorPolicy {}; - // Set when the listener was closed or the flow cancelled where the loop could see it; the end - // that follows is the owner's, and only the way out below says anything about it. - auto stopping = false; - while (!stopping && !closed.stop_requested()) - { - auto accepted = AcceptResult {}; - try - { - accepted = co_await listener->accept(); - } - catch (async::OperationCancelled const&) - { - // The flow's own stop, met in an accept that answers it by THROWING `OperationCancelled` - // -- one parked on a loop timer, say, or any `ResultAwaitable` resumed without a value -- - // where core-cpp's socket listeners answer `Cancelled`. Either way `serve` returns, and - // the way out still says whether a degraded loop stopped. - stopping = true; - continue; - } - if (!accepted.has_value()) - { - // One failed accept is almost never a failed listener: only a closed or dead one ends - // the loop, and everything else is accepted past (`AcceptPolicy.hpp`). - auto const& error = accepted.error(); - auto const verdict = policy.onError(error.code, loop->clock().now()); - switch (verdict.action) - { - case AcceptAction::Stop: stopping = true; continue; - case AcceptAction::GiveUp: - // A dead listener left open would go on queueing handshakes nobody accepts: the - // port is closed, so it refuses them, and then the end is reported. - if (!closed.stop_requested()) - listener->close(); - report(reporting, - AcceptLoopEvent { .surface = reporting.surface, - .line = describeAcceptLoopEnded(reporting.surface, error), - .error = error, - .kind = AcceptLoopEventKind::GaveUp }); - co_return; - case AcceptAction::AcceptAgain: break; - } - if (verdict.change == AcceptConditionChange::Degraded) - report(reporting, - AcceptLoopEvent { .surface = reporting.surface, - .line = - describeAcceptDegraded(reporting.surface, error, verdict.streak), - .error = error, - .kind = AcceptLoopEventKind::Degraded }); - else if (verdict.change == AcceptConditionChange::Recovered) - report(reporting, - AcceptLoopEvent { .surface = reporting.surface, - .line = describeAcceptRecovered(reporting.surface, verdict.streak), - .error = {}, - .kind = AcceptLoopEventKind::Recovered }); - if (verdict.warning.has_value()) - report(reporting, - AcceptLoopEvent { .surface = reporting.surface, - .line = describeAcceptFailure(reporting.surface, error, verdict), - .error = error, - .kind = AcceptLoopEventKind::Warning }); - if (verdict.delay > std::chrono::milliseconds {}) - stopping = !co_await backOff(loop, closed, verdict.delay); - continue; - } - if (auto const recovered = policy.onAccepted(loop->clock().now()); - recovered.change == AcceptConditionChange::Recovered) - report(reporting, - AcceptLoopEvent { .surface = reporting.surface, - .line = describeAcceptRecovered(reporting.surface, recovered.streak), - .error = {}, - .kind = AcceptLoopEventKind::Recovered }); - auto conn = std::move(*accepted); - // Once per connection, before anything frames the stream: a transport that negotiates - // (TLS) has finished doing so before the first request byte is read. A connection whose - // handshake fails has no channel to answer on, so it is dropped unanswered -- and closed - // by `conn`'s destructor, as every connection not refused mid-request is. - if (auto const handshaken = co_await conn->handshakeIfNeeded(); !handshaken.has_value()) - continue; - co_await handleConnection(conn.get(), &handler, limits); - } - // Every way out but giving up comes here: a closed listener, a destroyed one, a cancelled flow. - // A loop that was degraded says it has stopped, or a liveness registry goes on showing a surface - // that was shut down as degraded -- and, restarted under the same name, the new loop has a - // fresh policy that never reports the recovery that would clear it. - if (policy.degraded()) - report(reporting, - AcceptLoopEvent { .surface = reporting.surface, - .line = describeAcceptLoopStopped(reporting.surface), - .error = {}, - .kind = AcceptLoopEventKind::Stopped }); + // Connections are served in sequence (`ConnectionFlow::Awaited`), so `handler`, in this frame, + // outlives every flow that points at it. + co_await acceptLoop(loop, + listener, + std::move(reporting), + ConnectionFlow::Awaited, + [served = &handler, limits](std::unique_ptr conn) { + return serveAccepted(std::move(conn), served, limits); + }); } } // namespace core::net diff --git a/src/core/net/HttpServer.hpp b/src/core/net/HttpServer.hpp index d3042f7d..7843fe45 100644 --- a/src/core/net/HttpServer.hpp +++ b/src/core/net/HttpServer.hpp @@ -13,6 +13,7 @@ /// rather than speculatively. #include +#include #include #include #include @@ -104,18 +105,6 @@ struct HttpLimits .reads = 4 }; }; -/// Where @c serve's accept loop reports what @c AcceptErrorPolicy decided (`AcceptPolicy.hpp`). -struct AcceptLoopReporting -{ - std::string surface = "http"; ///< What the loop serves, as its reports name it. - /// Told each report: a failed accept the loop went on past (rate-limited), the loop becoming - /// degraded on a long run of unclassified failures, recovering from one, and giving up on a dead - /// listener. @c AcceptLoopHealth::record is written to be handed these. **When empty, each - /// report's line goes to @c reportDiagnostic instead**, so a loop that degrades or gives up is - /// never silent by default -- the shape of the incident `AcceptPolicy.hpp` opens with. - std::function onEvent; -}; - /// Serves connections from @p listener until it is closed, dispatching each request /// to @p handler. Connections are handled in sequence on the loop thread (a slow /// handler stalls the accept loop), which suits the single-threaded model this From 83dc2a3d7d4f2219171c8971104a2441fe354fff Mon Sep 17 00:00:00 2001 From: Christian Parpart Date: Fri, 27 Nov 2026 01:39:16 +0100 Subject: [PATCH 11/19] feat(http): message types, framing table, head parser and chunked codec Message types, framing table, head parser and chunked codec. core::http is a new module (DEPS base async net, PLATFORMS native, gated by CORE_CPP_WITH_HTTP, default ON), starting with its pure layer, which no socket enters. Message.hpp: HttpVersion; HttpErrorCode with one code per wasi:http error-code case and a neutral toString; HttpError with that interface's payload types; Fields, whose append refuses a name that is not a token and a value with a control character or edge whitespace, but no name for its meaning; and the validating Method, RequestTarget (four forms) and ReasonPhrase factories. Framing.hpp: HttpLimits; requestFraming and responseFraming, interpreted from one RFC 9112 section 6.3 row table that refuses TE with CL in a request, TE in HTTP/1.0, chunked twice or not final, and a Content-Length other than one decimal value; isFramingField; an incremental, bounded HeadParser that refuses bare LF and CR, whitespace before a colon or the first field, obs-fold in a request (and unfolds it in a response), and a missing or duplicate Host; and a table-driven ChunkedDecoder with chunkHeader and lastChunk. The limit codes differ by MessageRole, from one role table. SmugglingCorpus.hpp is the test-only corpus the server's tests will run too. The vendored smoke now carries http. Refuse a request-target form its method may not use, and say which refusals are 505 and 501. The authority-form is CONNECT's alone and CONNECT has no other; the asterisk-form is OPTIONS'. A mismatch is RequestUriInvalid (RFC 9112 sections 3.2.3 and 3.2.4), from one rule table in the head parser. HttpError gains RefusalReason, which tells an unsupported version (505) and an undecodable request transfer coding (501) apart from the other ProtocolError refusals, since the WIT's error-code has no case for either. The smuggling corpus gains nine target-form rows. Also in this commit: - a bounded field count, quote-aware coding lists, plain chunked requests - an escaped quote keeps a coding list's quoted-string open Signed-off-by: Christian Parpart --- .agent/reference/provenance.md | 9 + .github/workflows/build.yml | 2 +- cmake/CoreCppModules.cmake | 6 + cmake/CoreCppOptions.cmake | 1 + docs/getting-started/options.md | 1 + docs/vendoring.md | 8 +- src/core/http/CMakeLists.txt | 22 + src/core/http/Framing.cpp | 1149 ++++++++++++++++++++++++ src/core/http/Framing.hpp | 271 ++++++ src/core/http/Framing_test.cpp | 866 ++++++++++++++++++ src/core/http/Message.cpp | 152 ++++ src/core/http/Message.hpp | 310 +++++++ src/core/http/Message_test.cpp | 233 +++++ src/core/http/SmugglingCorpus.hpp | 891 ++++++++++++++++++ src/core/http/detail/Syntax.hpp | 213 +++++ tests/consumer-vendored/CMakeLists.txt | 2 +- 16 files changed, 4130 insertions(+), 6 deletions(-) create mode 100644 src/core/http/CMakeLists.txt create mode 100644 src/core/http/Framing.cpp create mode 100644 src/core/http/Framing.hpp create mode 100644 src/core/http/Framing_test.cpp create mode 100644 src/core/http/Message.cpp create mode 100644 src/core/http/Message.hpp create mode 100644 src/core/http/Message_test.cpp create mode 100644 src/core/http/SmugglingCorpus.hpp create mode 100644 src/core/http/detail/Syntax.hpp diff --git a/.agent/reference/provenance.md b/.agent/reference/provenance.md index 73b0eb0a..fa53e801 100644 --- a/.agent/reference/provenance.md +++ b/.agent/reference/provenance.md @@ -230,6 +230,15 @@ others in notes. | `src/core/fs/windows/WindowsPathWalk.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the Windows component walker and the NT seam | | `src/core/fs/windows/WindowsPathWalk.hpp` | origin: core-cpp | - | - | 0.24.0 (P13) | | `src/core/fs/windows/WindowsPathWalk_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/http/CMakeLists.txt` | origin: core-cpp | - | - | 0.24.0 (P13): the module and its test binary | +| `src/core/http/Framing.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the RFC 9112 section 6.3 row table, the head parser and the chunked codec's transition table | +| `src/core/http/Framing.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): limits, body framing, `HeadParser`, `ChunkedDecoder` | +| `src/core/http/Framing_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the smuggling corpus, whole and one byte at a time; the framing tables; the parsers' bounds | +| `src/core/http/Message.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/http/Message.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): one `HttpErrorCode` per WASI 0.3 `wasi:http` `error-code` case, the validating field, method, target and reason factories | +| `src/core/http/Message_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/http/SmugglingCorpus.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): test-only request-smuggling corpus, shared with the server's tests | +| `src/core/http/detail/Syntax.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): the RFC 9110/3986 character-class table both parsers and the factories share | | `src/core/SystemRandomSource.hpp` | origin: core-cpp | - | - | the platform half of `Random.hpp`: one `fillFromSystemRandom()` per platform | | `src/core/log/Assert.hpp` | contour-terminal/contour | `src/crispy/Assert.hpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | `fatal()`/`SoftRequire()` moved here from crispy's `Assert.hpp` to close a base→log layering cycle; `Require`/`Guarantee`/`todo`/`unreachable`/`setFailHandler` stay in `src/core/Assert.hpp` | | `src/core/log/CMakeLists.txt` | origin: core-cpp | - | - | - | diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 61cfeafc..c2b129d7 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1353,7 +1353,7 @@ jobs: run: | cmake -DMODE=sync -DREF="$GITHUB_SHA" -DREPO="$GITHUB_WORKSPACE" \ -DDEST="$RUNNER_TEMP/vendor/core-cpp" \ - "-DMODULES=base;log;cli;codec;platform;async;net;fs;testing" \ + "-DMODULES=base;log;cli;codec;platform;async;net;fs;http;testing" \ -P cmake/CoreCppVendor.cmake sed -n '1,7p' "$RUNNER_TEMP/vendor/core-cpp/MANIFEST" diff --git a/cmake/CoreCppModules.cmake b/cmake/CoreCppModules.cmake index bd54653c..3d083753 100644 --- a/cmake/CoreCppModules.cmake +++ b/cmake/CoreCppModules.cmake @@ -281,6 +281,12 @@ core_cpp_module_target(NAME net_tls MODULE net KIND STATIC DEPS net PLATFORMS na # WASI have no file descriptors to hold. core_cpp_module(NAME fs KIND STATIC DEPS base log async platform PLATFORMS native WHEN CORE_CPP_WITH_FS) +# HTTP/1.1 (RFC 9110/9112): the message vocabulary, the framing rules, the head parser and the +# chunked codec, a pure layer no socket enters. async and net are its edges for what runs over +# core::net's sockets; the error payload already names net::TlsFailure. Native only, like those +# sockets. Its own module rather than more of net, whose serve()/HttpServer.hpp it leaves untouched. +core_cpp_module(NAME http KIND STATIC DEPS base async net PLATFORMS native WHEN CORE_CPP_WITH_HTTP) + # endo's terminal UI. Native only: there is no terminal under Emscripten, where CORE_CPP_WITH_TUI is # forced off. core::tui_output is the part that composes and writes bytes, and it has a row of its # own because it links less than the module does: base alone, no libunicode and no coroutines, so a diff --git a/cmake/CoreCppOptions.cmake b/cmake/CoreCppOptions.cmake index 6dd4e1f5..ce5d12c9 100644 --- a/cmake/CoreCppOptions.cmake +++ b/cmake/CoreCppOptions.cmake @@ -37,6 +37,7 @@ cmake_dependent_option(CORE_CPP_WITH_IMAGES "Decode images in core::tui (stb_ima "CORE_CPP_WITH_TUI" OFF) option(CORE_CPP_WITH_TLS "Build core::net_tls (OpenSSL)" OFF) option(CORE_CPP_WITH_FS "Build core::fs, the descriptor-relative file system" ON) +option(CORE_CPP_WITH_HTTP "Build core::http, HTTP/1.1 messages and framing" ON) # Linux only; ignored elsewhere. Needs pkg-config and libsystemd's development files (libsystemd-dev, # systemd-devel). option(CORE_CPP_WITH_SYSTEMD "Notify of system sleep/wake on Linux through logind (libsystemd)" ON) diff --git a/docs/getting-started/options.md b/docs/getting-started/options.md index 2f44f2fe..0659d49c 100644 --- a/docs/getting-started/options.md +++ b/docs/getting-started/options.md @@ -20,6 +20,7 @@ core-cpp never writes to the parent's cache. | `CORE_CPP_WITH_IMAGES` | ON, when `CORE_CPP_WITH_TUI` is | Decode images in `core::tui` (stb_image) | | `CORE_CPP_WITH_TLS` | OFF | Build `core::net_tls` (OpenSSL, from the system) | | `CORE_CPP_WITH_FS` | ON | Build `core::fs`, the descriptor-relative file system. Native only: under Emscripten and WASI the module is skipped | +| `CORE_CPP_WITH_HTTP` | ON | Build `core::http`, HTTP/1.1 messages and framing. Native only: under Emscripten and WASI the module is skipped | | `CORE_CPP_WITH_SYSTEMD` | ON | Linux only: notify of system sleep/wake through logind (`libsystemd`, found with pkg-config and linked by value). A configure without its development files stops, naming this option; OFF builds without it and `makeNativeSystemPowerMonitor()` reports `NotImplemented` | | `CORE_CPP_WITH_TRACY` | OFF | Instrument core-cpp for the Tracy profiler | | `CORE_CPP_PEDANTIC` | ON when top-level | Compile core-cpp's targets with the pedantic warning set | diff --git a/docs/vendoring.md b/docs/vendoring.md index f3a5d9f1..68763486 100644 --- a/docs/vendoring.md +++ b/docs/vendoring.md @@ -28,7 +28,7 @@ cmake -DMODE=sync -DREF= -DDEST= \ # The same, choosing the modules and the repository explicitly. MODULES is a CMake list, so the # shell must not see its semicolons: quote the whole -D argument. cmake -DMODE=sync -DREF= -DDEST= -DREPO= \ - "-DMODULES=base;log;cli;codec;platform;async;net;fs;testing" \ + "-DMODULES=base;log;cli;codec;platform;async;net;fs;http;testing" \ -P /cmake/CoreCppVendor.cmake # Verify against its MANIFEST. Needs no git, and this one IS the copy's own script. @@ -46,9 +46,9 @@ cmake -DMODE=check -DDEST= -P /cmake/CoreCppVendor.cmake - **`MODULES`** selects which module directories are copied; it defaults to every module the ref has. A module that no option can switch off must be in the list, and `sync` reads the ref's own `cmake/CoreCppModules.cmake` to refuse a list that leaves one out; `CORE_CPP_WITH_TUI=OFF` is - what lets contour leave `tui` out, and `CORE_CPP_WITH_FS=OFF` leaves `fs` out. A copy without the - directory of a module whose option is still on stops the configure with a message naming that - option. + what lets contour leave `tui` out, `CORE_CPP_WITH_FS=OFF` leaves `fs` out and + `CORE_CPP_WITH_HTTP=OFF` leaves `http` out. A copy without the directory of a module whose + option is still on stops the configure with a message naming that option. - **`REF`** is a tag or a full 40-character commit SHA, and `sync` refuses anything else. A branch, `HEAD` or a short SHA names a different tree from one day to the next, and the manifest would then record a ref that cannot restore the copy it describes. diff --git a/src/core/http/CMakeLists.txt b/src/core/http/CMakeLists.txt new file mode 100644 index 00000000..037d8beb --- /dev/null +++ b/src/core/http/CMakeLists.txt @@ -0,0 +1,22 @@ +# SPDX-License-Identifier: Apache-2.0 + +# core::http: HTTP/1.1 (RFC 9110/9112). The pure layer here -- the message vocabulary with its +# validating factories, the framing rules of RFC 9112 section 6.3 as one row table, the incremental +# head parser and the chunked codec -- holds no socket, so every framing rule is tested from a table +# (Framing_test.cpp, over the shared SmugglingCorpus.hpp). +core_cpp_add_module(http KIND STATIC + HEADERS + Framing.hpp + Message.hpp + SOURCES + Framing.cpp + Message.cpp + PUBLIC_LIBS core::base core::net) + +# One binary: the pure layer links nothing but the module. SmugglingCorpus.hpp is the test-only +# corpus the server's cases run too. +core_cpp_add_test(http + SOURCES + Framing_test.cpp + Message_test.cpp + SmugglingCorpus.hpp) diff --git a/src/core/http/Framing.cpp b/src/core/http/Framing.cpp new file mode 100644 index 00000000..c505fded --- /dev/null +++ b/src/core/http/Framing.cpp @@ -0,0 +1,1149 @@ +// SPDX-License-Identifier: Apache-2.0 +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace core::http +{ + +namespace +{ + + // --------------------------------------------------------------------------------------------- + // What differs between a request and a response: the codes a limit is reported with, and two + // syntax rules RFC 9112 words differently for a server and for a user agent. + + /// What a parser does with an obs-fold line (RFC 9112 section 5.2). + enum class ObsFold : std::uint8_t + { + Refuse, ///< A server rejects the message. + Unfold, ///< A user agent replaces the fold with SP. + }; + + /// What a parser does with empty lines before the start line (RFC 9112 section 2.2). + enum class LeadingEmptyLines : std::uint8_t + { + Refuse, ///< Nothing allows them. + Skip, ///< A server ignores them before a request line. + }; + + /// The rules of one @c MessageRole. + struct RoleRules + { + MessageRole role; + HttpErrorCode headSection; ///< The head is past maxHeadBytes. + HttpErrorCode startLineTooLong; ///< The start line is past maxFieldBytes. + HttpErrorCode fieldTooLong; ///< A field line is past maxFieldBytes. + HttpErrorCode trailerSection; ///< The trailers are past maxTrailerBytes. + HttpErrorCode trailerTooLong; ///< A trailer line is past maxFieldBytes. + HttpErrorCode bodySize; ///< The body is past maxBodyBytes. + ObsFold obsFold; + LeadingEmptyLines leadingEmptyLines; + }; + + constexpr auto RoleTable = std::array { + RoleRules { .role = MessageRole::Request, + .headSection = HttpErrorCode::RequestHeaderSectionSize, + .startLineTooLong = HttpErrorCode::RequestUriTooLong, + .fieldTooLong = HttpErrorCode::RequestHeaderSize, + .trailerSection = HttpErrorCode::RequestTrailerSectionSize, + .trailerTooLong = HttpErrorCode::RequestTrailerSize, + .bodySize = HttpErrorCode::RequestBodySize, + .obsFold = ObsFold::Refuse, + .leadingEmptyLines = LeadingEmptyLines::Skip }, + RoleRules { .role = MessageRole::Response, + .headSection = HttpErrorCode::ResponseHeaderSectionSize, + .startLineTooLong = HttpErrorCode::ProtocolError, + .fieldTooLong = HttpErrorCode::ResponseHeaderSize, + .trailerSection = HttpErrorCode::ResponseTrailerSectionSize, + .trailerTooLong = HttpErrorCode::ResponseTrailerSize, + .bodySize = HttpErrorCode::ResponseBodySize, + .obsFold = ObsFold::Unfold, + .leadingEmptyLines = LeadingEmptyLines::Refuse }, + }; + + [[nodiscard]] RoleRules const& rulesFor(MessageRole role) + { + auto const& rules = RoleTable.at(static_cast(role)); + Require(rules.role == role); + return rules; + } + + // --------------------------------------------------------------------------------------------- + // Field lines, shared by the head and the trailer section. + + /// The field name at the start of a (possibly partial) field line, if its colon has been seen. + [[nodiscard]] std::optional nameOf(std::string_view line) + { + auto const colon = line.find(':'); + if (colon == std::string_view::npos) + return std::nullopt; + return std::string { line.substr(0, colon) }; + } + + /// The bound of the section a field line goes into: how many lines it may hold, and the code for + /// one more. + struct FieldSection + { + std::size_t maxFields; + HttpErrorCode tooMany; + }; + + /// Appends the field line held back for a possible obs-fold, if any, within @p section's count. + [[nodiscard]] HttpResult flushField(std::optional& pending, + Fields& into, + FieldSection section) + { + if (!pending) + return {}; + if (into.entries().size() >= section.maxFields) + return std::unexpected( + detail::refusal(section.tooMany, "more than maxFields field lines", pending->name)); + auto field = std::move(*pending); + pending.reset(); + return into.append(std::move(field.name), std::move(field.value)); + } + + /// Takes one complete field line: an obs-fold continues the held-back field (or is refused, by + /// role), any other line appends the held-back one and is held back in its turn. + [[nodiscard]] HttpResult takeFieldLine(std::string_view line, + RoleRules const& rules, + FieldSection section, + std::optional& pending, + Fields& into) + { + if (detail::isIn(line.front(), detail::CharClass::Whitespace)) + { + if (!pending) + return std::unexpected( + detail::refusal(HttpErrorCode::ProtocolError, "whitespace before the first field line")); + if (rules.obsFold == ObsFold::Refuse) + return std::unexpected( + detail::refusal(HttpErrorCode::ProtocolError, "an obs-fold line", pending->name)); + auto const continuation = detail::trimWhitespace(line); + if (!continuation.empty()) + pending->value += (pending->value.empty() ? "" : " ") + std::string { continuation }; + return {}; + } + if (auto flushed = flushField(pending, into, section); !flushed) + return flushed; + auto const colon = line.find(':'); + if (colon == std::string_view::npos) + return std::unexpected( + detail::refusal(HttpErrorCode::ProtocolError, "a field line without a colon")); + // Whitespace between the name and the colon (RFC 9112 section 5.1) makes the name no token, so + // Fields::append refuses it with every other malformed name. + auto const name = line.substr(0, colon); + pending = Field { .name = std::string { name }, + .value = std::string { detail::trimWhitespace(line.substr(colon + 1)) } }; + return {}; + } + + // --------------------------------------------------------------------------------------------- + // Start lines. + + /// The version of an `HTTP/x.y` token: major 1 only, and any minor past 0 is HTTP/1.1. + [[nodiscard]] std::optional parseVersion(std::string_view text) + { + constexpr auto Prefix = std::string_view { "HTTP/1." }; + if (text.size() != Prefix.size() + 1 || !text.starts_with(Prefix) + || !detail::isIn(text.back(), detail::CharClass::Digit)) + return std::nullopt; + return text.back() == '0' ? HttpVersion::Http10 : HttpVersion::Http11; + } + + /// The refusal of a start line whose version is not HTTP/1.x. + [[nodiscard]] HttpError unsupportedVersion() + { + return detail::refusal(HttpErrorCode::ProtocolError, + "an unsupported HTTP version", + std::nullopt, + std::nullopt, + RefusalReason::UnsupportedVersion); + } + + /// Whether a method may use only its own target form, or others besides. + enum class MethodForms : std::uint8_t + { + Any, ///< The method may use the other forms too. + OnlyThis, ///< The method uses this form and no other. + }; + + /// A request-target form only one method may use (RFC 9112 sections 3.2.3 and 3.2.4). + struct TargetFormRule + { + RequestTargetForm form; + std::string_view method; + MethodForms methodForms; + }; + + /// Authority-form is CONNECT's, and CONNECT has no other; `*` is OPTIONS', which may also name a + /// resource. Origin- and absolute-form are any other method's. + constexpr auto TargetFormRules = std::array { + TargetFormRule { + .form = RequestTargetForm::Authority, .method = "CONNECT", .methodForms = MethodForms::OnlyThis }, + TargetFormRule { + .form = RequestTargetForm::Asterisk, .method = "OPTIONS", .methodForms = MethodForms::Any }, + }; + + /// Refuses a request target whose form its method may not use. + [[nodiscard]] HttpResult checkTargetForm(std::string_view method, RequestTargetForm form) + { + for (auto const& rule: TargetFormRules) + { + auto const formIsRules = form == rule.form; + auto const methodIsRules = method == rule.method; + if (formIsRules != methodIsRules && (formIsRules || rule.methodForms == MethodForms::OnlyThis)) + return std::unexpected( + detail::refusal(HttpErrorCode::RequestUriInvalid, + std::format("a request-target form {} may not use", method))); + } + return {}; + } + + /// Whether @p host is a valid Host field value (RFC 9112 section 3.2): an authority, possibly + /// empty. + [[nodiscard]] bool isHostValue(std::string_view host) + { + return host.empty() || detail::isAuthority(host, detail::PortRule::Optional); + } + + // --------------------------------------------------------------------------------------------- + // Body framing (RFC 9112 section 6.3): the fields are classified into shapes, and the first row + // of FramingTable that matches the shapes decides. + + /// The shape of the Transfer-Encoding fields. + enum class TransferShape : std::uint8_t + { + Absent, ///< No Transfer-Encoding. + Chunked, ///< Exactly `chunked`: one coding, no parameter. + CodedChunked, ///< A valid list whose final coding is chunked, after other codings or parameters. + OtherLast, ///< A valid list whose final coding is not chunked. + Invalid, ///< Empty, not tokens, an unterminated quote, chunked twice or with a parameter. + }; + + /// The shape of the Content-Length fields. + enum class LengthShape : std::uint8_t + { + Absent, ///< No Content-Length. + Valid, ///< One decimal value, possibly repeated. + Invalid, ///< Anything else. + }; + + /// What of the request method decides a response's framing. + enum class MethodShape : std::uint8_t + { + Other, + Head, + Connect, + }; + + /// What of the status decides a response's framing. + enum class StatusShape : std::uint8_t + { + Other, + Informational, ///< 1xx. + NoContent, ///< 204, 304. + Success, ///< Any other 2xx. + }; + + /// What a matching row decides. + enum class Verdict : std::uint8_t + { + NoBody, + Length, + Chunked, + UntilClose, + Refuse, + }; + + /// Whether a row overrides the persistence the version and Connection field give. + enum class PersistenceRule : std::uint8_t + { + FromFields, ///< As the version and the Connection field say (RFC 9112 section 9.3). + Close, ///< The connection closes. + }; + + /// The bit of @p value in a row's mask. + template + [[nodiscard]] constexpr std::uint8_t bit(Enum value) noexcept + { + return static_cast(1U << static_cast(value)); + } + + /// A row's mask that matches every value. + constexpr std::uint8_t AnyValue = 0b1111'1111; + + /// One rule: masks over role, version, method, status, Transfer-Encoding and Content-Length, + /// then what it decides. + struct FramingRow + { + std::uint8_t roles; + std::uint8_t versions; + std::uint8_t methods; + std::uint8_t statuses; + std::uint8_t transfers; + std::uint8_t lengths; + Verdict verdict; + /// Close on every Refuse row: a refusal is fatal to the connection, which the caller answers + /// (if it can) and closes, so the refusal itself carries no Framing. + PersistenceRule persistence; + std::string_view why; + /// What a Refuse row refuses for, beyond @c HttpErrorCode::ProtocolError; Unclassified elsewhere. + RefusalReason reason = RefusalReason::Unclassified; + }; + + constexpr auto Request = bit(MessageRole::Request); + constexpr auto Response = bit(MessageRole::Response); + constexpr auto TransferPresent = bit(TransferShape::Chunked) | bit(TransferShape::CodedChunked) + | bit(TransferShape::OtherLast) | bit(TransferShape::Invalid); + constexpr auto ChunkedFinal = bit(TransferShape::Chunked) | bit(TransferShape::CodedChunked); + constexpr auto LengthPresent = bit(LengthShape::Valid) | bit(LengthShape::Invalid); + + /// RFC 9112 section 6.3, in its order, with sections 6.1 and 7 folded in; the first match wins. + constexpr auto FramingTable = std::array { + FramingRow { Response, + AnyValue, + bit(MethodShape::Head), + AnyValue, + AnyValue, + AnyValue, + Verdict::NoBody, + PersistenceRule::FromFields, + "a response to HEAD has no body" }, + FramingRow { Response, + AnyValue, + AnyValue, + bit(StatusShape::Informational), + AnyValue, + AnyValue, + Verdict::NoBody, + PersistenceRule::FromFields, + "a 1xx response has no body" }, + FramingRow { Response, + AnyValue, + AnyValue, + bit(StatusShape::NoContent), + AnyValue, + AnyValue, + Verdict::NoBody, + PersistenceRule::FromFields, + "a 204 or 304 response has no body" }, + FramingRow { Response, + AnyValue, + bit(MethodShape::Connect), + bit(StatusShape::Success), + AnyValue, + AnyValue, + Verdict::NoBody, + PersistenceRule::Close, + "a 2xx to CONNECT turns the connection into a tunnel" }, + FramingRow { AnyValue, + bit(HttpVersion::Http10), + AnyValue, + AnyValue, + TransferPresent, + AnyValue, + Verdict::Refuse, + PersistenceRule::Close, + "Transfer-Encoding in an HTTP/1.0 message" }, + FramingRow { AnyValue, + AnyValue, + AnyValue, + AnyValue, + bit(TransferShape::Invalid), + AnyValue, + Verdict::Refuse, + PersistenceRule::Close, + "an invalid Transfer-Encoding (empty, not tokens, an unterminated quote, or chunked " + "twice or with a " + "parameter)" }, + FramingRow { Request, + AnyValue, + AnyValue, + AnyValue, + TransferPresent, + LengthPresent, + Verdict::Refuse, + PersistenceRule::Close, + "a request with both Transfer-Encoding and Content-Length" }, + FramingRow { Request, + AnyValue, + AnyValue, + AnyValue, + bit(TransferShape::OtherLast), + AnyValue, + Verdict::Refuse, + PersistenceRule::Close, + "chunked is not a request's final transfer coding" }, + FramingRow { Request, + AnyValue, + AnyValue, + AnyValue, + bit(TransferShape::CodedChunked), + AnyValue, + Verdict::Refuse, + PersistenceRule::Close, + "a request transfer coding other than chunked, or a parameter (RFC 9112 6.1: 501)", + RefusalReason::UnimplementedCoding }, + FramingRow { Request, + AnyValue, + AnyValue, + AnyValue, + bit(TransferShape::Chunked), + AnyValue, + Verdict::Chunked, + PersistenceRule::FromFields, + "a chunked request" }, + FramingRow { Response, + AnyValue, + AnyValue, + AnyValue, + ChunkedFinal, + LengthPresent, + Verdict::Chunked, + PersistenceRule::Close, + "Transfer-Encoding overrides Content-Length; the connection closes" }, + FramingRow { Response, + AnyValue, + AnyValue, + AnyValue, + ChunkedFinal, + AnyValue, + Verdict::Chunked, + PersistenceRule::FromFields, + "a chunked response" }, + FramingRow { Response, + AnyValue, + AnyValue, + AnyValue, + bit(TransferShape::OtherLast), + AnyValue, + Verdict::UntilClose, + PersistenceRule::Close, + "chunked is not the final coding; the body ends at close" }, + FramingRow { AnyValue, + AnyValue, + AnyValue, + AnyValue, + AnyValue, + bit(LengthShape::Invalid), + Verdict::Refuse, + PersistenceRule::Close, + "an invalid Content-Length" }, + FramingRow { AnyValue, + AnyValue, + AnyValue, + AnyValue, + AnyValue, + bit(LengthShape::Valid), + Verdict::Length, + PersistenceRule::FromFields, + "a length" }, + FramingRow { Request, + AnyValue, + AnyValue, + AnyValue, + AnyValue, + AnyValue, + Verdict::NoBody, + PersistenceRule::FromFields, + "a request without framing fields has no body" }, + FramingRow { Response, + AnyValue, + AnyValue, + AnyValue, + AnyValue, + AnyValue, + Verdict::UntilClose, + PersistenceRule::Close, + "a response without framing fields ends at close" }, + }; + + /// Whether a field's list parsed cleanly. + enum class ListSyntax : std::uint8_t + { + Valid, ///< Every element ended. + UnterminatedQuote, ///< A quoted-string ran to the end of a value. + }; + + /// The elements of every value of the field @p name: the comma-separated list of RFC 9110 + /// section 5.6.1, each element without its whitespace, empty elements included. A comma inside a + /// quoted-string (section 5.6.4, with its backslash escapes) does not split. + template + ListSyntax forEachElement(Fields const& fields, std::string_view name, Visit visit) + { + /// Where the split is within a value. + enum class Quoting : std::uint8_t + { + Outside, ///< Not in a quoted-string. + Inside, ///< In one. + Escaped, ///< After a backslash in one. + }; + auto syntax = ListSyntax::Valid; + for (auto const value: fields.get(name)) + { + auto quoting = Quoting::Outside; + auto start = std::size_t { 0 }; + auto index = std::size_t { 0 }; + for (auto const octet: value) + { + if (quoting == Quoting::Escaped) + quoting = Quoting::Inside; + else if (quoting == Quoting::Inside && octet == '\\') + quoting = Quoting::Escaped; + else if (octet == '"') + quoting = quoting == Quoting::Inside ? Quoting::Outside : Quoting::Inside; + else if (quoting == Quoting::Outside && octet == ',') + { + visit(detail::trimWhitespace(value.substr(start, index - start))); + start = index + 1; + } + ++index; + } + visit(detail::trimWhitespace(value.substr(start))); + if (quoting != Quoting::Outside) + syntax = ListSyntax::UnterminatedQuote; + } + return syntax; + } + + [[nodiscard]] TransferShape transferShapeOf(Fields const& fields) + { + if (fields.get("Transfer-Encoding").empty()) + return TransferShape::Absent; + auto codings = std::size_t { 0 }; + auto chunkedSeen = false; + auto lastIsChunked = false; + auto valid = true; + auto plain = true; + auto const syntax = forEachElement(fields, "Transfer-Encoding", [&](std::string_view element) { + if (element.empty()) + return; + auto const semicolon = element.find(';'); + auto const coding = detail::trimWhitespace(element.substr(0, semicolon)); + auto const isChunked = detail::equalsIgnoringCase(coding, "chunked"); + auto const hasParameter = semicolon != std::string_view::npos; + if (!detail::isToken(coding) || (isChunked && (chunkedSeen || hasParameter))) + valid = false; + plain = plain && isChunked && !hasParameter; + ++codings; + chunkedSeen = chunkedSeen || isChunked; + lastIsChunked = isChunked; + }); + if (syntax != ListSyntax::Valid || !valid || codings == 0) + return TransferShape::Invalid; + if (!lastIsChunked) + return TransferShape::OtherLast; + return plain && codings == 1 ? TransferShape::Chunked : TransferShape::CodedChunked; + } + + /// The shape of the Content-Length fields and, when valid, their one value. + struct LengthFacts + { + LengthShape shape = LengthShape::Absent; + std::uint64_t value = 0; + }; + + [[nodiscard]] LengthFacts lengthOf(Fields const& fields) + { + if (fields.get("Content-Length").empty()) + return {}; + auto agreed = std::optional {}; + auto valid = true; + forEachElement(fields, "Content-Length", [&](std::string_view element) { + auto const value = detail::parseDecimal(element); + if (!value || (agreed && *agreed != *value)) + { + valid = false; + return; + } + agreed = value; + }); + if (!valid || !agreed) + return LengthFacts { .shape = LengthShape::Invalid, .value = 0 }; + return LengthFacts { .shape = LengthShape::Valid, .value = *agreed }; + } + + /// Whether the Connection field lists @p option. + [[nodiscard]] bool hasConnectionOption(Fields const& fields, std::string_view option) + { + auto found = false; + forEachElement(fields, "Connection", [&](std::string_view element) { + found = found || detail::equalsIgnoringCase(element, option); + }); + return found; + } + + /// The persistence of RFC 9112 section 9.3: close if asked, else HTTP/1.1 persists and HTTP/1.0 + /// persists only when asked to keep alive. + [[nodiscard]] Persistence persistenceOf(HttpVersion version, Fields const& fields) + { + if (hasConnectionOption(fields, "close")) + return Persistence::Close; + if (version == HttpVersion::Http11 || hasConnectionOption(fields, "keep-alive")) + return Persistence::KeepAlive; + return Persistence::Close; + } + + [[nodiscard]] MethodShape methodShapeOf(std::string_view method) + { + if (method == "HEAD") + return MethodShape::Head; + if (method == "CONNECT") + return MethodShape::Connect; + return MethodShape::Other; + } + + [[nodiscard]] StatusShape statusShapeOf(std::uint16_t status) + { + if (status >= 100 && status < 200) + return StatusShape::Informational; + if (status == 204 || status == 304) + return StatusShape::NoContent; + if (status >= 200 && status < 300) + return StatusShape::Success; + return StatusShape::Other; + } + + [[nodiscard]] HttpResult frame( + MessageRole role, HttpVersion version, MethodShape method, StatusShape status, Fields const& fields) + { + auto const transfer = transferShapeOf(fields); + auto const length = lengthOf(fields); + auto const matches = [&](FramingRow const& row) { + return (row.roles & bit(role)) != 0 && (row.versions & bit(version)) != 0 + && (row.methods & bit(method)) != 0 && (row.statuses & bit(status)) != 0 + && (row.transfers & bit(transfer)) != 0 && (row.lengths & bit(length.shape)) != 0; + }; + auto const row = std::ranges::find_if(FramingTable, matches); + // The last two rows match every request and every response. + Require(row != FramingTable.end()); + auto const persistence = + row->persistence == PersistenceRule::Close ? Persistence::Close : persistenceOf(version, fields); + switch (row->verdict) + { + case Verdict::NoBody: + return Framing { .kind = BodyFraming::None, .length = 0, .persistence = persistence }; + case Verdict::Length: + return Framing { .kind = BodyFraming::Length, + .length = length.value, + .persistence = persistence }; + case Verdict::Chunked: + return Framing { .kind = BodyFraming::Chunked, .length = 0, .persistence = persistence }; + case Verdict::UntilClose: + return Framing { .kind = BodyFraming::UntilClose, .length = 0, .persistence = persistence }; + case Verdict::Refuse: break; + } + return std::unexpected(detail::refusal( + HttpErrorCode::ProtocolError, std::string { row->why }, std::nullopt, std::nullopt, row->reason)); + } + + /// The fields the connection writes itself (D7). + constexpr auto FramingFieldNames = std::array { + "Transfer-Encoding", "Content-Length", "Connection", "Keep-Alive", "TE", "Upgrade", + }; + + // --------------------------------------------------------------------------------------------- + // The chunked decoder's transition table: one row per state, one column per character class. + + /// The class of an octet outside chunk data. + enum class ChunkClass : std::uint8_t + { + Hex, ///< HEXDIG. + Semicolon, ///< ';'. + Space, ///< SP, HTAB. + Cr, ///< CR. + Lf, ///< LF. + Text, ///< Any other visible octet or obs-text. + Control, ///< Any other control octet, NUL included. + }; + constexpr auto ChunkClassCount = std::size_t { 7 }; + + [[nodiscard]] constexpr ChunkClass chunkClassOf(char octet) noexcept + { + if (octet == '\r') + return ChunkClass::Cr; + if (octet == '\n') + return ChunkClass::Lf; + if (octet == ';') + return ChunkClass::Semicolon; + if (detail::isIn(octet, detail::CharClass::Hex)) + return ChunkClass::Hex; + if (detail::isIn(octet, detail::CharClass::Whitespace)) + return ChunkClass::Space; + if (detail::isIn(octet, detail::CharClass::FieldValue)) + return ChunkClass::Text; + return ChunkClass::Control; + } + + /// What a transition does besides moving to its state. + enum class ChunkAction : std::uint8_t + { + Refuse, ///< The octet is not allowed here. + Line, ///< Counts a chunk-line octet. + Digit, ///< Counts a chunk-line octet and adds a hex digit to the size. + EndSize, ///< Counts a chunk-line octet; the size has ended and needs a digit. + EndLine, ///< The chunk line has ended: data follows, or the trailers if the size is 0. + Expect, ///< The octet was the one expected; nothing else. + TrailerByte, ///< Adds an octet to the trailer line. + EndTrailer, ///< The trailer line has ended: a field, or the end of the body if empty. + }; + + using State = ChunkedDecoder::State; + + struct ChunkTransition + { + State next = State::Failed; + ChunkAction action = ChunkAction::Refuse; + std::string_view why; + }; + + using ChunkRow = std::array; + + /// A row in which every class is refused for @p why but those @p allowed name. + constexpr ChunkRow refuseAllBut(std::string_view why, + std::initializer_list> allowed) + { + auto row = ChunkRow {}; + for (auto& transition: row) + transition = ChunkTransition { .next = State::Failed, .action = ChunkAction::Refuse, .why = why }; + for (auto const& [chunkClass, transition]: allowed) + row.at(static_cast(chunkClass)) = transition; + return row; + } + + constexpr auto StateCount = static_cast(State::Failed) + 1; + + constexpr auto ChunkTable = [] { + auto table = std::array {}; + for (auto& row: table) + row = refuseAllBut("no octet is read in this state", {}); + auto const at = [&table](State state) -> ChunkRow& { + return table.at(static_cast(state)); + }; + at(State::Size) = refuseAllBut( + "a chunk size is hex digits, then a ';', whitespace or CRLF", + { { ChunkClass::Hex, { .next = State::Size, .action = ChunkAction::Digit, .why = {} } }, + { ChunkClass::Semicolon, + { .next = State::Extension, .action = ChunkAction::EndSize, .why = {} } }, + { ChunkClass::Space, { .next = State::SizeSpace, .action = ChunkAction::EndSize, .why = {} } }, + { ChunkClass::Cr, { .next = State::SizeLf, .action = ChunkAction::EndSize, .why = {} } } }); + at(State::SizeSpace) = refuseAllBut( + "whitespace after a chunk size is followed by a ';' only", + { { ChunkClass::Space, { .next = State::SizeSpace, .action = ChunkAction::Line, .why = {} } }, + { ChunkClass::Semicolon, + { .next = State::Extension, .action = ChunkAction::Line, .why = {} } } }); + at(State::Extension) = refuseAllBut( + "a chunk extension holds a control octet or a bare LF", + { { ChunkClass::Hex, { .next = State::Extension, .action = ChunkAction::Line, .why = {} } }, + { ChunkClass::Semicolon, { .next = State::Extension, .action = ChunkAction::Line, .why = {} } }, + { ChunkClass::Space, { .next = State::Extension, .action = ChunkAction::Line, .why = {} } }, + { ChunkClass::Text, { .next = State::Extension, .action = ChunkAction::Line, .why = {} } }, + { ChunkClass::Cr, { .next = State::SizeLf, .action = ChunkAction::Line, .why = {} } } }); + at(State::SizeLf) = refuseAllBut( + "a chunk line's CR is not followed by LF", + { { ChunkClass::Lf, { .next = State::Data, .action = ChunkAction::EndLine, .why = {} } } }); + at(State::DataCr) = refuseAllBut( + "chunk data is not followed by CRLF", + { { ChunkClass::Cr, { .next = State::DataLf, .action = ChunkAction::Expect, .why = {} } } }); + at(State::DataLf) = refuseAllBut( + "chunk data's CR is not followed by LF", + { { ChunkClass::Lf, { .next = State::Size, .action = ChunkAction::Expect, .why = {} } } }); + at(State::TrailerLine) = refuseAllBut( + "a trailer line holds a control octet or a bare LF", + { { ChunkClass::Hex, + { .next = State::TrailerLine, .action = ChunkAction::TrailerByte, .why = {} } }, + { ChunkClass::Semicolon, + { .next = State::TrailerLine, .action = ChunkAction::TrailerByte, .why = {} } }, + { ChunkClass::Space, + { .next = State::TrailerLine, .action = ChunkAction::TrailerByte, .why = {} } }, + { ChunkClass::Text, + { .next = State::TrailerLine, .action = ChunkAction::TrailerByte, .why = {} } }, + { ChunkClass::Cr, { .next = State::TrailerLf, .action = ChunkAction::Expect, .why = {} } } }); + at(State::TrailerLf) = refuseAllBut( + "a trailer line's CR is not followed by LF", + { { ChunkClass::Lf, + { .next = State::TrailerLine, .action = ChunkAction::EndTrailer, .why = {} } } }); + return table; + }(); + + /// The most hex digits a chunk size may have: 16 fill 64 bits, and a 17th could overflow them. + constexpr auto MaxChunkSizeDigits = std::size_t { 16 }; + + /// The value of the hex digit @p octet. + [[nodiscard]] constexpr std::uint64_t hexValue(char octet) noexcept + { + if (octet >= '0' && octet <= '9') + return static_cast(octet - '0'); + return static_cast(detail::toLowerAscii(octet) - 'a') + 10; + } + +} // namespace + +// ------------------------------------------------------------------------------------------------- +// Framing + +HttpResult requestFraming(HttpVersion version, Fields const& fields) +{ + return frame(MessageRole::Request, version, MethodShape::Other, StatusShape::Other, fields); +} + +HttpResult responseFraming(std::string_view requestMethod, + HttpVersion version, + std::uint16_t status, + Fields const& fields) +{ + return frame(MessageRole::Response, version, methodShapeOf(requestMethod), statusShapeOf(status), fields); +} + +bool isFramingField(std::string_view name) noexcept +{ + return std::ranges::any_of(FramingFieldNames, [name](std::string_view framing) { + return detail::equalsIgnoringCase(framing, name); + }); +} + +// ------------------------------------------------------------------------------------------------- +// HeadParser + +HeadParser::HeadParser(MessageRole role, HttpLimits limits): _role { role }, _limits { limits } +{ +} + +HttpResult HeadParser::feed(std::string_view bytes) +{ + if (_state == State::Failed) + return std::unexpected(*_error); + if (_state == State::Complete) + return FeedResult { .progress = Progress::Complete, .consumed = 0 }; + auto const& rules = rulesFor(_role); + auto consumed = std::size_t { 0 }; + for (auto const octet: bytes) + { + ++consumed; + if (++_headBytes > _limits.maxHeadBytes) + return std::unexpected(fail(detail::refusal(rules.headSection, + "the head is past maxHeadBytes", + std::nullopt, + std::uint64_t { _headBytes }))); + switch (_lineState) + { + case LineState::Text: + if (octet == '\r') + { + _lineState = LineState::Cr; + break; + } + if (octet == '\n') + return std::unexpected( + fail(detail::refusal(HttpErrorCode::ProtocolError, "a bare LF ends a line"))); + if (_line.size() >= _limits.maxFieldBytes) + { + auto const isStartLine = _state == State::StartLine; + return std::unexpected( + fail(detail::refusal(isStartLine ? rules.startLineTooLong : rules.fieldTooLong, + "a line is past maxFieldBytes", + isStartLine ? std::nullopt : nameOf(_line), + std::uint64_t { _line.size() + 1 }))); + } + _line += octet; + break; + case LineState::Cr: + if (octet != '\n') + return std::unexpected( + fail(detail::refusal(HttpErrorCode::ProtocolError, "a bare CR in a line"))); + _lineState = LineState::Text; + if (auto ended = endLine(); !ended) + return std::unexpected(fail(std::move(ended.error()))); + if (_state == State::Complete) + return FeedResult { .progress = Progress::Complete, .consumed = consumed }; + break; + } + } + return FeedResult { .progress = Progress::NeedMore, .consumed = consumed }; +} + +HttpResult HeadParser::endLine() +{ + auto const line = std::move(_line); + _line.clear(); + if (_state == State::StartLine) + { + if (line.empty()) + { + if (rulesFor(_role).leadingEmptyLines == LeadingEmptyLines::Skip) + return {}; + return std::unexpected( + detail::refusal(HttpErrorCode::ProtocolError, "an empty line before the start line")); + } + _state = State::Fields; + return startLine(line); + } + if (line.empty()) + return finish(); + return fieldLine(line); +} + +HttpResult HeadParser::startLine(std::string_view line) +{ + if (_role == MessageRole::Request) + { + // request-line = method SP request-target SP HTTP-version, one SP each. + auto const first = line.find(' '); + auto const second = first == std::string_view::npos ? first : line.find(' ', first + 1); + if (second == std::string_view::npos || first == 0 || second == first + 1 + || second + 1 == line.size()) + return std::unexpected(detail::refusal(HttpErrorCode::ProtocolError, "a malformed request line")); + auto method = Method::parse(line.substr(0, first)); + if (!method) + return std::unexpected(std::move(method.error())); + auto target = RequestTarget::parse(line.substr(first + 1, second - first - 1)); + if (!target) + return std::unexpected(std::move(target.error())); + auto const version = parseVersion(line.substr(second + 1)); + if (!version) + return std::unexpected(unsupportedVersion()); + if (auto formed = checkTargetForm(method->text(), target->form()); !formed) + return formed; + _request.method = std::move(*method); + _request.target = std::move(*target); + _request.version = *version; + return {}; + } + + // status-line = HTTP-version SP 3DIGIT SP [ reason-phrase ]; the SP after the code may be absent. + auto const space = line.find(' '); + auto const version = parseVersion(line.substr(0, space)); + if (!version) + return std::unexpected(unsupportedVersion()); + auto const rest = space == std::string_view::npos ? std::string_view {} : line.substr(space + 1); + auto const digits = rest.substr(0, 3); + if (digits.size() != 3 || !detail::allIn(digits, detail::CharClass::Digit) || digits.front() < '1' + || digits.front() > '5' || (rest.size() > 3 && rest[3] != ' ')) + return std::unexpected(detail::refusal(HttpErrorCode::ProtocolError, "a malformed status line")); + auto reason = ReasonPhrase::parse(rest.size() > 3 ? rest.substr(4) : std::string_view {}); + if (!reason) + return std::unexpected(std::move(reason.error())); + _response.version = *version; + _response.status = static_cast(detail::parseDecimal(digits).value_or(0)); + _response.reason = std::move(*reason); + return {}; +} + +HttpResult HeadParser::fieldLine(std::string_view line) +{ + auto& fields = _role == MessageRole::Request ? _request.fields : _response.fields; + auto const& rules = rulesFor(_role); + return takeFieldLine(line, + rules, + FieldSection { .maxFields = _limits.maxFields, .tooMany = rules.headSection }, + _pending, + fields); +} + +HttpResult HeadParser::finish() +{ + auto& fields = _role == MessageRole::Request ? _request.fields : _response.fields; + if (auto flushed = flushField( + _pending, + fields, + FieldSection { .maxFields = _limits.maxFields, .tooMany = rulesFor(_role).headSection }); + !flushed) + return flushed; + if (_role == MessageRole::Request) + { + auto const hosts = fields.get("Host"); + if (hosts.size() > 1) + return std::unexpected( + detail::refusal(HttpErrorCode::ProtocolError, "more than one Host field", "Host")); + if (hosts.empty() && _request.version == HttpVersion::Http11) + return std::unexpected( + detail::refusal(HttpErrorCode::ProtocolError, "an HTTP/1.1 request without Host")); + if (!hosts.empty() && !isHostValue(hosts.front())) + return std::unexpected( + detail::refusal(HttpErrorCode::ProtocolError, "an invalid Host field", "Host")); + } + _state = State::Complete; + return {}; +} + +HttpError HeadParser::fail(HttpError error) +{ + _state = State::Failed; + _error = error; + return error; +} + +RequestHead HeadParser::takeRequest() +{ + Require(_role == MessageRole::Request && _state == State::Complete); + return std::move(_request); +} + +ResponseHead HeadParser::takeResponse() +{ + Require(_role == MessageRole::Response && _state == State::Complete); + return std::move(_response); +} + +// ------------------------------------------------------------------------------------------------- +// ChunkedDecoder + +ChunkedDecoder::ChunkedDecoder(MessageRole role, HttpLimits limits): _role { role }, _limits { limits } +{ + Require(_limits.maxReadChunk > 0); +} + +HttpResult ChunkedDecoder::feed(std::string_view bytes) +{ + if (_state == State::Failed) + return std::unexpected(*_error); + auto consumed = std::size_t { 0 }; + while (consumed < bytes.size() && _state != State::Done) + { + if (_state == State::Data) + { + auto const take = static_cast( + std::min({ _remaining, bytes.size() - consumed, _limits.maxReadChunk })); + auto const data = bytes.substr(consumed, take); + consumed += take; + _remaining -= take; + if (_remaining == 0) + _state = State::DataCr; + return ChunkStep { .consumed = consumed, .data = data, .progress = Progress::NeedMore }; + } + if (auto stepped = step(bytes[consumed]); !stepped) + return std::unexpected(fail(std::move(stepped.error()))); + ++consumed; + } + return ChunkStep { .consumed = consumed, + .data = {}, + .progress = _state == State::Done ? Progress::Complete : Progress::NeedMore }; +} + +HttpResult ChunkedDecoder::step(char octet) +{ + auto const& rules = rulesFor(_role); + auto const& transition = + ChunkTable.at(static_cast(_state)).at(static_cast(chunkClassOf(octet))); + auto const inTrailers = _state == State::TrailerLine || _state == State::TrailerLf; + if (inTrailers && ++_trailerBytes > _limits.maxTrailerBytes) + return std::unexpected(detail::refusal(rules.trailerSection, + "the trailers are past maxTrailerBytes", + std::nullopt, + std::uint64_t { _trailerBytes })); + auto const inChunkLine = _state == State::Size || _state == State::SizeSpace || _state == State::Extension + || _state == State::SizeLf; + if (inChunkLine && ++_lineBytes > _limits.maxChunkLineBytes) + return std::unexpected( + detail::refusal(HttpErrorCode::ProtocolError, "a chunk line is past maxChunkLineBytes")); + + switch (transition.action) + { + case ChunkAction::Refuse: + return std::unexpected( + detail::refusal(HttpErrorCode::ProtocolError, std::string { transition.why })); + case ChunkAction::Line: + case ChunkAction::Expect: break; + case ChunkAction::Digit: + if (++_sizeDigits > MaxChunkSizeDigits) + return std::unexpected(detail::refusal(HttpErrorCode::ProtocolError, + "a chunk size has more than 16 hex digits")); + _size = (_size << 4U) | hexValue(octet); + break; + case ChunkAction::EndSize: + if (_sizeDigits == 0) + return std::unexpected( + detail::refusal(HttpErrorCode::ProtocolError, "a chunk size has no digits")); + break; + case ChunkAction::EndLine: { + auto const limit = _limits.maxBodyBytes.value_or(std::numeric_limits::max()); + if (_size > limit - std::min(limit, _bodyBytes)) + return std::unexpected( + detail::refusal(rules.bodySize, + "the body is past maxBodyBytes", + std::nullopt, + _size > std::numeric_limits::max() - _bodyBytes + ? std::numeric_limits::max() + : _bodyBytes + _size)); + _bodyBytes += _size; + _remaining = _size; + _state = _size == 0 ? State::TrailerLine : State::Data; + _size = 0; + _sizeDigits = 0; + _lineBytes = 0; + return {}; + } + case ChunkAction::TrailerByte: + if (_line.size() >= _limits.maxFieldBytes) + return std::unexpected(detail::refusal(rules.trailerTooLong, + "a trailer line is past maxFieldBytes", + nameOf(_line), + std::uint64_t { _line.size() + 1 })); + _line += octet; + break; + case ChunkAction::EndTrailer: _state = transition.next; return endTrailerLine(); + } + _state = transition.next; + return {}; +} + +HttpResult ChunkedDecoder::endTrailerLine() +{ + auto const& rules = rulesFor(_role); + auto const section = FieldSection { .maxFields = _limits.maxFields, .tooMany = rules.trailerSection }; + auto const line = std::move(_line); + _line.clear(); + if (line.empty()) + { + if (auto flushed = flushField(_pending, _trailers, section); !flushed) + return flushed; + _state = State::Done; + return {}; + } + return takeFieldLine(line, rules, section, _pending, _trailers); +} + +HttpError ChunkedDecoder::fail(HttpError error) +{ + _state = State::Failed; + _error = error; + return error; +} + +Fields ChunkedDecoder::takeTrailers() +{ + return std::move(_trailers); +} + +std::string chunkHeader(std::size_t size) +{ + Require(size > 0); + return std::format("{:x}\r\n", size); +} + +std::string lastChunk(Fields const& trailers) +{ + auto result = std::string { "0\r\n" }; + for (auto const& field: trailers.entries()) + result += field.name + ": " + field.value + "\r\n"; + result += "\r\n"; + return result; +} + +} // namespace core::http diff --git a/src/core/http/Framing.hpp b/src/core/http/Framing.hpp new file mode 100644 index 00000000..a5a53d28 --- /dev/null +++ b/src/core/http/Framing.hpp @@ -0,0 +1,271 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// How an HTTP/1.1 message is delimited on the wire (RFC 9112): the limits every parser is bound +/// by, the body-framing rules of section 6.3, the incremental head parser, and the chunked codec of +/// section 7. Nothing here touches a socket; every input is bytes the caller already holds. + +#include +#include + +#include +#include +#include +#include +#include + +namespace core::http +{ + +/// The bounds a peer's message is held to, fixed when a parser or connection is constructed. +/// +/// A peer is untrusted, so nothing it sends makes the host hold more than these: every parser +/// refuses past them instead of buffering on. +struct HttpLimits +{ + /// The start line and the fields, line endings included. + std::size_t maxHeadBytes = std::size_t { 64 } * 1024; + /// Any one line of a head or a trailer section, the start line included. + std::size_t maxFieldBytes = std::size_t { 16 } * 1024; + /// The most field lines in a head, and the most in a trailer section; each is a host object. + std::size_t maxFields = 100; + /// A chunked body's trailer section. + std::size_t maxTrailerBytes = std::size_t { 16 } * 1024; + /// A chunk's size line, its extensions included. + std::size_t maxChunkLineBytes = 1024; + /// The most body bytes handed out at once. + std::size_t maxReadChunk = std::size_t { 64 } * 1024; + /// The largest body a chunked decoder accepts; empty for no limit. + std::optional maxBodyBytes; +}; + +/// Which kind of message a parser reads, which selects the error codes it reports and the rules +/// that differ between the two (obs-fold, framing). +enum class MessageRole : std::uint8_t +{ + Request, ///< A request, as a server reads it. + Response, ///< A response, as a client reads it. +}; + +/// How a message body is delimited. +enum class BodyFraming : std::uint8_t +{ + None, ///< There is no body. + Length, ///< @c Framing::length bytes follow the head. + Chunked, ///< The chunked coding (@c ChunkedDecoder). + UntilClose, ///< The body ends when the connection does; a response only. +}; + +/// Whether the connection carries another message after this one. +enum class Persistence : std::uint8_t +{ + KeepAlive, ///< Another message may follow. + Close, ///< The connection closes after this message. +}; + +/// A message's body framing and whether its connection persists. +struct Framing +{ + BodyFraming kind = BodyFraming::None; ///< How the body is delimited. + std::uint64_t length = 0; ///< The body's length, for @c BodyFraming::Length. + Persistence persistence = Persistence::KeepAlive; ///< Whether the connection persists. +}; + +/// The framing of a request with @p fields, by RFC 9112 section 6.3. +/// +/// Refuses (@c HttpErrorCode::ProtocolError) what that section and section 6.1 call faulty, and what +/// a smuggler sends: Transfer-Encoding together with Content-Length, Transfer-Encoding in HTTP/1.0, +/// chunked twice or not the final coding, a malformed coding list (an unterminated quote included), +/// and a Content-Length that is not one decimal value (a list of identical values is that value). +/// A request's Transfer-Encoding must be exactly `chunked`: any other coding or a parameter is +/// refused too, as a coding this layer cannot decode (a server answers 501, section 6.1), so no +/// coded body reaches a caller that believes it plain. Every refusal is fatal to the connection: the +/// caller answers it if it can, and closes. +/// @param version The request's version. +/// @param fields The request's fields. +/// @return The framing, or the refusal. +[[nodiscard]] CORE_HTTP_API HttpResult requestFraming(HttpVersion version, Fields const& fields); + +/// The framing of a response to a @p requestMethod request, by RFC 9112 section 6.3. +/// +/// A response to HEAD, a 1xx, 204 or 304 has no body whatever its fields say; a 2xx to CONNECT +/// has none either and closes, since the connection is a tunnel from then on. Transfer-Encoding +/// whose final coding is chunked frames as chunked, and closes if Content-Length came with it; one +/// whose final coding is not chunked reads until close; without either a response reads until +/// close. A transfer coding before the final chunked is not decoded; it stays in the body. The +/// refusals are @c requestFraming's but the two that hold a request to plain chunked and the one +/// for Transfer-Encoding with Content-Length, which a response is framed through. +/// @param requestMethod The method of the request this answers. +/// @param version The response's version. +/// @param status The response's status code. +/// @param fields The response's fields. +/// @return The framing, or the refusal. +[[nodiscard]] CORE_HTTP_API HttpResult responseFraming(std::string_view requestMethod, + HttpVersion version, + std::uint16_t status, + Fields const& fields); + +/// Whether @p name, compared without regard to case, is a field the connection writes itself: +/// Transfer-Encoding, Content-Length, Connection, Keep-Alive, TE or Upgrade (D7). A @c bool because +/// the name asks the question. +/// @param name A field name. +/// @return True for a framing field. +[[nodiscard]] CORE_HTTP_API bool isFramingField(std::string_view name) noexcept; + +/// Whether a parser has reached the end of what it parses. +enum class Progress : std::uint8_t +{ + NeedMore, ///< More bytes are needed. + Complete, ///< The head, or the body with its trailers, is complete. +}; + +/// What one @c HeadParser::feed did. +struct FeedResult +{ + Progress progress; ///< Whether the head is complete. + std::size_t consumed; ///< How many of the bytes fed belong to the head; the rest are the body's. +}; + +/// Parses one message head, incrementally and within @c HttpLimits. +/// +/// Fed the bytes as they arrive, it holds no more than one line of them, refuses the moment a +/// limit is passed, and never recurses. It refuses what RFC 9112 says a recipient must not accept: +/// a bare LF or a bare CR as a line ending, whitespace before a field's colon or before the first +/// field, an invalid field value, and obs-fold in a request (a response's obs-fold is replaced by +/// SP, as section 5.2 asks of a user agent). A request is also refused for two Host fields, an +/// invalid Host, or none in HTTP/1.1 (section 3.2). Empty lines before a request line are skipped. +/// Once it has refused, it refuses every later feed the same way. +class CORE_HTTP_API HeadParser +{ + public: + /// A parser for one head of @p role. + /// @param role What is parsed: a request or a response. + /// @param limits The bounds the head is held to. + HeadParser(MessageRole role, HttpLimits limits); + + /// Parses as much of @p bytes as belongs to the head. + /// @param bytes The next bytes of the message. + /// @return How many bytes were consumed and whether the head is complete, or the refusal. A + /// complete parser consumes nothing more. + [[nodiscard]] HttpResult feed(std::string_view bytes); + + /// The parsed request head. Requires a complete request parser; moves the head out. + [[nodiscard]] RequestHead takeRequest(); + + /// The parsed response head. Requires a complete response parser; moves the head out. + [[nodiscard]] ResponseHead takeResponse(); + + private: + /// Where the parser is. + enum class State : std::uint8_t + { + StartLine, ///< Before the start line ends. + Fields, ///< In the fields. + Complete, ///< After the empty line. + Failed, ///< After a refusal. + }; + + /// Where the parser is within a line. + enum class LineState : std::uint8_t + { + Text, ///< In the line's text. + Cr, ///< After its CR, waiting for the LF. + }; + + [[nodiscard]] HttpResult endLine(); + [[nodiscard]] HttpResult startLine(std::string_view line); + [[nodiscard]] HttpResult fieldLine(std::string_view line); + [[nodiscard]] HttpResult finish(); + [[nodiscard]] HttpError fail(HttpError error); + + MessageRole _role; + HttpLimits _limits; + State _state = State::StartLine; + LineState _lineState = LineState::Text; + std::size_t _headBytes = 0; + std::string _line; + std::optional _pending; + std::optional _error; + RequestHead _request; + ResponseHead _response; +}; + +/// What one @c ChunkedDecoder::feed did. +struct ChunkStep +{ + std::size_t consumed; ///< How many of the bytes fed were used. + std::string_view data; ///< Body bytes among them, a view of the bytes fed; may be empty. + Progress progress; ///< @c Progress::Complete once the trailers have ended. +}; + +/// Decodes a chunked body (RFC 9112 section 7.1), incrementally and within @c HttpLimits. +/// +/// A table of transitions, indexed by state and character class, drives every byte outside chunk +/// data; data is handed out as views of the bytes fed, at most @c HttpLimits::maxReadChunk at a +/// time. A chunk size has at most 16 hex digits, a chunk line at most @c maxChunkLineBytes, every +/// line ends in CRLF, and the trailers are field lines held to @c maxFieldBytes each and +/// @c maxTrailerBytes together (codes by role). Bytes after the final CRLF are not consumed. +class CORE_HTTP_API ChunkedDecoder +{ + public: + /// A decoder for one body of @p role. + /// @param role Whose body is decoded: a request's or a response's. + /// @param limits The bounds the body is held to. + ChunkedDecoder(MessageRole role, HttpLimits limits); + + /// Decodes from @p bytes until it has body bytes to hand out, needs more, or is complete. + /// @param bytes The next bytes of the body. + /// @return What was consumed and decoded, or the refusal, which every later feed repeats. + [[nodiscard]] HttpResult feed(std::string_view bytes); + + /// The trailer fields; complete once @c feed has reported @c Progress::Complete. Moves them out. + [[nodiscard]] Fields takeTrailers(); + + /// Where the decoder is; the rows of its transition table. + enum class State : std::uint8_t + { + Size, ///< In a chunk size. + SizeSpace, ///< In whitespace after the size, which only a ';' may follow. + Extension, ///< In a chunk's extensions. + SizeLf, ///< After a chunk line's CR. + Data, ///< In chunk data. + DataCr, ///< After chunk data, before its CR. + DataLf, ///< After chunk data's CR. + TrailerLine, ///< In a trailer line, or at the empty line that ends the body. + TrailerLf, ///< After a trailer line's CR. + Done, ///< After the final CRLF. + Failed, ///< After a refusal. + }; + + private: + [[nodiscard]] HttpResult step(char octet); + [[nodiscard]] HttpResult endTrailerLine(); + [[nodiscard]] HttpError fail(HttpError error); + + MessageRole _role; + HttpLimits _limits; + State _state = State::Size; + std::uint64_t _size = 0; + std::size_t _sizeDigits = 0; + std::size_t _lineBytes = 0; + std::uint64_t _remaining = 0; + std::uint64_t _bodyBytes = 0; + std::size_t _trailerBytes = 0; + std::string _line; + std::optional _pending; + std::optional _error; + Fields _trailers; +}; + +/// The line that opens a chunk of @p size bytes: lower-case hex and CRLF, `1a\r\n` for 26. +/// @param size The chunk's size; nonzero, since a zero-size chunk is @c lastChunk. +/// @return The chunk line. +[[nodiscard]] CORE_HTTP_API std::string chunkHeader(std::size_t size); + +/// The last chunk and the trailer section that end a chunked body: `0\r\n`, each trailer, `\r\n`. +/// @param trailers The trailer fields; validated already, as every @c Fields is. +/// @return The bytes that end the body. +[[nodiscard]] CORE_HTTP_API std::string lastChunk(Fields const& trailers); + +} // namespace core::http diff --git a/src/core/http/Framing_test.cpp b/src/core/http/Framing_test.cpp new file mode 100644 index 00000000..13ae6858 --- /dev/null +++ b/src/core/http/Framing_test.cpp @@ -0,0 +1,866 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The pure layer's framing rules: the smuggling corpus through HeadParser, requestFraming and +// ChunkedDecoder, whole and one byte at a time; the RFC 9112 section 6.3 table for responses; the +// head parser's bounds; and the chunked codec in both directions. +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using core::http::BodyFraming; +using core::http::ChunkedDecoder; +using core::http::Fields; +using core::http::HeadParser; +using core::http::HttpErrorCode; +using core::http::HttpLimits; +using core::http::HttpVersion; +using core::http::MessageRole; +using core::http::Persistence; +using core::http::Progress; +using core::http::test::smugglingCorpus; +using core::http::test::smugglingLimits; +using core::http::test::SmugglingVerdict; + +namespace +{ + +/// How many bytes each call to a parser is handed. +enum class Feeding : std::uint8_t +{ + Whole, ///< Everything that is left, in one call. + OneByte, ///< One byte per call. +}; + +/// What running a request through the pure layer came to. +struct Outcome +{ + std::optional error; ///< The refusal, if any. + std::string body; ///< The decoded body of an accepted request. + std::string detail; ///< Why, when it went wrong. +}; + +/// The next slice of @p rest that @p feeding hands a parser. +std::string_view slice(std::string_view rest, Feeding feeding) +{ + return feeding == Feeding::Whole ? rest : rest.substr(0, std::min(rest.size(), 1)); +} + +/// Decodes the chunked body at the start of @p wire into @p body, or fails. +Outcome decodeChunked(MessageRole role, HttpLimits limits, std::string_view wire, Feeding feeding) +{ + auto decoder = ChunkedDecoder { role, limits }; + auto outcome = Outcome {}; + while (true) + { + auto const step = decoder.feed(slice(wire, feeding)); + if (!step.has_value()) + return Outcome { .error = step.error().code, .body = {}, .detail = step.error().toString() }; + outcome.body += step->data; + wire.remove_prefix(step->consumed); + if (step->progress == Progress::Complete) + return outcome; + if (wire.empty()) + return Outcome { .error = HttpErrorCode::InternalError, .body = {}, .detail = "body incomplete" }; + } +} + +/// Runs @p wire, one message of @p role, through the head parser, the framing rules and the body's +/// framing; a response answers a GET. +Outcome runMessage(MessageRole role, std::string_view wire, HttpLimits limits, Feeding feeding) +{ + auto parser = HeadParser { role, limits }; + while (true) + { + auto const fed = parser.feed(slice(wire, feeding)); + if (!fed.has_value()) + return Outcome { .error = fed.error().code, .body = {}, .detail = fed.error().toString() }; + wire.remove_prefix(fed->consumed); + if (fed->progress == Progress::Complete) + break; + if (wire.empty()) + return Outcome { .error = HttpErrorCode::InternalError, .body = {}, .detail = "head incomplete" }; + } + auto const framing = [&] { + if (role == MessageRole::Request) + { + auto const head = parser.takeRequest(); + return core::http::requestFraming(head.version, head.fields); + } + auto const head = parser.takeResponse(); + return core::http::responseFraming("GET", head.version, head.status, head.fields); + }(); + if (!framing.has_value()) + return Outcome { .error = framing.error().code, .body = {}, .detail = framing.error().toString() }; + switch (framing->kind) + { + case BodyFraming::None: return Outcome {}; + case BodyFraming::Length: + if (wire.size() < framing->length) + return Outcome { .error = HttpErrorCode::InternalError, .body = {}, .detail = "body short" }; + return Outcome { .error = std::nullopt, + .body = std::string { wire.substr(0, framing->length) }, + .detail = {} }; + case BodyFraming::Chunked: return decodeChunked(role, limits, wire, feeding); + case BodyFraming::UntilClose: + if (role == MessageRole::Response) + return Outcome { .error = std::nullopt, .body = std::string { wire }, .detail = {} }; + break; + } + return Outcome { .error = HttpErrorCode::InternalError, + .body = {}, + .detail = "a request read until close" }; +} + +/// The limits of the bounds cases: small, so a case's wire is short. +HttpLimits smallLimits(std::size_t maxFields) +{ + return HttpLimits { .maxHeadBytes = std::size_t { 64 } * 1024, + .maxFieldBytes = 1024, + .maxFields = maxFields, + .maxTrailerBytes = std::size_t { 16 } * 1024, + .maxChunkLineBytes = 64, + .maxReadChunk = 4096, + .maxBodyBytes = std::nullopt }; +} + +/// The fields of @p list, each appended or the case fails. +Fields fieldsOf(std::initializer_list> list) +{ + auto fields = Fields {}; + for (auto const& [name, value]: list) + REQUIRE(fields.append(std::string { name }, std::string { value }).has_value()); + return fields; +} + +} // namespace + +TEST_CASE("Framing.smugglingCorpus", "[http][smuggling]") +{ + auto names = std::vector {}; + for (auto const& row: smugglingCorpus()) + { + CHECK(std::ranges::find(names, row.name) == names.end()); + names.push_back(row.name); + for (auto const feeding: { Feeding::Whole, Feeding::OneByte }) + { + INFO("row " << row.name << (feeding == Feeding::Whole ? " (whole)" : " (one byte at a time)")); + auto const outcome = runMessage(row.role, row.wire, smugglingLimits(), feeding); + INFO("outcome: " << outcome.detail); + if (row.verdict == SmugglingVerdict::Refused) + { + REQUIRE(outcome.error.has_value()); + CHECK(*outcome.error == row.code); + CHECK(row.status >= 400); + } + else + { + CHECK_FALSE(outcome.error.has_value()); + CHECK(outcome.body == row.body); + CHECK(row.status == 200); + } + } + } + CHECK(names.size() >= 50); +} + +TEST_CASE("Framing.requestTable", "[http]") +{ + struct Row + { + std::string_view name; + HttpVersion version; + Fields fields; + BodyFraming kind; + std::uint64_t length; + Persistence persistence; + }; + auto const rows = std::vector { + { .name = "bodiless 1.1", + .version = HttpVersion::Http11, + .fields = {}, + .kind = BodyFraming::None, + .length = 0, + .persistence = Persistence::KeepAlive }, + { .name = "length", + .version = HttpVersion::Http11, + .fields = fieldsOf({ { "Content-Length", "5" } }), + .kind = BodyFraming::Length, + .length = 5, + .persistence = Persistence::KeepAlive }, + { .name = "largest length", + .version = HttpVersion::Http11, + .fields = fieldsOf({ { "Content-Length", "18446744073709551615" } }), + .kind = BodyFraming::Length, + .length = UINT64_MAX, + .persistence = Persistence::KeepAlive }, + { .name = "chunked", + .version = HttpVersion::Http11, + .fields = fieldsOf({ { "transfer-encoding", "Chunked" } }), + .kind = BodyFraming::Chunked, + .length = 0, + .persistence = Persistence::KeepAlive }, + { .name = "connection close", + .version = HttpVersion::Http11, + .fields = fieldsOf({ { "Connection", "Upgrade, close" } }), + .kind = BodyFraming::None, + .length = 0, + .persistence = Persistence::Close }, + { .name = "bodiless 1.0", + .version = HttpVersion::Http10, + .fields = {}, + .kind = BodyFraming::None, + .length = 0, + .persistence = Persistence::Close }, + { .name = "1.0 keep-alive", + .version = HttpVersion::Http10, + .fields = fieldsOf({ { "Connection", "Keep-Alive" }, { "Content-Length", "2" } }), + .kind = BodyFraming::Length, + .length = 2, + .persistence = Persistence::KeepAlive }, + }; + for (auto const& row: rows) + { + INFO("row " << row.name); + auto const framing = core::http::requestFraming(row.version, row.fields); + REQUIRE(framing.has_value()); + CHECK(framing->kind == row.kind); + CHECK(framing->length == row.length); + CHECK(framing->persistence == row.persistence); + } +} + +TEST_CASE("Framing.responseTable", "[http]") +{ + struct Row + { + std::string_view name; + std::string_view method; + HttpVersion version; + std::uint16_t status; + Fields fields; + BodyFraming kind; + std::uint64_t length; + Persistence persistence; + }; + auto const lengthAndChunked = fieldsOf({ { "Content-Length", "3" }, { "Transfer-Encoding", "chunked" } }); + auto const rows = std::vector { + { .name = "HEAD ignores the framing fields", + .method = "HEAD", + .version = HttpVersion::Http11, + .status = 200, + .fields = lengthAndChunked, + .kind = BodyFraming::None, + .length = 0, + .persistence = Persistence::KeepAlive }, + { .name = "100 has no body", + .method = "GET", + .version = HttpVersion::Http11, + .status = 100, + .fields = fieldsOf({ { "Content-Length", "3" } }), + .kind = BodyFraming::None, + .length = 0, + .persistence = Persistence::KeepAlive }, + { .name = "199 has no body", + .method = "GET", + .version = HttpVersion::Http11, + .status = 199, + .fields = {}, + .kind = BodyFraming::None, + .length = 0, + .persistence = Persistence::KeepAlive }, + { .name = "204 has no body", + .method = "POST", + .version = HttpVersion::Http11, + .status = 204, + .fields = fieldsOf({ { "Transfer-Encoding", "chunked" } }), + .kind = BodyFraming::None, + .length = 0, + .persistence = Persistence::KeepAlive }, + { .name = "304 has no body", + .method = "GET", + .version = HttpVersion::Http11, + .status = 304, + .fields = fieldsOf({ { "Content-Length", "10" } }), + .kind = BodyFraming::None, + .length = 0, + .persistence = Persistence::KeepAlive }, + { .name = "a 2xx to CONNECT is a tunnel", + .method = "CONNECT", + .version = HttpVersion::Http11, + .status = 200, + .fields = fieldsOf({ { "Content-Length", "10" } }), + .kind = BodyFraming::None, + .length = 0, + .persistence = Persistence::Close }, + { .name = "a 407 to CONNECT has a body", + .method = "CONNECT", + .version = HttpVersion::Http11, + .status = 407, + .fields = fieldsOf({ { "Content-Length", "4" } }), + .kind = BodyFraming::Length, + .length = 4, + .persistence = Persistence::KeepAlive }, + { .name = "a bare 1.1 response reads until close", + .method = "GET", + .version = HttpVersion::Http11, + .status = 200, + .fields = {}, + .kind = BodyFraming::UntilClose, + .length = 0, + .persistence = Persistence::Close }, + { .name = "TE and CL frame as chunked and close", + .method = "GET", + .version = HttpVersion::Http11, + .status = 200, + .fields = lengthAndChunked, + .kind = BodyFraming::Chunked, + .length = 0, + .persistence = Persistence::Close }, + { .name = "chunked", + .method = "GET", + .version = HttpVersion::Http11, + .status = 200, + .fields = fieldsOf({ { "Transfer-Encoding", "gzip, chunked" } }), + .kind = BodyFraming::Chunked, + .length = 0, + .persistence = Persistence::KeepAlive }, + { .name = "a quoted comma does not split the coding list", + .method = "GET", + .version = HttpVersion::Http11, + .status = 200, + .fields = fieldsOf({ { "Transfer-Encoding", "gzip;a=\"x, chunked\"" } }), + .kind = BodyFraming::UntilClose, + .length = 0, + .persistence = Persistence::Close }, + { .name = "a response may carry other codings before chunked", + .method = "GET", + .version = HttpVersion::Http11, + .status = 200, + .fields = fieldsOf({ { "Transfer-Encoding", "gzip;q=1, chunked" } }), + .kind = BodyFraming::Chunked, + .length = 0, + .persistence = Persistence::KeepAlive }, + { .name = "chunked, gzip reads until close", + .method = "GET", + .version = HttpVersion::Http11, + .status = 200, + .fields = fieldsOf({ { "Transfer-Encoding", "chunked, gzip" } }), + .kind = BodyFraming::UntilClose, + .length = 0, + .persistence = Persistence::Close }, + { .name = "length", + .method = "GET", + .version = HttpVersion::Http11, + .status = 200, + .fields = fieldsOf({ { "Content-Length", "7" } }), + .kind = BodyFraming::Length, + .length = 7, + .persistence = Persistence::KeepAlive }, + { .name = "1.0 without keep-alive closes", + .method = "GET", + .version = HttpVersion::Http10, + .status = 200, + .fields = fieldsOf({ { "Content-Length", "7" } }), + .kind = BodyFraming::Length, + .length = 7, + .persistence = Persistence::Close }, + { .name = "1.0 with keep-alive persists", + .method = "GET", + .version = HttpVersion::Http10, + .status = 200, + .fields = fieldsOf({ { "Content-Length", "7" }, { "Connection", "keep-alive" } }), + .kind = BodyFraming::Length, + .length = 7, + .persistence = Persistence::KeepAlive }, + { .name = "connection close", + .method = "GET", + .version = HttpVersion::Http11, + .status = 200, + .fields = fieldsOf({ { "Content-Length", "7" }, { "Connection", "CLOSE" } }), + .kind = BodyFraming::Length, + .length = 7, + .persistence = Persistence::Close }, + }; + for (auto const& row: rows) + { + INFO("row " << row.name); + auto const framing = core::http::responseFraming(row.method, row.version, row.status, row.fields); + REQUIRE(framing.has_value()); + CHECK(framing->kind == row.kind); + CHECK(framing->length == row.length); + CHECK(framing->persistence == row.persistence); + } +} + +TEST_CASE("Framing.responseTableRefusals", "[http]") +{ + struct Row + { + std::string_view name; + HttpVersion version; + Fields fields; + }; + auto const rows = std::vector { + { .name = "two lengths", + .version = HttpVersion::Http11, + .fields = fieldsOf({ { "Content-Length", "3, 4" } }) }, + { .name = "a signed length", + .version = HttpVersion::Http11, + .fields = fieldsOf({ { "Content-Length", "+3" } }) }, + { .name = "chunked twice", + .version = HttpVersion::Http11, + .fields = fieldsOf({ { "Transfer-Encoding", "chunked, chunked" } }) }, + { .name = "TE on 1.0", + .version = HttpVersion::Http10, + .fields = fieldsOf({ { "Transfer-Encoding", "chunked" } }) }, + { .name = "chunked with a parameter", + .version = HttpVersion::Http11, + .fields = fieldsOf({ { "Transfer-Encoding", "chunked;q=1" } }) }, + { .name = "an escaped quote keeps the quoted-string open", + .version = HttpVersion::Http11, + .fields = fieldsOf({ { "Transfer-Encoding", R"(gzip;a="x\", chunked)" } }) }, + { .name = "an unterminated quote", + .version = HttpVersion::Http11, + .fields = fieldsOf({ { "Transfer-Encoding", "gzip;a=\"x, chunked" } }) }, + { .name = "a coding that is not a token", + .version = HttpVersion::Http11, + .fields = fieldsOf({ { "Transfer-Encoding", "gz(ip), chunked" } }) }, + }; + for (auto const& row: rows) + { + INFO("row " << row.name); + auto const framing = core::http::responseFraming("GET", row.version, 200, row.fields); + REQUIRE_FALSE(framing.has_value()); + CHECK(framing.error().code == HttpErrorCode::ProtocolError); + } +} + +TEST_CASE("Framing.framingFields", "[http]") +{ + for (auto const name: + { "Transfer-Encoding", "content-length", "CONNECTION", "Keep-Alive", "te", "Upgrade" }) + { + INFO("field " << name); + CHECK(core::http::isFramingField(name)); + } + for (auto const name: { "Host", "Trailer", "Content-Type", "Transfer-Encodings", "t", "" }) + { + INFO("field " << name); + CHECK_FALSE(core::http::isFramingField(name)); + } +} + +TEST_CASE("HeadParser.response", "[http]") +{ + auto const wire = + std::string_view { "HTTP/1.1 404 Not Found\r\nContent-Length: 3\r\nX-A: b c \r\n\r\nabcNEXT" }; + for (auto const feeding: { Feeding::Whole, Feeding::OneByte }) + { + auto parser = HeadParser { MessageRole::Response, HttpLimits {} }; + auto rest = wire; + auto progress = Progress::NeedMore; + while (progress == Progress::NeedMore) + { + auto const fed = parser.feed(slice(rest, feeding)); + REQUIRE(fed.has_value()); + rest.remove_prefix(fed->consumed); + progress = fed->progress; + } + CHECK(rest == "abcNEXT"); + auto const head = parser.takeResponse(); + CHECK(head.status == 404); + CHECK(head.reason.text() == "Not Found"); + CHECK(head.version == HttpVersion::Http11); + REQUIRE(head.fields.entries().size() == 2); + CHECK(head.fields.get("x-a") == std::vector { "b c" }); + + // A complete parser consumes nothing more. + auto const again = parser.feed("more"); + REQUIRE(again.has_value()); + CHECK(again->consumed == 0); + CHECK(again->progress == Progress::Complete); + } +} + +TEST_CASE("HeadParser.responseUnfoldsObsFold", "[http]") +{ + // RFC 9112 5.2: a user agent replaces an obs-fold with SP; a server refuses it (the corpus). + auto parser = HeadParser { MessageRole::Response, HttpLimits {} }; + auto const fed = parser.feed("HTTP/1.1 200 OK\r\nX-A: a\r\n \t b\r\nX-B: c\r\n\r\n"); + REQUIRE(fed.has_value()); + REQUIRE(fed->progress == Progress::Complete); + auto const head = parser.takeResponse(); + CHECK(head.fields.get("X-A") == std::vector { "a b" }); + CHECK(head.fields.get("X-B") == std::vector { "c" }); +} + +TEST_CASE("HeadParser.startLines", "[http]") +{ + struct Row + { + std::string_view wire; + std::optional error; + }; + auto const responses = std::vector { + { .wire = "HTTP/1.1 200\r\n\r\n", .error = std::nullopt }, + { .wire = "HTTP/1.2 200 OK\r\n\r\n", .error = std::nullopt }, + { .wire = "HTTP/1.1 99 Low\r\n\r\n", .error = HttpErrorCode::ProtocolError }, + { .wire = "HTTP/1.1 099 Low\r\n\r\n", .error = HttpErrorCode::ProtocolError }, + { .wire = "HTTP/1.1 600 High\r\n\r\n", .error = HttpErrorCode::ProtocolError }, + { .wire = "HTTP/1.1 2000 Long\r\n\r\n", .error = HttpErrorCode::ProtocolError }, + { .wire = "HTTP/1.1 200 OK\r\n\r\n", .error = HttpErrorCode::ProtocolError }, + { .wire = "HTTP/2 200 OK\r\n\r\n", .error = HttpErrorCode::ProtocolError }, + { .wire = "http/1.1 200 OK\r\n\r\n", .error = HttpErrorCode::ProtocolError }, + { .wire = "HTTP/1.1 200 O\x01K\r\n\r\n", .error = HttpErrorCode::ProtocolError }, + }; + for (auto const& row: responses) + { + INFO("response " << row.wire); + auto parser = HeadParser { MessageRole::Response, HttpLimits {} }; + auto const fed = parser.feed(row.wire); + if (row.error) + { + REQUIRE_FALSE(fed.has_value()); + CHECK(fed.error().code == *row.error); + } + else + { + REQUIRE(fed.has_value()); + CHECK(fed->progress == Progress::Complete); + CHECK(parser.takeResponse().version == HttpVersion::Http11); + } + } + + auto const requests = std::vector { + { .wire = "\r\n\r\nGET / HTTP/1.1\r\nHost: a\r\n\r\n", .error = std::nullopt }, + { .wire = "G(T / HTTP/1.1\r\nHost: a\r\n\r\n", .error = HttpErrorCode::RequestMethodInvalid }, + { .wire = "GET /a#b HTTP/1.1\r\nHost: a\r\n\r\n", .error = HttpErrorCode::RequestUriInvalid }, + { .wire = "GET / HTTP/1.1\r\nHost: a\r\n\r\n", .error = HttpErrorCode::ProtocolError }, + { .wire = "GET / HTTP/1.1 \r\nHost: a\r\n\r\n", .error = HttpErrorCode::ProtocolError }, + { .wire = "GET /\r\nHost: a\r\n\r\n", .error = HttpErrorCode::ProtocolError }, + { .wire = "GET / HTTP/1.1\r\n: a\r\n\r\n", .error = HttpErrorCode::ProtocolError }, + { .wire = "GET / HTTP/1.1\r\nHost a\r\n\r\n", .error = HttpErrorCode::ProtocolError }, + }; + for (auto const& row: requests) + { + INFO("request " << row.wire); + auto parser = HeadParser { MessageRole::Request, HttpLimits {} }; + auto const fed = parser.feed(row.wire); + if (row.error) + { + REQUIRE_FALSE(fed.has_value()); + CHECK(fed.error().code == *row.error); + } + else + { + REQUIRE(fed.has_value()); + CHECK(fed->progress == Progress::Complete); + auto const head = parser.takeRequest(); + CHECK(head.method.text() == "GET"); + CHECK(head.target.text() == "/"); + } + } +} + +TEST_CASE("HeadParser.boundsWhatItHolds", "[http]") +{ + // A peer that never ends a line is refused once the line passes maxFieldBytes, not after + // whatever it chose to send: the parser holds at most the limit. + auto const limits = HttpLimits { .maxHeadBytes = std::size_t { 64 } * 1024, + .maxFieldBytes = 1024, + .maxFields = 100, + .maxTrailerBytes = 1024, + .maxChunkLineBytes = 64, + .maxReadChunk = 4096, + .maxBodyBytes = std::nullopt }; + for (auto const role: { MessageRole::Request, MessageRole::Response }) + { + auto parser = HeadParser { role, limits }; + auto const start = role == MessageRole::Request + ? std::string_view { "GET / HTTP/1.1\r\nX-Endless: " } + : std::string_view { "HTTP/1.1 200 OK\r\nX-Endless: " }; + REQUIRE(parser.feed(start).has_value()); + auto const block = std::string(256, 'x'); + auto fedBytes = start.size(); + auto refusal = std::optional {}; + for ([[maybe_unused]] auto const round: std::views::iota(0, 1 << 12)) + { + auto const fed = parser.feed(block); + if (!fed.has_value()) + { + refusal = fed.error(); + break; + } + CHECK(fed->consumed == block.size()); + fedBytes += fed->consumed; + } + REQUIRE(refusal.has_value()); + CHECK(refusal->code + == (role == MessageRole::Request ? HttpErrorCode::RequestHeaderSize + : HttpErrorCode::ResponseHeaderSize)); + CHECK(refusal->fieldName == std::optional { "X-Endless" }); + CHECK(fedBytes <= limits.maxFieldBytes + start.size()); + + // A refused parser stays refused. + auto const after = parser.feed("\r\n\r\n"); + REQUIRE_FALSE(after.has_value()); + CHECK(after.error().code == refusal->code); + } +} + +TEST_CASE("HeadParser.headSectionSize", "[http]") +{ + auto const limits = HttpLimits { .maxHeadBytes = 200, + .maxFieldBytes = 100, + .maxFields = 100, + .maxTrailerBytes = 100, + .maxChunkLineBytes = 64, + .maxReadChunk = 4096, + .maxBodyBytes = std::nullopt }; + for (auto const role: { MessageRole::Request, MessageRole::Response }) + { + auto parser = HeadParser { role, limits }; + auto wire = std::string { role == MessageRole::Request ? "GET / HTTP/1.1\r\nHost: a\r\n" + : "HTTP/1.1 200 OK\r\n" }; + for (auto const index: std::views::iota(0, 10)) + wire += "X-" + std::to_string(index) + ": " + std::string(40, 'v') + "\r\n"; + wire += "\r\n"; + auto const fed = parser.feed(wire); + REQUIRE_FALSE(fed.has_value()); + CHECK(fed.error().code + == (role == MessageRole::Request ? HttpErrorCode::RequestHeaderSectionSize + : HttpErrorCode::ResponseHeaderSectionSize)); + REQUIRE(fed.error().size.has_value()); + CHECK(*fed.error().size > limits.maxHeadBytes); + } +} + +TEST_CASE("ChunkedDecoder.oneByteFeedsYieldDataAndTrailers", "[http]") +{ + auto const wire = std::string_view { + "5;a=b\r\nhello\r\n1A\r\nabcdefghijklmnopqrstuvwxyz\r\n0\r\nX-T: 1\r\nX-U: two\r\n\r\nNEXT" + }; + for (auto const feeding: { Feeding::Whole, Feeding::OneByte }) + { + auto decoder = ChunkedDecoder { MessageRole::Response, HttpLimits {} }; + auto rest = wire; + auto body = std::string {}; + auto progress = Progress::NeedMore; + while (progress == Progress::NeedMore) + { + REQUIRE_FALSE(rest.empty()); + auto const step = decoder.feed(slice(rest, feeding)); + REQUIRE(step.has_value()); + CHECK(step->data.size() <= step->consumed); + body += step->data; + rest.remove_prefix(step->consumed); + progress = step->progress; + } + CHECK(body == "helloabcdefghijklmnopqrstuvwxyz"); + CHECK(rest == "NEXT"); + auto const trailers = decoder.takeTrailers(); + CHECK(trailers.get("x-t") == std::vector { "1" }); + CHECK(trailers.get("X-U") == std::vector { "two" }); + + auto const again = decoder.feed(rest); + REQUIRE(again.has_value()); + CHECK(again->consumed == 0); + CHECK(again->progress == Progress::Complete); + } +} + +TEST_CASE("ChunkedDecoder.dataIsClampedToMaxReadChunk", "[http]") +{ + auto limits = HttpLimits {}; + limits.maxReadChunk = 4; + auto decoder = ChunkedDecoder { MessageRole::Request, limits }; + auto rest = std::string_view { "a\r\n0123456789\r\n0\r\n\r\n" }; + auto pieces = std::vector {}; + auto progress = Progress::NeedMore; + while (progress == Progress::NeedMore) + { + auto const step = decoder.feed(rest); + REQUIRE(step.has_value()); + CHECK(step->data.size() <= limits.maxReadChunk); + if (!step->data.empty()) + pieces.emplace_back(step->data); + rest.remove_prefix(step->consumed); + progress = step->progress; + } + CHECK(pieces == std::vector { "0123", "4567", "89" }); +} + +TEST_CASE("ChunkedDecoder.limitsPerRole", "[http]") +{ + auto const limits = HttpLimits { .maxHeadBytes = 1024, + .maxFieldBytes = 32, + .maxFields = 100, + .maxTrailerBytes = 48, + .maxChunkLineBytes = 16, + .maxReadChunk = 4096, + .maxBodyBytes = 8 }; + struct Row + { + std::string_view name; + std::string_view wire; + HttpErrorCode request; + HttpErrorCode response; + }; + auto const rows = std::vector { + { .name = "trailer section", + .wire = "0\r\nX-A: 0123456789\r\nX-B: 0123456789\r\nX-C: 0123456789\r\n\r\n", + .request = HttpErrorCode::RequestTrailerSectionSize, + .response = HttpErrorCode::ResponseTrailerSectionSize }, + { .name = "trailer field", + .wire = "0\r\nX-Long: 01234567890123456789012345678901\r\n\r\n", + .request = HttpErrorCode::RequestTrailerSize, + .response = HttpErrorCode::ResponseTrailerSize }, + { .name = "body", + .wire = "5\r\nhello\r\n5\r\nworld\r\n0\r\n\r\n", + .request = HttpErrorCode::RequestBodySize, + .response = HttpErrorCode::ResponseBodySize }, + { .name = "chunk line", + .wire = "5;name=0123456789\r\nhello\r\n0\r\n\r\n", + .request = HttpErrorCode::ProtocolError, + .response = HttpErrorCode::ProtocolError }, + { .name = "whitespace before the first trailer field", + .wire = "0\r\n X-A: 1\r\n\r\n", + .request = HttpErrorCode::ProtocolError, + .response = HttpErrorCode::ProtocolError }, + }; + for (auto const& row: rows) + { + for (auto const role: { MessageRole::Request, MessageRole::Response }) + { + for (auto const feeding: { Feeding::Whole, Feeding::OneByte }) + { + INFO("row " << row.name << (role == MessageRole::Request ? " request" : " response")); + auto const outcome = decodeChunked(role, limits, row.wire, feeding); + INFO(outcome.detail); + REQUIRE(outcome.error.has_value()); + CHECK(*outcome.error == (role == MessageRole::Request ? row.request : row.response)); + } + } + } + + // The trailer-field row names its field and its size. + auto decoder = ChunkedDecoder { MessageRole::Response, limits }; + auto const step = decoder.feed(rows[1].wire); + REQUIRE_FALSE(step.has_value()); + CHECK(step.error().fieldName == std::optional { "X-Long" }); + REQUIRE(step.error().size.has_value()); + CHECK(*step.error().size > limits.maxFieldBytes); +} + +TEST_CASE("HeadParser.maxFields", "[http]") +{ + for (auto const role: { MessageRole::Request, MessageRole::Response }) + { + auto const start = std::string { role == MessageRole::Request ? "GET / HTTP/1.1\r\nHost: a\r\n" + : "HTTP/1.1 200 OK\r\n" }; + auto const fieldsUpTo = [&](int count) { + auto wire = start; + // The request's Host is one of its fields. + auto const first = role == MessageRole::Request ? 1 : 0; + for (auto const index: std::views::iota(first, count)) + wire += "X-" + std::to_string(index) + ": v\r\n"; + return wire + "\r\n"; + }; + INFO((role == MessageRole::Request ? "request" : "response")); + + auto atLimit = HeadParser { role, smallLimits(100) }; + auto const accepted = atLimit.feed(fieldsUpTo(100)); + REQUIRE(accepted.has_value()); + CHECK(accepted->progress == Progress::Complete); + + auto pastLimit = HeadParser { role, smallLimits(100) }; + auto const refused = pastLimit.feed(fieldsUpTo(101)); + REQUIRE_FALSE(refused.has_value()); + CHECK(refused.error().code + == (role == MessageRole::Request ? HttpErrorCode::RequestHeaderSectionSize + : HttpErrorCode::ResponseHeaderSectionSize)); + } +} + +TEST_CASE("ChunkedDecoder.maxFields", "[http]") +{ + auto const trailersUpTo = [](int count) { + auto wire = std::string { "0\r\n" }; + for (auto const index: std::views::iota(0, count)) + wire += "X-" + std::to_string(index) + ": v\r\n"; + return wire + "\r\n"; + }; + for (auto const role: { MessageRole::Request, MessageRole::Response }) + { + INFO((role == MessageRole::Request ? "request" : "response")); + auto const accepted = decodeChunked(role, smallLimits(10), trailersUpTo(10), Feeding::Whole); + CHECK_FALSE(accepted.error.has_value()); + auto const refused = decodeChunked(role, smallLimits(10), trailersUpTo(11), Feeding::Whole); + REQUIRE(refused.error.has_value()); + CHECK(*refused.error + == (role == MessageRole::Request ? HttpErrorCode::RequestTrailerSectionSize + : HttpErrorCode::ResponseTrailerSectionSize)); + } +} + +TEST_CASE("ChunkedDecoder.trailerObsFoldByRole", "[http]") +{ + // RFC 9112 5.2, as for a head: a user agent unfolds a response's trailers, a server refuses. + auto const wire = std::string_view { "0\r\nX-A: a\r\n \t b\r\nX-B: c\r\n\r\n" }; + auto response = ChunkedDecoder { MessageRole::Response, HttpLimits {} }; + auto const step = response.feed(wire); + REQUIRE(step.has_value()); + REQUIRE(step->progress == Progress::Complete); + auto const trailers = response.takeTrailers(); + CHECK(trailers.get("X-A") == std::vector { "a b" }); + CHECK(trailers.get("X-B") == std::vector { "c" }); + + auto request = ChunkedDecoder { MessageRole::Request, HttpLimits {} }; + auto const refused = request.feed(wire); + REQUIRE_FALSE(refused.has_value()); + CHECK(refused.error().code == HttpErrorCode::ProtocolError); +} + +TEST_CASE("ChunkedEncoder.framesWhatTheDecoderReads", "[http]") +{ + CHECK(core::http::chunkHeader(26) == "1a\r\n"); + CHECK(core::http::chunkHeader(1) == "1\r\n"); + CHECK(core::http::chunkHeader(0xffff) == "ffff\r\n"); + CHECK(core::http::lastChunk(Fields {}) == "0\r\n\r\n"); + + auto const trailers = fieldsOf({ { "X-T", "1" }, { "X-U", "a b" } }); + CHECK(core::http::lastChunk(trailers) == "0\r\nX-T: 1\r\nX-U: a b\r\n\r\n"); + + auto const payload = std::string(300, 'p'); + auto const wire = + core::http::chunkHeader(payload.size()) + payload + "\r\n" + core::http::lastChunk(trailers); + auto decoder = ChunkedDecoder { MessageRole::Request, HttpLimits {} }; + auto rest = std::string_view { wire }; + auto body = std::string {}; + auto progress = Progress::NeedMore; + while (progress == Progress::NeedMore) + { + REQUIRE_FALSE(rest.empty()); + auto const step = decoder.feed(rest); + REQUIRE(step.has_value()); + body += step->data; + rest.remove_prefix(step->consumed); + progress = step->progress; + } + CHECK(body == payload); + CHECK(rest.empty()); + CHECK(decoder.takeTrailers().get("X-U") == std::vector { "a b" }); +} diff --git a/src/core/http/Message.cpp b/src/core/http/Message.cpp new file mode 100644 index 00000000..d9dfc505 --- /dev/null +++ b/src/core/http/Message.cpp @@ -0,0 +1,152 @@ +// SPDX-License-Identifier: Apache-2.0 +#include + +#include + +#include +#include +#include +#include +#include +#include + +namespace core::http +{ + +namespace +{ + + /// Whether @p text is `scheme ":" "//" ...` with URI characters after it (an absolute URI with an + /// authority, as HTTP's are). + bool isAbsoluteUri(std::string_view text) + { + auto const colon = text.find(':'); + if (colon == std::string_view::npos || colon == 0 + || !detail::isIn(text.front(), detail::CharClass::Alpha)) + return false; + auto const scheme = text.substr(0, colon); + auto const rest = text.substr(colon + 1); + return detail::isUriText(scheme, detail::CharClass::Alpha | detail::CharClass::Digit, "+-.") + && rest.starts_with("//") + && detail::isUriText( + rest, detail::CharClass::Unreserved | detail::CharClass::SubDelim, ":@/?[]"); + } + +} // namespace + +std::string HttpError::toString() const +{ + auto result = std::string { http::toString(code) }; + if (fieldName) + result += " [field " + *fieldName + "]"; + if (size) + result += " [size " + std::to_string(*size) + "]"; + if (coding) + result += " [coding " + *coding + "]"; + if (dnsRcode) + result += " [rcode " + *dnsRcode + "]"; + if (dnsInfoCode) + result += " [info code " + std::to_string(*dnsInfoCode) + "]"; + if (tls && !tls->message.empty()) + result += " [TLS " + tls->message + "]"; + if (!detail.empty()) + result += " (" + detail + ")"; + return result; +} + +HttpResult Fields::append(std::string name, std::string value) +{ + if (!detail::isToken(name)) + return std::unexpected( + detail::refusal(HttpErrorCode::ProtocolError, "a field name is not a token", std::move(name))); + if (!detail::allIn(value, detail::CharClass::FieldValue)) + return std::unexpected( + detail::refusal(HttpErrorCode::ProtocolError, + "a field value holds a control character (CR, LF, NUL or another)", + std::move(name))); + if (detail::trimWhitespace(value).size() != value.size()) + return std::unexpected(detail::refusal(HttpErrorCode::ProtocolError, + "a field value has leading or trailing whitespace", + std::move(name))); + _entries.push_back(Field { .name = std::move(name), .value = std::move(value) }); + return {}; +} + +std::vector Fields::get(std::string_view name) const +{ + auto values = std::vector {}; + for (auto const& entry: _entries) + if (detail::equalsIgnoringCase(entry.name, name)) + values.emplace_back(entry.value); + return values; +} + +std::size_t Fields::erase(std::string_view name) +{ + return std::erase_if(_entries, + [name](Field const& entry) { return detail::equalsIgnoringCase(entry.name, name); }); +} + +Method::Method(): _text { "GET" } +{ +} + +Method::Method(std::string text): _text { std::move(text) } +{ +} + +HttpResult Method::parse(std::string_view token) +{ + if (!detail::isToken(token)) + return std::unexpected( + detail::refusal(HttpErrorCode::RequestMethodInvalid, "a method is not a token")); + return Method { std::string { token } }; +} + +RequestTarget::RequestTarget(): _text { "/" }, _form { RequestTargetForm::Origin } +{ +} + +RequestTarget::RequestTarget(std::string text, RequestTargetForm form): + _text { std::move(text) }, _form { form } +{ +} + +HttpResult RequestTarget::parse(std::string_view target) +{ + auto const form = [target]() -> std::optional { + if (target == "*") + return RequestTargetForm::Asterisk; + if (target.starts_with('/')) + { + // origin-form = absolute-path [ "?" query ]: pchar, '/' and '?'. + if (detail::isUriText( + target, detail::CharClass::Unreserved | detail::CharClass::SubDelim, ":@/?")) + return RequestTargetForm::Origin; + return std::nullopt; + } + if (isAbsoluteUri(target)) + return RequestTargetForm::Absolute; + if (detail::isAuthority(target, detail::PortRule::Required)) + return RequestTargetForm::Authority; + return std::nullopt; + }(); + if (!form) + return std::unexpected(detail::refusal(HttpErrorCode::RequestUriInvalid, + "a request target is not one of the four forms")); + return RequestTarget { std::string { target }, *form }; +} + +ReasonPhrase::ReasonPhrase(std::string text): _text { std::move(text) } +{ +} + +HttpResult ReasonPhrase::parse(std::string_view text) +{ + if (!detail::allIn(text, detail::CharClass::FieldValue)) + return std::unexpected( + detail::refusal(HttpErrorCode::ProtocolError, "a reason phrase holds a control character")); + return ReasonPhrase { std::string { text } }; +} + +} // namespace core::http diff --git a/src/core/http/Message.hpp b/src/core/http/Message.hpp new file mode 100644 index 00000000..4fa8ffd4 --- /dev/null +++ b/src/core/http/Message.hpp @@ -0,0 +1,310 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// The HTTP/1.1 message vocabulary (RFC 9110, RFC 9112): the error codes with their payload, the +/// field list, and the validating factories every method, request target and reason phrase is built +/// through, so no value that could split or smuggle a message reaches the wire. + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace core::http +{ + +/// The protocol version a message is framed by. +enum class HttpVersion : std::uint8_t +{ + Http10, ///< HTTP/1.0: no chunked coding, closes unless asked to keep alive. + Http11, ///< HTTP/1.1, and every later 1.x minor version a peer sends (RFC 9112 section 2.3). +}; + +/// Classifies an HTTP failure. +/// +/// One code for each case of the WASI 0.3 `wasi:http` `error-code`, in its order, so a consumer +/// maps them one to one; the payload a case carries is in @c HttpError. @c Last is a sentinel, the +/// number of codes, and never an error. +enum class HttpErrorCode : std::uint8_t +{ + DnsTimeout, ///< The name lookup timed out. + DnsError, ///< The name lookup failed (@c HttpError::dnsRcode, @c dnsInfoCode). + DestinationNotFound, ///< The name does not exist. + DestinationUnavailable, ///< The destination exists but cannot be reached now. + DestinationIpProhibited, ///< The destination address is not allowed. + DestinationIpUnroutable, ///< There is no route to the destination address. + ConnectionRefused, ///< The destination refused the connection. + ConnectionTerminated, ///< The connection ended before the exchange did. + ConnectionTimeout, ///< Connecting timed out. + ConnectionReadTimeout, ///< A read timed out between bytes. + ConnectionWriteTimeout, ///< A write timed out. + ConnectionLimitReached, ///< No connection could be had within the configured cap. + TlsProtocolError, ///< The TLS handshake or record layer failed. + TlsCertificateError, ///< The peer's certificate was refused. + TlsAlertReceived, ///< The peer sent a TLS alert (@c HttpError::tls). + RequestDenied, ///< The request was refused by policy. + RequestLengthRequired, ///< The request needs a length it does not carry. + RequestBodySize, ///< The request body is too large, or not its declared size (@c size). + RequestMethodInvalid, ///< The method is not a token. + RequestUriInvalid, ///< The request target is not one of the four forms. + RequestUriTooLong, ///< The request line is too long. + RequestHeaderSectionSize, ///< The request head is too large (@c size). + RequestHeaderSize, ///< A request field line is too large (@c fieldName, @c size). + RequestTrailerSectionSize, ///< The request trailer section is too large (@c size). + RequestTrailerSize, ///< A request trailer line is too large (@c fieldName, @c size). + ResponseIncomplete, ///< The response ended before its framing did. + ResponseHeaderSectionSize, ///< The response head is too large (@c size). + ResponseHeaderSize, ///< A response field line is too large (@c fieldName, @c size). + ResponseBodySize, ///< The response body is too large, or not its declared size (@c size). + ResponseTrailerSectionSize, ///< The response trailer section is too large (@c size). + ResponseTrailerSize, ///< A response trailer line is too large (@c fieldName, @c size). + ResponseTransferCoding, ///< A transfer coding cannot be decoded (@c coding). + ResponseContentCoding, ///< A content coding cannot be decoded (@c coding). + ResponseTimeout, ///< No response head arrived in time. + UpgradeFailed, ///< A protocol upgrade failed. + ProtocolError, ///< The peer, or the caller, broke the protocol's syntax or framing. + LoopDetected, ///< A redirect or proxy loop. + ConfigurationError, ///< The client or server is configured so it cannot do this. + InternalError, ///< Anything else (@c detail). + Last, ///< The number of codes; never an error. +}; + +namespace detail +{ + /// The name of each code, indexed by its value. + inline constexpr auto HttpErrorCodeNames = + std::array(HttpErrorCode::Last)> { + "DNS timeout", + "DNS error", + "destination not found", + "destination unavailable", + "destination IP prohibited", + "destination IP unroutable", + "connection refused", + "connection terminated", + "connection timeout", + "connection read timeout", + "connection write timeout", + "connection limit reached", + "TLS protocol error", + "TLS certificate error", + "TLS alert received", + "request denied", + "request length required", + "request body size", + "request method invalid", + "request URI invalid", + "request URI too long", + "request header section size", + "request header size", + "request trailer section size", + "request trailer size", + "response incomplete", + "response header section size", + "response header size", + "response body size", + "response trailer section size", + "response trailer size", + "response transfer coding", + "response content coding", + "response timeout", + "upgrade failed", + "protocol error", + "loop detected", + "configuration error", + "internal error", + }; +} // namespace detail + +/// A short, human-readable name for @p code; "unknown" for @c HttpErrorCode::Last. +[[nodiscard]] constexpr std::string_view toString(HttpErrorCode code) noexcept +{ + auto const index = static_cast(code); + return index < detail::HttpErrorCodeNames.size() ? detail::HttpErrorCodeNames.at(index) : "unknown"; +} + +/// What a refusal of a peer's message was for, where its code alone does not say which status a +/// server answers it with. +/// +/// Not part of the WIT's `error-code`, which has no case for either: both are a +/// @c HttpErrorCode::ProtocolError there. RFC 9110 gives each a status of its own, so the parsers +/// say which it was and a server's @c errorStatusTable maps the pair. +enum class RefusalReason : std::uint8_t +{ + Unclassified, ///< Nothing beyond the code; the default. + UnsupportedVersion, ///< The message's version is not HTTP/1.x (RFC 9110 section 15.6.6: 505). + UnimplementedCoding, ///< A request transfer coding this layer cannot decode (RFC 9112 6.1: 501). +}; + +/// An HTTP failure: its code and the payload the code carries. +/// +/// The payload fields follow the pinned WIT's payload types; each is set only for the codes that +/// name it in @c HttpErrorCode, and empty otherwise. @c reason refines a refusal beyond the WIT. +struct HttpError +{ + HttpErrorCode code = HttpErrorCode::InternalError; ///< What failed. + std::optional size; ///< The size past a limit, or the actual body size. + std::optional fieldName; ///< The field a field-size code is about. + std::optional dnsRcode; ///< The DNS response code's name (@c DnsError). + std::optional dnsInfoCode; ///< The extended DNS error code (@c DnsError). + std::optional coding; ///< The coding a coding code is about. + std::optional tls; ///< The TLS failure (@c TlsAlertReceived and others). + std::string detail; ///< A human-readable reason; may be empty. + RefusalReason reason = RefusalReason::Unclassified; ///< What a refusal was for, beyond the code. + + /// The code's name, then whatever of the payload is set. + [[nodiscard]] CORE_HTTP_API std::string toString() const; +}; + +/// The result of an HTTP operation. +template +using HttpResult = std::expected; + +/// One field line: a name and its value, as given (names keep their case). +struct Field +{ + std::string name; ///< The field name, a token. + std::string value; ///< The field value, without leading or trailing whitespace. +}; + +/// An ordered list of field lines: a head's fields or a body's trailers. +/// +/// Every entry was validated on the way in, so a @c Fields is safe to write as it is. It refuses no +/// name for what the name means: framing fields such as Content-Length are legal entries, and +/// keeping a caller's out of a message is the writer's rule (@c isFramingField), not this type's. +class CORE_HTTP_API Fields +{ + public: + /// Appends one field line. + /// + /// Refuses a name that is not a token (RFC 9110 section 5.1), and a value with CR, LF, NUL, any + /// other control character but HTAB, or leading or trailing whitespace (section 5.5). + /// @param name The field name. + /// @param value The field value. + /// @return Nothing, or @c HttpErrorCode::ProtocolError naming the field; nothing is appended then. + [[nodiscard]] HttpResult append(std::string name, std::string value); + + /// Every value of the field named @p name, compared without regard to case, in order. + /// @param name The field name. + /// @return Views of the values, valid until this list changes. + [[nodiscard]] std::vector get(std::string_view name) const; + + /// Removes every field line named @p name, compared without regard to case. + /// @param name The field name. + /// @return How many lines were removed. + std::size_t erase(std::string_view name); + + /// Every field line, in order. + [[nodiscard]] std::span entries() const noexcept { return _entries; } + + private: + std::vector _entries; +}; + +/// A request method: a token (RFC 9110 section 9.1), case-sensitive. +class CORE_HTTP_API Method +{ + public: + /// GET. + Method(); + + /// Validates @p token as a method. + /// @param token The method, as it appears on the request line. + /// @return The method, or @c HttpErrorCode::RequestMethodInvalid. + [[nodiscard]] static HttpResult parse(std::string_view token); + + /// The method's text. + [[nodiscard]] std::string_view text() const noexcept { return _text; } + + private: + explicit Method(std::string text); + + std::string _text; +}; + +/// Which of the four forms of RFC 9112 section 3.2 a request target has. +enum class RequestTargetForm : std::uint8_t +{ + Origin, ///< An absolute path and an optional query: `/where?q`. + Absolute, ///< An absolute URI: `http://host/where`, as sent to a proxy. + Authority, ///< A host and a port: `host:443`, for CONNECT. + Asterisk, ///< `*`, for a server-wide OPTIONS. +}; + +/// A request target, validated to be one of the four forms and to hold only URI characters. +class CORE_HTTP_API RequestTarget +{ + public: + /// `/`. + RequestTarget(); + + /// Validates @p target. + /// + /// Refuses whitespace, control characters, octets outside ASCII, a fragment, a malformed + /// percent-encoding, and anything that is not one of the four forms. + /// @param target The target, as it appears on the request line. + /// @return The target, or @c HttpErrorCode::RequestUriInvalid. + [[nodiscard]] static HttpResult parse(std::string_view target); + + /// The target's text. + [[nodiscard]] std::string_view text() const noexcept { return _text; } + + /// The target's form. + [[nodiscard]] RequestTargetForm form() const noexcept { return _form; } + + private: + RequestTarget(std::string text, RequestTargetForm form); + + std::string _text; + RequestTargetForm _form; +}; + +/// A status line's reason phrase: HTAB, SP, visible ASCII and obs-text (RFC 9112 section 4). +class CORE_HTTP_API ReasonPhrase +{ + public: + /// The empty phrase. + ReasonPhrase() = default; + + /// Validates @p text. + /// @param text The phrase; may be empty. + /// @return The phrase, or @c HttpErrorCode::ProtocolError for a control character but HTAB. + [[nodiscard]] static HttpResult parse(std::string_view text); + + /// The phrase's text. + [[nodiscard]] std::string_view text() const noexcept { return _text; } + + private: + explicit ReasonPhrase(std::string text); + + std::string _text; +}; + +/// A request's start line and its fields. +struct RequestHead +{ + Method method; ///< The method. + RequestTarget target; ///< The request target. + HttpVersion version = HttpVersion::Http11; ///< The version it is framed by. + Fields fields; ///< The header fields. +}; + +/// A response's status line and its fields. +struct ResponseHead +{ + std::uint16_t status = 200; ///< The status code, 100 to 599. + ReasonPhrase reason; ///< The reason phrase. + HttpVersion version = HttpVersion::Http11; ///< The version it is framed by. + Fields fields; ///< The header fields. +}; + +} // namespace core::http diff --git a/src/core/http/Message_test.cpp b/src/core/http/Message_test.cpp new file mode 100644 index 00000000..c282decc --- /dev/null +++ b/src/core/http/Message_test.cpp @@ -0,0 +1,233 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The message vocabulary: the error codes and their payload, and the validating factories every +// outbound field, method, target and reason phrase is built through. +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using core::http::Fields; +using core::http::HttpError; +using core::http::HttpErrorCode; +using core::http::Method; +using core::http::ReasonPhrase; +using core::http::RequestTarget; +using core::http::RequestTargetForm; +using namespace std::string_view_literals; + +namespace +{ + +/// Every code below the @c Last sentinel. +auto allCodes() +{ + return std::views::iota(std::size_t { 0 }, static_cast(HttpErrorCode::Last)) + | std::views::transform([](std::size_t index) { return static_cast(index); }); +} + +} // namespace + +// The payload's field types are the pinned wasi:http `error-code` payloads' (R26): a DNS rcode is a +// string, its info code a u16; sizes are u64 (P14 narrows the u32 cases). +static_assert(std::is_same_v); +static_assert(std::is_same_v>); +static_assert(std::is_same_v>); +static_assert(std::is_same_v>); +static_assert(std::is_same_v>); +static_assert(std::is_same_v>); +static_assert(std::is_same_v>); +static_assert(std::is_same_v); + +TEST_CASE("Message.everyErrorCodeHasADistinctName", "[http]") +{ + auto names = std::set {}; + for (auto const code: allCodes()) + { + auto const name = core::http::toString(code); + INFO("code " << static_cast(code)); + CHECK_FALSE(name.empty()); + CHECK(name != core::http::toString(HttpErrorCode::Last)); + names.insert(name); + } + CHECK(names.size() == static_cast(HttpErrorCode::Last)); + CHECK(core::http::toString(HttpErrorCode::DnsTimeout) == "DNS timeout"); + CHECK(core::http::toString(HttpErrorCode::InternalError) == "internal error"); +} + +TEST_CASE("Message.errorToStringCarriesItsPayload", "[http]") +{ + auto const error = HttpError { .code = HttpErrorCode::RequestHeaderSize, + .size = 17000, + .fieldName = std::string { "X-Big" }, + .dnsRcode = std::nullopt, + .dnsInfoCode = std::nullopt, + .coding = std::nullopt, + .tls = std::nullopt, + .detail = "field line too long", + .reason = core::http::RefusalReason::Unclassified }; + auto const text = error.toString(); + CHECK(text.contains("request header size")); + CHECK(text.contains("X-Big")); + CHECK(text.contains("17000")); + CHECK(text.contains("field line too long")); +} + +TEST_CASE("Message.fieldsAppendRefusesInvalidNamesAndValues", "[http]") +{ + struct Row + { + std::string_view name; + std::string_view value; + }; + auto const refused = std::vector { + { .name = "X", .value = "a\r\nb" }, // response splitting + { .name = "X", .value = "a\rb" }, // a bare CR + { .name = "X", .value = "a\nb" }, // a bare LF + { .name = "X", .value = "a\0b"sv }, // NUL + { .name = "X", + .value = "a\x01" + "b" }, // another control character + { .name = "X", .value = "a\x7f" }, // DEL + { .name = "X", .value = " a" }, // leading whitespace + { .name = "X", .value = "a\t" }, // trailing whitespace + { .name = "", .value = "a" }, // an empty name + { .name = "X Y", .value = "a" }, // a space in the name + { .name = "X:", .value = "a" }, // a colon in the name + { .name = "X\r\nY", .value = "a" }, // CRLF in the name + { .name = "Ä", .value = "a" }, // a non-token octet in the name + }; + for (auto const& row: refused) + { + auto fields = Fields {}; + INFO("name '" << row.name << "' value '" << row.value << "'"); + auto const result = fields.append(std::string { row.name }, std::string { row.value }); + REQUIRE_FALSE(result.has_value()); + CHECK(result.error().code == HttpErrorCode::ProtocolError); + CHECK(fields.entries().empty()); + } +} + +TEST_CASE("Message.fieldsAcceptFramingFieldsAndInnerWhitespace", "[http]") +{ + // Content-Length and TE are legal guest fields: P14 strips them from the head and passes the + // length on as knownLength. Refusing them is the connection's job (D7), not the field type's. + auto fields = Fields {}; + REQUIRE(fields.append("Content-Length", "3").has_value()); + REQUIRE(fields.append("TE", "trailers").has_value()); + REQUIRE(fields.append("Transfer-Encoding", "chunked").has_value()); + REQUIRE(fields.append("X-Spaced", "a b\tc").has_value()); + REQUIRE(fields.append("X-Empty", "").has_value()); + REQUIRE(fields.append("X-Obs-Text", "caf\xc3\xa9").has_value()); + CHECK(fields.entries().size() == 6); +} + +TEST_CASE("Message.fieldsGetIsCaseInsensitiveAndKeepsOrder", "[http]") +{ + auto fields = Fields {}; + REQUIRE(fields.append("Set-Cookie", "a=1").has_value()); + REQUIRE(fields.append("Host", "example.com").has_value()); + REQUIRE(fields.append("set-cookie", "b=2").has_value()); + + auto const cookies = fields.get("SET-COOKIE"); + REQUIRE(cookies.size() == 2); + CHECK(cookies[0] == "a=1"); + CHECK(cookies[1] == "b=2"); + CHECK(fields.get("Absent").empty()); + + CHECK(fields.erase("SET-cookie") == 2); + CHECK(fields.erase("SET-cookie") == 0); + REQUIRE(fields.entries().size() == 1); + CHECK(fields.entries()[0].name == "Host"); + CHECK(fields.entries()[0].value == "example.com"); +} + +TEST_CASE("Message.methodParse", "[http]") +{ + for (auto const text: { "GE T"sv, ""sv, "GET\r\n"sv, "G(T"sv, "GET\0"sv }) + { + INFO("method '" << text << "'"); + auto const method = Method::parse(text); + REQUIRE_FALSE(method.has_value()); + CHECK(method.error().code == HttpErrorCode::RequestMethodInvalid); + } + auto const method = Method::parse("PROPFIND"); + REQUIRE(method.has_value()); + CHECK(method->text() == "PROPFIND"); + CHECK(Method {}.text() == "GET"); +} + +TEST_CASE("Message.requestTargetParse", "[http]") +{ + struct Row + { + std::string_view text; + RequestTargetForm form; + }; + auto const accepted = std::vector { + { .text = "/", .form = RequestTargetForm::Origin }, + { .text = "/a/b?c=d&e=%20f", .form = RequestTargetForm::Origin }, + { .text = "/a:b@c!$'()*+,;=-._~", .form = RequestTargetForm::Origin }, + { .text = "http://example.com/x?y", .form = RequestTargetForm::Absolute }, + { .text = "https://[::1]:8443/", .form = RequestTargetForm::Absolute }, + { .text = "example.com:443", .form = RequestTargetForm::Authority }, + { .text = "[::1]:443", .form = RequestTargetForm::Authority }, + { .text = "*", .form = RequestTargetForm::Asterisk }, + }; + for (auto const& row: accepted) + { + INFO("target '" << row.text << "'"); + auto const target = RequestTarget::parse(row.text); + REQUIRE(target.has_value()); + CHECK(target->text() == row.text); + CHECK(target->form() == row.form); + } + + for (auto const text: { "/a b"sv, + ""sv, + "/a\r\nb"sv, + "/a#frag"sv, + "/%zz"sv, + "/%2"sv, + "a/b"sv, + "example.com"sv, + "example.com:"sv, + "example.com:8x"sv, + "**"sv, + "/\x80"sv, + "1http://x/"sv }) + { + INFO("target '" << text << "'"); + auto const target = RequestTarget::parse(text); + REQUIRE_FALSE(target.has_value()); + CHECK(target.error().code == HttpErrorCode::RequestUriInvalid); + } + CHECK(RequestTarget {}.text() == "/"); +} + +TEST_CASE("Message.reasonPhraseParse", "[http]") +{ + for (auto const text: { "OK\r\n"sv, "O\rK"sv, "O\nK"sv, "\x01"sv }) + { + INFO("reason '" << text << "'"); + auto const reason = ReasonPhrase::parse(text); + REQUIRE_FALSE(reason.has_value()); + CHECK(reason.error().code == HttpErrorCode::ProtocolError); + } + for (auto const text: { "OK"sv, ""sv, "Not Found"sv, "Tab\there"sv, "caf\xc3\xa9"sv }) + { + INFO("reason '" << text << "'"); + auto const reason = ReasonPhrase::parse(text); + REQUIRE(reason.has_value()); + CHECK(reason->text() == text); + } +} diff --git a/src/core/http/SmugglingCorpus.hpp b/src/core/http/SmugglingCorpus.hpp new file mode 100644 index 00000000..f320c46a --- /dev/null +++ b/src/core/http/SmugglingCorpus.hpp @@ -0,0 +1,891 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// The request-smuggling corpus: requests whose framing RFC 9112 says to refuse, beside the ones it +/// says to accept, each with the error and the status a server answers. Run here through +/// @c HeadParser, @c requestFraming and @c ChunkedDecoder (Framing_test.cpp), and by the server's +/// tests (Task 18) over a connection, both under @c smugglingLimits(). Test-only: in no +/// `FILE_SET`, so never installed. + +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace core::http::test +{ + +/// Whether a corpus message is to be refused or read. +enum class SmugglingVerdict : std::uint8_t +{ + Refused, ///< The message is refused with @c SmugglingCase::code and @c SmugglingCase::status. + Accepted, ///< The message is read; its body is @c SmugglingCase::body. +}; + +/// One message of the corpus. +struct SmugglingCase +{ + std::string_view name; ///< What the row tests, unique, usable as a section name. + MessageRole role; ///< A request (a server reads it) or a response (a client does). + std::string_view wire; ///< The message's bytes, as its sender sends them. + SmugglingVerdict verdict; ///< Refused or accepted. + HttpErrorCode code; ///< The error a refused message is refused with; unused when accepted. + /// What a server answers a request row with (200 when accepted); for a response row, what a + /// gateway that received it answers its own client with (502 when refused). + std::uint16_t status; + std::string_view body; ///< The decoded body of an accepted message. +}; + +/// The limits the corpus is written against: small enough that a size row is a short literal. +[[nodiscard]] inline HttpLimits smugglingLimits() +{ + return HttpLimits { .maxHeadBytes = 1024, + .maxFieldBytes = 256, + .maxFields = 100, + .maxTrailerBytes = 256, + .maxChunkLineBytes = 64, + .maxReadChunk = std::size_t { 64 } * 1024, + .maxBodyBytes = std::nullopt }; +} + +namespace detail +{ + using namespace std::string_view_literals; + + inline constexpr auto SmugglingRows = std::array { + // RFC 9112 6.1: Transfer-Encoding and Content-Length together; the server may reject, and does + SmugglingCase { .name = "te-with-cl", + .role = MessageRole::Request, + .wire = "POST / HTTP/1.1\r\n" + "Host: a\r\n" + "Content-Length: 3\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n" + "3\r\n" + "abc\r\n" + "0\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 400, + .body = "" }, + // RFC 9112 6.3 item 5: an invalid Content-Length + SmugglingCase { .name = "cl-two-different", + .role = MessageRole::Request, + .wire = "POST / HTTP/1.1\r\n" + "Host: a\r\n" + "Content-Length: 3\r\n" + "Content-Length: 4\r\n" + "\r\n" + "abcd"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 400, + .body = "" }, + // RFC 9110 8.6: a list of differing values + SmugglingCase { .name = "cl-list-differs", + .role = MessageRole::Request, + .wire = "POST / HTTP/1.1\r\n" + "Host: a\r\n" + "Content-Length: 3, 4\r\n" + "\r\n" + "abcd"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 400, + .body = "" }, + // RFC 9110 8.6: Content-Length = 1*DIGIT + SmugglingCase { .name = "cl-plus-sign", + .role = MessageRole::Request, + .wire = "POST / HTTP/1.1\r\n" + "Host: a\r\n" + "Content-Length: +3\r\n" + "\r\n" + "abc"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 400, + .body = "" }, + // RFC 9110 8.6: Content-Length = 1*DIGIT + SmugglingCase { .name = "cl-minus-sign", + .role = MessageRole::Request, + .wire = "POST / HTTP/1.1\r\n" + "Host: a\r\n" + "Content-Length: -3\r\n" + "\r\n" + "abc"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 400, + .body = "" }, + // RFC 9110 8.6: whitespace inside the value + SmugglingCase { .name = "cl-inner-space", + .role = MessageRole::Request, + .wire = "POST / HTTP/1.1\r\n" + "Host: a\r\n" + "Content-Length: 1 2\r\n" + "\r\n" + "abcdefghijkl"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 400, + .body = "" }, + // RFC 9110 8.6: Content-Length = 1*DIGIT + SmugglingCase { .name = "cl-hex", + .role = MessageRole::Request, + .wire = "POST / HTTP/1.1\r\n" + "Host: a\r\n" + "Content-Length: 0x3\r\n" + "\r\n" + "abc"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 400, + .body = "" }, + // RFC 9110 8.6: Content-Length = 1*DIGIT + SmugglingCase { .name = "cl-empty", + .role = MessageRole::Request, + .wire = "POST / HTTP/1.1\r\n" + "Host: a\r\n" + "Content-Length: \r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 400, + .body = "" }, + // RFC 9110 8.6: a length past 2^64 - 1 cannot be represented + SmugglingCase { .name = "cl-overflow", + .role = MessageRole::Request, + .wire = "POST / HTTP/1.1\r\n" + "Host: a\r\n" + "Content-Length: 18446744073709551616\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 400, + .body = "" }, + // RFC 9110 8.6: identical values are one value + SmugglingCase { .name = "cl-identical-duplicate", + .role = MessageRole::Request, + .wire = "POST / HTTP/1.1\r\n" + "Host: a\r\n" + "Content-Length: 3\r\n" + "Content-Length: 3\r\n" + "\r\n" + "abc"sv, + .verdict = SmugglingVerdict::Accepted, + .code = HttpErrorCode::InternalError, + .status = 200, + .body = "abc" }, + // RFC 9110 8.6: a list of identical decimal values is one value + SmugglingCase { .name = "cl-identical-list", + .role = MessageRole::Request, + .wire = "POST / HTTP/1.1\r\n" + "Host: a\r\n" + "Content-Length: 3, 003\r\n" + "\r\n" + "abc"sv, + .verdict = SmugglingVerdict::Accepted, + .code = HttpErrorCode::InternalError, + .status = 200, + .body = "abc" }, + // RFC 9112 7: chunked is applied at most once + SmugglingCase { .name = "te-chunked-twice", + .role = MessageRole::Request, + .wire = "POST / HTTP/1.1\r\n" + "Host: a\r\n" + "Transfer-Encoding: chunked, chunked\r\n" + "\r\n" + "0\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 400, + .body = "" }, + // RFC 9112 7: chunked is applied at most once, across field lines too + SmugglingCase { .name = "te-chunked-twice-lines", + .role = MessageRole::Request, + .wire = "POST / HTTP/1.1\r\n" + "Host: a\r\n" + "Transfer-Encoding: chunked\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n" + "0\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 400, + .body = "" }, + // RFC 9112 6.3 item 4: chunked is not the final request coding + SmugglingCase { .name = "te-chunked-then-gzip", + .role = MessageRole::Request, + .wire = "POST / HTTP/1.1\r\n" + "Host: a\r\n" + "Transfer-Encoding: chunked, gzip\r\n" + "\r\n" + "0\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 400, + .body = "" }, + // RFC 9112 6.3 item 4: chunked is not the final request coding + SmugglingCase { .name = "te-not-chunked", + .role = MessageRole::Request, + .wire = "POST / HTTP/1.1\r\n" + "Host: a\r\n" + "Transfer-Encoding: gzip\r\n" + "\r\n" + "abc"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 400, + .body = "" }, + // RFC 9112 6.1: a Transfer-Encoding with no coding + SmugglingCase { .name = "te-empty", + .role = MessageRole::Request, + .wire = "POST / HTTP/1.1\r\n" + "Host: a\r\n" + "Transfer-Encoding: \r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 400, + .body = "" }, + // RFC 9112 7: chunked takes no parameter + SmugglingCase { .name = "te-chunked-with-parameter", + .role = MessageRole::Request, + .wire = "POST / HTTP/1.1\r\n" + "Host: a\r\n" + "Transfer-Encoding: chunked;q=1\r\n" + "\r\n" + "0\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 400, + .body = "" }, + // RFC 9112 6.1: Transfer-Encoding in HTTP/1.0 is faulty framing; the connection closes + SmugglingCase { .name = "te-on-http10", + .role = MessageRole::Request, + .wire = "POST / HTTP/1.0\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n" + "0\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 400, + .body = "" }, + // RFC 9112 5.1: whitespace between the field name and the colon + SmugglingCase { .name = "te-space-before-colon", + .role = MessageRole::Request, + .wire = "POST / HTTP/1.1\r\n" + "Host: a\r\n" + "Transfer-Encoding : chunked\r\n" + "Content-Length: 3\r\n" + "\r\n" + "abc"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 400, + .body = "" }, + // RFC 9112 5.1: whitespace between the field name and the colon + SmugglingCase { .name = "cl-space-before-colon", + .role = MessageRole::Request, + .wire = "POST / HTTP/1.1\r\n" + "Host: a\r\n" + "Content-Length : 3\r\n" + "\r\n" + "abc"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 400, + .body = "" }, + // RFC 9112 3.2: more than one Host field line + SmugglingCase { .name = "host-twice", + .role = MessageRole::Request, + .wire = "GET / HTTP/1.1\r\n" + "Host: a\r\n" + "Host: b\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 400, + .body = "" }, + // RFC 9112 3.2: an HTTP/1.1 request without Host + SmugglingCase { .name = "host-missing-http11", + .role = MessageRole::Request, + .wire = "GET / HTTP/1.1\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 400, + .body = "" }, + // RFC 9112 3.2: only HTTP/1.1 requires Host + SmugglingCase { .name = "host-missing-http10", + .role = MessageRole::Request, + .wire = "GET / HTTP/1.0\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Accepted, + .code = HttpErrorCode::InternalError, + .status = 200, + .body = "" }, + // RFC 9112 3.2: an invalid Host value + SmugglingCase { .name = "host-invalid", + .role = MessageRole::Request, + .wire = "GET / HTTP/1.1\r\n" + "Host: a/b\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 400, + .body = "" }, + // RFC 9112 5.2: a server rejects obs-fold + SmugglingCase { .name = "obs-fold", + .role = MessageRole::Request, + .wire = "GET / HTTP/1.1\r\n" + "Host: a\r\n" + "X-A: 1\r\n" + " 2\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 400, + .body = "" }, + // RFC 9112 2.2: whitespace between the start line and the first field + SmugglingCase { .name = "whitespace-before-first-field", + .role = MessageRole::Request, + .wire = "GET / HTTP/1.1\r\n" + " Host: a\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 400, + .body = "" }, + // RFC 9112 2.2: a bare LF line ending is refused, not recognized + SmugglingCase { .name = "bare-lf", + .role = MessageRole::Request, + .wire = "GET / HTTP/1.1\n" + "Host: a\n" + "\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 400, + .body = "" }, + // RFC 9112 2.2: a bare LF line ending is refused, not recognized + SmugglingCase { .name = "bare-lf-in-fields", + .role = MessageRole::Request, + .wire = "GET / HTTP/1.1\r\n" + "Host: a\n" + "X-A: b\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 400, + .body = "" }, + // RFC 9112 2.2: a bare CR is invalid + SmugglingCase { .name = "bare-cr", + .role = MessageRole::Request, + .wire = "GET / HTTP/1.1\r\n" + "Host: a\rX-A: b\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 400, + .body = "" }, + // RFC 9110 5.5: a NUL in a field value + SmugglingCase { .name = "nul-in-value", + .role = MessageRole::Request, + .wire = "GET / HTTP/1.1\r\n" + "Host: a\r\n" + "X-A: a\0b\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 400, + .body = "" }, + // RFC 9112 2.3: only major version 1 is spoken + SmugglingCase { .name = "http-version-2", + .role = MessageRole::Request, + .wire = "GET / HTTP/2.0\r\n" + "Host: a\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 505, + .body = "" }, + // a chunk size past 16 hex digits could overflow 64 bits + SmugglingCase { .name = "chunk-size-17-digits", + .role = MessageRole::Request, + .wire = "POST / HTTP/1.1\r\n" + "Host: a\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n" + "00000000000000001\r\n" + "a\r\n" + "0\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 400, + .body = "" }, + // 16 hex digits fit; leading zeros are digits + SmugglingCase { .name = "chunk-size-16-digits", + .role = MessageRole::Request, + .wire = "POST / HTTP/1.1\r\n" + "Host: a\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n" + "0000000000000001\r\n" + "a\r\n" + "0\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Accepted, + .code = HttpErrorCode::InternalError, + .status = 200, + .body = "a" }, + // RFC 9112 7.1: a chunk line ends in CRLF + SmugglingCase { .name = "chunk-size-bare-lf", + .role = MessageRole::Request, + .wire = "POST / HTTP/1.1\r\n" + "Host: a\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n" + "3\n" + "abc\r\n" + "0\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 400, + .body = "" }, + // RFC 9112 7.1: chunk data is followed by CRLF + SmugglingCase { .name = "chunk-data-overrun", + .role = MessageRole::Request, + .wire = "POST / HTTP/1.1\r\n" + "Host: a\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n" + "3\r\n" + "abcd\r\n" + "0\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 400, + .body = "" }, + // RFC 9112 7.1: whitespace after the size is BWS before a ";" only + SmugglingCase { .name = "chunk-size-trailing-space", + .role = MessageRole::Request, + .wire = "POST / HTTP/1.1\r\n" + "Host: a\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n" + "3 \r\n" + "abc\r\n" + "0\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 400, + .body = "" }, + // RFC 9112 7.1: chunk-size = 1*HEXDIG, so an empty chunk line is no size of 0 + SmugglingCase { .name = "chunk-size-empty", + .role = MessageRole::Request, + .wire = "POST / HTTP/1.1\r\n" + "Host: a\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n" + "\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 400, + .body = "" }, + // RFC 9112 7.1: chunk-size = 1*HEXDIG + SmugglingCase { .name = "chunk-size-not-hex", + .role = MessageRole::Request, + .wire = "POST / HTTP/1.1\r\n" + "Host: a\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n" + "3g\r\n" + "abc\r\n" + "0\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 400, + .body = "" }, + // RFC 9112 7.1.1: extensions and trailers are accepted + SmugglingCase { .name = "chunk-extension", + .role = MessageRole::Request, + .wire = "POST / HTTP/1.1\r\n" + "Host: a\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n" + "3 ; name=\"v a\"\r\n" + "abc\r\n" + "0;x\r\n" + "X-T: 1\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Accepted, + .code = HttpErrorCode::InternalError, + .status = 200, + .body = "abc" }, + // RFC 9112 6.1: a request coding this layer cannot decode; a server answers 501 + SmugglingCase { .name = "te-gzip-chunked", + .role = MessageRole::Request, + .wire = "POST / HTTP/1.1\r\n" + "Host: a\r\n" + "Transfer-Encoding: gzip, chunked\r\n" + "\r\n" + "3\r\n" + "abc\r\n" + "0\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 501, + .body = "" }, + // a quoted comma does not split a coding list; the unterminated quote is malformed + SmugglingCase { .name = "te-unterminated-quote", + .role = MessageRole::Request, + .wire = "POST / HTTP/1.1\r\n" + "Host: a\r\n" + "Transfer-Encoding: gzip;a=\"x, chunked\r\n" + "\r\n" + "3\r\n" + "abc\r\n" + "0\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 400, + .body = "" }, + // RFC 9112 6.1: a request transfer coding with a parameter; a server answers 501 + SmugglingCase { .name = "te-parameter", + .role = MessageRole::Request, + .wire = "POST / HTTP/1.1\r\n" + "Host: a\r\n" + "Transfer-Encoding: gzip;q=1, chunked\r\n" + "\r\n" + "3\r\n" + "abc\r\n" + "0\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 501, + .body = "" }, + // RFC 9112 6.1: a quoted parameter that hides a comma; a server answers 501 + SmugglingCase { .name = "te-quoted-parameter", + .role = MessageRole::Request, + .wire = "POST / HTTP/1.1\r\n" + "Host: a\r\n" + "Transfer-Encoding: gzip;a=\"x, y\", chunked\r\n" + "\r\n" + "3\r\n" + "abc\r\n" + "0\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 501, + .body = "" }, + // RFC 9112 7.1: a bare LF ends a chunk extension + SmugglingCase { .name = "chunk-extension-bare-lf", + .role = MessageRole::Request, + .wire = "POST / HTTP/1.1\r\n" + "Host: a\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n" + "3;a\n" + "abc\r\n" + "0\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 400, + .body = "" }, + // RFC 9112 7.1: a bare CR inside a chunk extension + SmugglingCase { .name = "chunk-extension-bare-cr", + .role = MessageRole::Request, + .wire = "POST / HTTP/1.1\r\n" + "Host: a\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n" + "3;a\rz\r\n" + "abc\r\n" + "0\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 400, + .body = "" }, + // RFC 9110 5.5: a NUL inside a chunk extension + SmugglingCase { .name = "chunk-extension-nul", + .role = MessageRole::Request, + .wire = "POST / HTTP/1.1\r\n" + "Host: a\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n" + "3;a\0b\r\n" + "abc\r\n" + "0\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 400, + .body = "" }, + // RFC 9112 7.1: chunk data ends in CRLF, not a bare LF + SmugglingCase { .name = "chunk-data-bare-lf", + .role = MessageRole::Request, + .wire = "POST / HTTP/1.1\r\n" + "Host: a\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n" + "3\r\n" + "abc\n" + "0\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 400, + .body = "" }, + // RFC 9112 2.2: a trailer line ending in a bare LF + SmugglingCase { .name = "trailer-bare-lf", + .role = MessageRole::Request, + .wire = "POST / HTTP/1.1\r\n" + "Host: a\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n" + "0\r\n" + "X-T: 1\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 400, + .body = "" }, + // RFC 9112 2.2: a bare LF line ending in a response head + SmugglingCase { .name = "response-bare-lf", + .role = MessageRole::Response, + .wire = "HTTP/1.1 200 OK\n" + "Content-Length: 0\n" + "\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 502, + .body = "" }, + // RFC 9110 5.5: a NUL in a response field value + SmugglingCase { .name = "response-nul-in-value", + .role = MessageRole::Response, + .wire = "HTTP/1.1 200 OK\r\n" + "X-A: a\0b\r\n" + "Content-Length: 0\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 502, + .body = "" }, + // RFC 9112 6.3 item 3: a response with TE and CL frames as chunked (and closes) + SmugglingCase { .name = "response-te-with-cl", + .role = MessageRole::Response, + .wire = "HTTP/1.1 200 OK\r\n" + "Content-Length: 99\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n" + "3\r\n" + "abc\r\n" + "0\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Accepted, + .code = HttpErrorCode::InternalError, + .status = 200, + .body = "abc" }, + // RFC 9112 6.3 item 5: a response with two different lengths + SmugglingCase { .name = "response-cl-two-different", + .role = MessageRole::Response, + .wire = "HTTP/1.1 200 OK\r\n" + "Content-Length: 3\r\n" + "Content-Length: 4\r\n" + "\r\n" + "abcd"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 502, + .body = "" }, + // RFC 9110 5.6.4: an escaped quote does not end a quoted-string, so the comma after it is + // inside the string and the list ends unterminated + SmugglingCase { .name = "response-te-escaped-quote", + .role = MessageRole::Response, + .wire = "HTTP/1.1 200 OK\r\n" + "Transfer-Encoding: gzip;a=\"x\\\", chunked\r\n" + "\r\n" + "3\r\n" + "abc\r\n" + "0\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 502, + .body = "" }, + // the head is past HttpLimits::maxHeadBytes + SmugglingCase { .name = "head-too-large", + .role = MessageRole::Request, + .wire = "GET / HTTP/1.1\r\n" + "Host: a\r\n" + "X-Pad-0: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\r\n" + "X-Pad-1: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\r\n" + "X-Pad-2: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\r\n" + "X-Pad-3: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\r\n" + "X-Pad-4: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::RequestHeaderSectionSize, + .status = 431, + .body = "" }, + // RFC 9112 3.2.3: the authority-form is only used for CONNECT + SmugglingCase { .name = "target-authority-with-get", + .role = MessageRole::Request, + .wire = "GET a:80 HTTP/1.1\r\n" + "Host: a\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::RequestUriInvalid, + .status = 400, + .body = "" }, + // RFC 9112 3.2.3: not even with OPTIONS + SmugglingCase { .name = "target-authority-with-options", + .role = MessageRole::Request, + .wire = "OPTIONS a:80 HTTP/1.1\r\n" + "Host: a\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::RequestUriInvalid, + .status = 400, + .body = "" }, + // RFC 9112 3.2.3: CONNECT names an authority and nothing else + SmugglingCase { .name = "target-connect-origin-form", + .role = MessageRole::Request, + .wire = "CONNECT / HTTP/1.1\r\n" + "Host: a\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::RequestUriInvalid, + .status = 400, + .body = "" }, + // RFC 9110 9.3.6: CONNECT's target is an authority + SmugglingCase { .name = "target-connect-absolute-form", + .role = MessageRole::Request, + .wire = "CONNECT http://a/ HTTP/1.1\r\n" + "Host: a\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::RequestUriInvalid, + .status = 400, + .body = "" }, + // RFC 9112 3.2.4: the asterisk-form is only used for a server-wide OPTIONS + SmugglingCase { .name = "target-asterisk-with-get", + .role = MessageRole::Request, + .wire = "GET * HTTP/1.1\r\n" + "Host: a\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::RequestUriInvalid, + .status = 400, + .body = "" }, + // RFC 9112 3.2.3: CONNECT with the authority-form + SmugglingCase { .name = "target-connect-authority", + .role = MessageRole::Request, + .wire = "CONNECT a:443 HTTP/1.1\r\n" + "Host: a:443\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Accepted, + .code = HttpErrorCode::InternalError, + .status = 200, + .body = "" }, + // RFC 9112 3.2.4: OPTIONS with the asterisk-form + SmugglingCase { .name = "target-options-asterisk", + .role = MessageRole::Request, + .wire = "OPTIONS * HTTP/1.1\r\n" + "Host: a\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Accepted, + .code = HttpErrorCode::InternalError, + .status = 200, + .body = "" }, + // RFC 9110 9.3.7: OPTIONS may name a resource too + SmugglingCase { .name = "target-options-origin-form", + .role = MessageRole::Request, + .wire = "OPTIONS /x HTTP/1.1\r\n" + "Host: a\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Accepted, + .code = HttpErrorCode::InternalError, + .status = 200, + .body = "" }, + // RFC 9112 3.2.2: a server accepts the absolute-form + SmugglingCase { .name = "target-absolute-form", + .role = MessageRole::Request, + .wire = "GET http://a/x HTTP/1.1\r\n" + "Host: a\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Accepted, + .code = HttpErrorCode::InternalError, + .status = 200, + .body = "" }, + // a field line is past HttpLimits::maxFieldBytes + SmugglingCase { .name = "field-too-large", + .role = MessageRole::Request, + .wire = "GET / HTTP/1.1\r\n" + "Host: a\r\n" + "X-Big: bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::RequestHeaderSize, + .status = 431, + .body = "" }, + // the request line is past HttpLimits::maxFieldBytes + SmugglingCase { .name = "request-line-too-long", + .role = MessageRole::Request, + .wire = "GET /ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" + "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" + "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" + "ccccccccccccccccccccccccccccccccccccccccccccccccc HTTP/1.1\r\n" + "Host: a\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::RequestUriTooLong, + .status = 414, + .body = "" }, + }; +} // namespace detail + +/// Every row of the corpus. +[[nodiscard]] constexpr std::span smugglingCorpus() noexcept +{ + return detail::SmugglingRows; +} + +} // namespace core::http::test diff --git a/src/core/http/detail/Syntax.hpp b/src/core/http/detail/Syntax.hpp new file mode 100644 index 00000000..33ff194f --- /dev/null +++ b/src/core/http/detail/Syntax.hpp @@ -0,0 +1,213 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// The character classes of RFC 9110 and RFC 3986 as one table, and the small predicates over it +/// that the message factories and the parsers share, and how they spell a refusal. Internal: in no +/// `FILE_SET`. + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace core::http::detail +{ + +/// One bit per character class an octet may belong to. +struct CharClass +{ + static constexpr std::uint8_t Token = 0b0000'0001; ///< tchar (RFC 9110 section 5.6.2). + static constexpr std::uint8_t FieldValue = 0b0000'0010; ///< field-vchar, SP, HTAB (section 5.5). + static constexpr std::uint8_t Hex = 0b0000'0100; ///< HEXDIG. + static constexpr std::uint8_t Unreserved = 0b0000'1000; ///< unreserved (RFC 3986 section 2.3). + static constexpr std::uint8_t SubDelim = 0b0001'0000; ///< sub-delims (RFC 3986 section 2.2). + static constexpr std::uint8_t Whitespace = 0b0010'0000; ///< SP, HTAB. + static constexpr std::uint8_t Digit = 0b0100'0000; ///< DIGIT. + static constexpr std::uint8_t Alpha = 0b1000'0000; ///< ALPHA. +}; + +/// The classes of every octet. +inline constexpr auto CharClasses = [] { + auto table = std::array {}; + auto const mark = [&table](std::string_view octets, std::uint8_t bits) { + for (auto const octet: octets) + table.at(static_cast(octet)) |= bits; + }; + constexpr auto Digits = std::string_view { "0123456789" }; + constexpr auto Lower = std::string_view { "abcdefghijklmnopqrstuvwxyz" }; + constexpr auto Upper = std::string_view { "ABCDEFGHIJKLMNOPQRSTUVWXYZ" }; + mark(Digits, CharClass::Token | CharClass::Hex | CharClass::Unreserved | CharClass::Digit); + mark(Lower, CharClass::Token | CharClass::Unreserved | CharClass::Alpha); + mark(Upper, CharClass::Token | CharClass::Unreserved | CharClass::Alpha); + mark("abcdefABCDEF", CharClass::Hex); + mark("!#$%&'*+-.^_`|~", CharClass::Token); + mark("-._~", CharClass::Unreserved); + mark("!$&'()*+,;=", CharClass::SubDelim); + mark(" \t", CharClass::Whitespace | CharClass::FieldValue); + for (auto const octet: std::views::iota(0x21, 0x7f)) + table.at(static_cast(octet)) |= CharClass::FieldValue; // VCHAR + for (auto const octet: std::views::iota(0x80, 0x100)) + table.at(static_cast(octet)) |= CharClass::FieldValue; // obs-text + return table; +}(); + +/// Whether @p octet is in any of @p classes. +[[nodiscard]] constexpr bool isIn(char octet, std::uint8_t classes) noexcept +{ + return (CharClasses.at(static_cast(octet)) & classes) != 0; +} + +/// Whether every octet of @p text is in one of @p classes. +[[nodiscard]] constexpr bool allIn(std::string_view text, std::uint8_t classes) noexcept +{ + return std::ranges::all_of(text, [classes](char octet) { return isIn(octet, classes); }); +} + +/// Whether @p text is a token: one or more tchar. +[[nodiscard]] constexpr bool isToken(std::string_view text) noexcept +{ + return !text.empty() && allIn(text, CharClass::Token); +} + +/// The lower-case of an ASCII letter, any other octet unchanged. +[[nodiscard]] constexpr char toLowerAscii(char octet) noexcept +{ + return octet >= 'A' && octet <= 'Z' ? static_cast(octet - 'A' + 'a') : octet; +} + +/// Whether @p a and @p b are equal ignoring ASCII case. +[[nodiscard]] constexpr bool equalsIgnoringCase(std::string_view a, std::string_view b) noexcept +{ + return std::ranges::equal(a, b, [](char x, char y) { return toLowerAscii(x) == toLowerAscii(y); }); +} + +/// @p text without leading and trailing SP and HTAB (OWS). +[[nodiscard]] constexpr std::string_view trimWhitespace(std::string_view text) noexcept +{ + auto const isSpace = [](char octet) { + return octet == ' ' || octet == '\t'; + }; + while (!text.empty() && isSpace(text.front())) + text.remove_prefix(1); + while (!text.empty() && isSpace(text.back())) + text.remove_suffix(1); + return text; +} + +/// Whether @p text is URI characters only, in @p classes or in @p extra, with every '%' starting a +/// two-hex-digit escape (RFC 3986 section 2.1). +[[nodiscard]] constexpr bool isUriText(std::string_view text, + std::uint8_t classes, + std::string_view extra) noexcept +{ + while (!text.empty()) + { + auto const octet = text.front(); + if (octet == '%') + { + if (text.size() < 3 || !isIn(text[1], CharClass::Hex) || !isIn(text[2], CharClass::Hex)) + return false; + text.remove_prefix(3); + continue; + } + if (!isIn(octet, classes) && !extra.contains(octet)) + return false; + text.remove_prefix(1); + } + return true; +} + +/// The value of @p digits, one or more decimal digits; empty if it is not that or exceeds 64 bits. +[[nodiscard]] constexpr std::optional parseDecimal(std::string_view digits) noexcept +{ + if (digits.empty()) + return std::nullopt; + constexpr auto Max = std::numeric_limits::max(); + auto value = std::uint64_t { 0 }; + for (auto const octet: digits) + { + if (!isIn(octet, CharClass::Digit)) + return std::nullopt; + auto const digit = static_cast(octet - '0'); + if (value > (Max - digit) / 10) + return std::nullopt; + value = (value * 10) + digit; + } + return value; +} + +/// Whether a port must have digits. +enum class PortRule : std::uint8_t +{ + Optional, ///< `host`, `host:` and `host:80` (a Host field, RFC 9110 section 7.2). + Required, ///< `host:80` only (authority-form, RFC 9112 section 3.2.3). +}; + +/// Whether @p text is `uri-host [ ":" port ]` (RFC 3986 section 3.2): an IP literal in brackets or a +/// reg-name (which covers IPv4), then a port of digits as @p rule demands. +[[nodiscard]] constexpr bool isAuthority(std::string_view text, PortRule rule) noexcept +{ + auto host = text; + auto port = std::string_view {}; + auto hasPort = false; + if (text.starts_with('[')) + { + auto const close = text.find(']'); + if (close == std::string_view::npos || close == 1) + return false; + host = text.substr(1, close - 1); + auto const rest = text.substr(close + 1); + if (!rest.empty() && !rest.starts_with(':')) + return false; + hasPort = !rest.empty(); + port = hasPort ? rest.substr(1) : rest; + if (!isUriText(host, CharClass::Unreserved | CharClass::SubDelim, ":")) + return false; + } + else + { + auto const colon = text.find(':'); + hasPort = colon != std::string_view::npos; + host = text.substr(0, colon); + port = hasPort ? text.substr(colon + 1) : std::string_view {}; + if (!isUriText(host, CharClass::Unreserved | CharClass::SubDelim, "")) + return false; + } + if (!allIn(port, CharClass::Digit)) + return false; + return rule == PortRule::Optional || (hasPort && !port.empty() && !host.empty()); +} + +/// A refusal of the caller's or the peer's syntax, framing or size. +/// @param code What failed. +/// @param detail Why. +/// @param fieldName The field it is about, if any. +/// @param size The size past a limit, if any. +/// @param reason What the refusal was for, beyond the code. +[[nodiscard]] inline HttpError refusal(HttpErrorCode code, + std::string detail, + std::optional fieldName = std::nullopt, + std::optional size = std::nullopt, + RefusalReason reason = RefusalReason::Unclassified) +{ + return HttpError { .code = code, + .size = size, + .fieldName = std::move(fieldName), + .dnsRcode = std::nullopt, + .dnsInfoCode = std::nullopt, + .coding = std::nullopt, + .tls = std::nullopt, + .detail = std::move(detail), + .reason = reason }; +} + +} // namespace core::http::detail diff --git a/tests/consumer-vendored/CMakeLists.txt b/tests/consumer-vendored/CMakeLists.txt index 8eeed18a..afbff716 100644 --- a/tests/consumer-vendored/CMakeLists.txt +++ b/tests/consumer-vendored/CMakeLists.txt @@ -6,7 +6,7 @@ # this project's own suite. # # cmake -DMODE=sync -DREF= -DDEST=/vendor/core-cpp \ -# "-DMODULES=base;log;cli;codec;platform;async;net;fs;testing" -P /cmake/CoreCppVendor.cmake +# "-DMODULES=base;log;cli;codec;platform;async;net;fs;http;testing" -P /cmake/CoreCppVendor.cmake # cmake -S tests/consumer-vendored -B -DCORE_CPP_VENDOR_DIR=/vendor/core-cpp # cmake --build && ctest --test-dir --output-on-failure # From ba01470efc30cd9d29c76cdf014dda737a913254 Mon Sep 17 00:00:00 2001 From: Christian Parpart Date: Fri, 27 Nov 2026 02:29:48 +0100 Subject: [PATCH 12/19] feat(http): role-aware connection with streamed bodies and trailers Connection puts the pure layer on an ISocket. Its MessageRole is what the end reads (Response on a client, Request on a server) and selects the error codes from one role table: a close inside a message is ResponseIncomplete or ProtocolError, a close before a head's first byte ConnectionTerminated, and a body that breaks its Length framing RequestBodySize or ResponseBodySize by what the end writes. Reads go through one buffer of HttpLimits::maxReadChunk bytes, the most the connection ever holds of a peer's bytes, into HeadParser and ChunkedDecoder constructed with the connection's limits, so trailers count against them. A Length body is held to maxBodyBytes here. Body readers share the connection state, may outlive the Connection, and are tied to the head they follow: a reader of an earlier body reads nothing of the next. A 1xx head has no body. Heads are written with one writeVectored. The connection adds the framing fields itself from a row per framing, and refuses a caller's framing field, UntilClose in a request, chunked in HTTP/1.0, and a body framing on 1xx, 204 or 304. A bodied response with no body is sent Content-Length: 0. writeBody writes no byte past a Length framing: a differing known length is refused before any body byte, a streamed one at the chunk that would pass it. Trailers need chunked and may hold no framing field. WireTimeouts.firstByte is ResponseTimeout in the response role and ConnectionReadTimeout in the request role, and betweenBytes is ConnectionReadTimeout; a zero duration is none (R31). Each read deadline is a DeadlineTimer that retires the parked read through cancelRead rather than a withTimeout race, because the race ends its losing read through the flow's stop token, which a transport without a loop park, InMemorySocket among them, never sees. Socket failures map through a NetErrorCode row table with a column per direction. reusable() is No after UntilClose, Persistence::Close, an error, a close, or an unread body in either direction. BufferBodySource and framingFor (known length and no trailers is Length, otherwise Chunked) complete the API. Also in this commit: - a close told from a broken connection, cancellation, HEAD and 304, a write deadline - sticky cancel marks, a serial request role - a head refused before its first wire byte leaves the connection as it was Signed-off-by: Christian Parpart --- .agent/reference/provenance.md | 9 + src/core/http/Body.cpp | 59 + src/core/http/Body.hpp | 123 ++ src/core/http/CMakeLists.txt | 34 +- src/core/http/Connection.cpp | 1054 +++++++++++ src/core/http/Connection.hpp | 189 ++ src/core/http/ConnectionLoopback_test.cpp | 429 +++++ src/core/http/Connection_test.cpp | 2098 +++++++++++++++++++++ src/core/http/HttpTestSupport.hpp | 120 ++ src/core/http/posix/HttpTestSupport.cpp | 14 + src/core/http/windows/HttpTestSupport.cpp | 19 + 11 files changed, 4142 insertions(+), 6 deletions(-) create mode 100644 src/core/http/Body.cpp create mode 100644 src/core/http/Body.hpp create mode 100644 src/core/http/Connection.cpp create mode 100644 src/core/http/Connection.hpp create mode 100644 src/core/http/ConnectionLoopback_test.cpp create mode 100644 src/core/http/Connection_test.cpp create mode 100644 src/core/http/HttpTestSupport.hpp create mode 100644 src/core/http/posix/HttpTestSupport.cpp create mode 100644 src/core/http/windows/HttpTestSupport.cpp diff --git a/.agent/reference/provenance.md b/.agent/reference/provenance.md index fa53e801..dc520622 100644 --- a/.agent/reference/provenance.md +++ b/.agent/reference/provenance.md @@ -230,15 +230,24 @@ others in notes. | `src/core/fs/windows/WindowsPathWalk.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the Windows component walker and the NT seam | | `src/core/fs/windows/WindowsPathWalk.hpp` | origin: core-cpp | - | - | 0.24.0 (P13) | | `src/core/fs/windows/WindowsPathWalk_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/http/Body.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/http/Body.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): `IBodyReader`, `IBodySource`, `BufferBodySource`, `framingFor` | | `src/core/http/CMakeLists.txt` | origin: core-cpp | - | - | 0.24.0 (P13): the module and its test binary | +| `src/core/http/Connection.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the role, socket-error and write-framing row tables; one read buffer per connection | +| `src/core/http/Connection.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): `Connection`, `WireTimeouts` (zero is none), `Reuse` | +| `src/core/http/ConnectionLoopback_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): deadlines and cancellation over a real pair on every backend | +| `src/core/http/Connection_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): both ends over an in-memory pair on a `TestLoop` | | `src/core/http/Framing.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the RFC 9112 section 6.3 row table, the head parser and the chunked codec's transition table | | `src/core/http/Framing.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): limits, body framing, `HeadParser`, `ChunkedDecoder` | | `src/core/http/Framing_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the smuggling corpus, whole and one byte at a time; the framing tables; the parsers' bounds | +| `src/core/http/HttpTestSupport.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): test-only helpers the http cases share | | `src/core/http/Message.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | | `src/core/http/Message.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): one `HttpErrorCode` per WASI 0.3 `wasi:http` `error-code` case, the validating field, method, target and reason factories | | `src/core/http/Message_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | | `src/core/http/SmugglingCorpus.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): test-only request-smuggling corpus, shared with the server's tests | | `src/core/http/detail/Syntax.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): the RFC 9110/3986 character-class table both parsers and the factories share | +| `src/core/http/posix/HttpTestSupport.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): test-only; `runsUnderWine` is false | +| `src/core/http/windows/HttpTestSupport.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): test-only; `runsUnderWine` from ntdll's `wine_get_version` | | `src/core/SystemRandomSource.hpp` | origin: core-cpp | - | - | the platform half of `Random.hpp`: one `fillFromSystemRandom()` per platform | | `src/core/log/Assert.hpp` | contour-terminal/contour | `src/crispy/Assert.hpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | `fatal()`/`SoftRequire()` moved here from crispy's `Assert.hpp` to close a base→log layering cycle; `Require`/`Guarantee`/`todo`/`unreachable`/`setFailHandler` stay in `src/core/Assert.hpp` | | `src/core/log/CMakeLists.txt` | origin: core-cpp | - | - | - | diff --git a/src/core/http/Body.cpp b/src/core/http/Body.cpp new file mode 100644 index 00000000..2a3fde35 --- /dev/null +++ b/src/core/http/Body.cpp @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: Apache-2.0 +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace core::http +{ + +BufferBodySource::BufferBodySource(std::string bytes, Fields trailers): + _bytes { std::move(bytes) }, + _length { _bytes.size() }, + _trailers { std::move(trailers) }, + _trailerIntent { _trailers.entries().empty() ? TrailerIntent::None : TrailerIntent::Possible } +{ +} + +std::optional BufferBodySource::knownLength() const noexcept +{ + return _length; +} + +TrailerIntent BufferBodySource::trailerIntent() const noexcept +{ + return _trailerIntent; +} + +async::Task> BufferBodySource::next() +{ + auto chunk = BodyChunk { .bytes = std::vector(_bytes.size()), .end = BodyEnd::Reached }; + std::ranges::transform( + _bytes, chunk.bytes.begin(), [](char octet) { return static_cast(octet); }); + _bytes.clear(); + co_return chunk; +} + +async::Task> BufferBodySource::trailers() +{ + co_return std::move(_trailers); +} + +Framing framingFor(IBodySource const* source) +{ + if (source == nullptr) + return Framing {}; + auto const length = source->knownLength(); + if (length.has_value() && source->trailerIntent() == TrailerIntent::None) + return Framing { .kind = BodyFraming::Length, + .length = *length, + .persistence = Persistence::KeepAlive }; + return Framing { .kind = BodyFraming::Chunked, .length = 0, .persistence = Persistence::KeepAlive }; +} + +} // namespace core::http diff --git a/src/core/http/Body.hpp b/src/core/http/Body.hpp new file mode 100644 index 00000000..0381125c --- /dev/null +++ b/src/core/http/Body.hpp @@ -0,0 +1,123 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// Message bodies as streams: what a reader hands out from a connection, what a writer is fed +/// from, and how a body's shape picks its framing. A body is never held whole by the connection; a +/// reader hands out at most @c HttpLimits::maxReadChunk at a time, and a writer takes what its +/// source hands it one chunk at a time. + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace core::http +{ + +/// Whether a body has more to come after a chunk. +enum class BodyEnd : std::uint8_t +{ + More, ///< More of the body follows. + Reached, ///< This chunk is the body's last; its trailers, if any, can be read now. +}; + +/// Whether a body source may have trailers to send once its bytes are done. +enum class TrailerIntent : std::uint8_t +{ + None, ///< It has none; a known length can then frame it by Content-Length. + Possible, ///< It may have some, which only the chunked coding can carry. +}; + +/// One piece of a body, owned by whoever holds it. +struct BodyChunk +{ + std::vector bytes; ///< The body bytes; may be empty, at the end in particular. + BodyEnd end = BodyEnd::More; ///< Whether this is the body's last chunk. +}; + +/// A message body as it arrives, read from the connection a chunk at a time. +class IBodyReader +{ + public: + IBodyReader() = default; + virtual ~IBodyReader() = default; + IBodyReader(IBodyReader const&) = delete; + IBodyReader& operator=(IBodyReader const&) = delete; + IBodyReader(IBodyReader&&) = delete; + IBodyReader& operator=(IBodyReader&&) = delete; + + /// Reads the next piece of the body. + /// @param maxBytes The most bytes wanted; clamped to @c HttpLimits::maxReadChunk, so a caller + /// cannot make the host hold more than that. Zero reads nothing and reports where the + /// body is. + /// @return Between none and @p maxBytes bytes, with @c BodyEnd::Reached on the last; every read + /// after that answers an empty @c Reached chunk. Or the failure, which ends the body. + [[nodiscard]] virtual async::Task> read(std::size_t maxBytes) = 0; + + /// The trailer fields, held to the connection's @c HttpLimits. Requires @c BodyEnd::Reached. + /// @return The trailers; empty for a body that was not chunked or sent none. + [[nodiscard]] virtual async::Task> trailers() = 0; +}; + +/// A message body as it is sent, which the connection pulls a chunk at a time. +class IBodySource +{ + public: + IBodySource() = default; + virtual ~IBodySource() = default; + IBodySource(IBodySource const&) = delete; + IBodySource& operator=(IBodySource const&) = delete; + IBodySource(IBodySource&&) = delete; + IBodySource& operator=(IBodySource&&) = delete; + + /// @return The body's length if the source knows it before sending, which a Length framing needs. + [[nodiscard]] virtual std::optional knownLength() const noexcept = 0; + + /// @return Whether trailers may follow the body. + [[nodiscard]] virtual TrailerIntent trailerIntent() const noexcept = 0; + + /// The next piece of the body. Not called again after a @c BodyEnd::Reached chunk. + /// @return The chunk, or the failure that ends the body. + [[nodiscard]] virtual async::Task> next() = 0; + + /// The trailers, asked for once after the last chunk when @c trailerIntent is + /// @c TrailerIntent::Possible. + /// @return The trailers; none of them may be a framing field (@c isFramingField). + [[nodiscard]] virtual async::Task> trailers() = 0; +}; + +/// A body already in memory: handed out as one chunk, with its trailers. +class CORE_HTTP_API BufferBodySource final: public IBodySource +{ + public: + /// @param bytes The whole body. + /// @param trailers The trailers; none means @c TrailerIntent::None, so a known length frames it. + explicit BufferBodySource(std::string bytes, Fields trailers = {}); + + [[nodiscard]] std::optional knownLength() const noexcept override; + [[nodiscard]] TrailerIntent trailerIntent() const noexcept override; + [[nodiscard]] async::Task> next() override; + [[nodiscard]] async::Task> trailers() override; + + private: + std::string _bytes; + std::uint64_t _length; + Fields _trailers; + TrailerIntent _trailerIntent; +}; + +/// The framing a body is sent with: a known length and no trailers is @c BodyFraming::Length, +/// anything else @c BodyFraming::Chunked, and no source at all @c BodyFraming::None. The +/// persistence is always @c Persistence::KeepAlive; the caller closes where it means to. +/// @param source The body, or null for none. +/// @return The framing. +[[nodiscard]] CORE_HTTP_API Framing framingFor(IBodySource const* source); + +} // namespace core::http diff --git a/src/core/http/CMakeLists.txt b/src/core/http/CMakeLists.txt index 037d8beb..c663a068 100644 --- a/src/core/http/CMakeLists.txt +++ b/src/core/http/CMakeLists.txt @@ -1,22 +1,44 @@ # SPDX-License-Identifier: Apache-2.0 -# core::http: HTTP/1.1 (RFC 9110/9112). The pure layer here -- the message vocabulary with its -# validating factories, the framing rules of RFC 9112 section 6.3 as one row table, the incremental -# head parser and the chunked codec -- holds no socket, so every framing rule is tested from a table -# (Framing_test.cpp, over the shared SmugglingCorpus.hpp). +# core::http: HTTP/1.1 (RFC 9110/9112). The pure layer -- the message vocabulary with its validating +# factories, the framing rules of RFC 9112 section 6.3 as one row table, the incremental head parser +# and the chunked codec -- holds no socket, so every framing rule is tested from a table +# (Framing_test.cpp, over the shared SmugglingCorpus.hpp). Connection puts it on an ISocket: heads +# and streamed bodies with trailers, read through one buffer of maxReadChunk bytes. core_cpp_add_module(http KIND STATIC HEADERS + Body.hpp + Connection.hpp Framing.hpp Message.hpp SOURCES + Body.cpp + Connection.cpp Framing.cpp Message.cpp PUBLIC_LIBS core::base core::net) -# One binary: the pure layer links nothing but the module. SmugglingCorpus.hpp is the test-only -# corpus the server's cases run too. +# One binary. SmugglingCorpus.hpp is the test-only corpus the server's cases run too, and +# HttpTestSupport.hpp the helpers the cases share; Connection_test.cpp drives both ends over +# net::testing's in-memory pair on a TestLoop, so nothing in it waits on anything but the loop. core_cpp_add_test(http SOURCES + Connection_test.cpp Framing_test.cpp + HttpTestSupport.hpp Message_test.cpp SmugglingCorpus.hpp) + +# Connection over a real socket pair on every backend this platform builds: the deadlines and the +# cancellations the in-memory double cannot drive. Its own binary for the label; a deadline defect +# hangs rather than fails, so every case runs under a watchdog, and TIMEOUT is the backstop. +core_cpp_add_test(http NAME http_loopback + SOURCES + ConnectionLoopback_test.cpp + HttpTestSupport.hpp + SOURCES_POSIX + posix/HttpTestSupport.cpp + SOURCES_WINDOWS + windows/HttpTestSupport.cpp + LABELS loopback + TIMEOUT 120) diff --git a/src/core/http/Connection.cpp b/src/core/http/Connection.cpp new file mode 100644 index 00000000..f42ee202 --- /dev/null +++ b/src/core/http/Connection.cpp @@ -0,0 +1,1054 @@ +// SPDX-License-Identifier: Apache-2.0 +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace core::http +{ + +namespace +{ + + using namespace std::chrono_literals; + + // --------------------------------------------------------------------------------------------- + // What differs between the two ends: one row per role, keyed by what the end reads. + + /// The codes of one @c MessageRole, named for what this end reads and what it writes. + struct RoleRow + { + MessageRole reads; + HttpErrorCode firstByteTimeout; ///< No byte of a head arrived within WireTimeouts::firstByte. + HttpErrorCode incomplete; ///< The peer closed inside a message. + HttpErrorCode readBodySize; ///< A body read is past HttpLimits::maxBodyBytes. + HttpErrorCode writeBodySize; ///< A body written breaks its Length framing. + }; + + constexpr auto RoleRows = std::array { + RoleRow { .reads = MessageRole::Request, + .firstByteTimeout = HttpErrorCode::ConnectionReadTimeout, + .incomplete = HttpErrorCode::ProtocolError, + .readBodySize = HttpErrorCode::RequestBodySize, + .writeBodySize = HttpErrorCode::ResponseBodySize }, + RoleRow { .reads = MessageRole::Response, + .firstByteTimeout = HttpErrorCode::ResponseTimeout, + .incomplete = HttpErrorCode::ResponseIncomplete, + .readBodySize = HttpErrorCode::ResponseBodySize, + .writeBodySize = HttpErrorCode::RequestBodySize }, + }; + + [[nodiscard]] RoleRow const& rowFor(MessageRole role) + { + auto const& row = RoleRows.at(static_cast(role)); + Require(row.reads == role); + return row; + } + + // --------------------------------------------------------------------------------------------- + // Socket failures, classified once: a row per NetErrorCode, a column per direction. + + /// Which way the failed operation moved bytes. + enum class Direction : std::uint8_t + { + Read, + Write, + }; + + struct NetErrorRow + { + net::NetErrorCode net; + HttpErrorCode onRead; + HttpErrorCode onWrite; + }; + + /// Every code not listed is @c HttpErrorCode::InternalError, with the socket's words as detail. + constexpr auto NetErrorRows = std::array { + NetErrorRow { .net = net::NetErrorCode::ConnReset, + .onRead = HttpErrorCode::ConnectionTerminated, + .onWrite = HttpErrorCode::ConnectionTerminated }, + NetErrorRow { .net = net::NetErrorCode::Eof, + .onRead = HttpErrorCode::ConnectionTerminated, + .onWrite = HttpErrorCode::ConnectionTerminated }, + // A cancel from the resource: the socket was closed or its read cancelled under the call. + NetErrorRow { .net = net::NetErrorCode::Cancelled, + .onRead = HttpErrorCode::ConnectionTerminated, + .onWrite = HttpErrorCode::ConnectionTerminated }, + NetErrorRow { .net = net::NetErrorCode::BadHandle, + .onRead = HttpErrorCode::ConnectionTerminated, + .onWrite = HttpErrorCode::ConnectionTerminated }, + NetErrorRow { .net = net::NetErrorCode::Timeout, + .onRead = HttpErrorCode::ConnectionReadTimeout, + .onWrite = HttpErrorCode::ConnectionWriteTimeout }, + NetErrorRow { .net = net::NetErrorCode::ConnRefused, + .onRead = HttpErrorCode::ConnectionRefused, + .onWrite = HttpErrorCode::ConnectionRefused }, + NetErrorRow { .net = net::NetErrorCode::HostUnreach, + .onRead = HttpErrorCode::DestinationUnavailable, + .onWrite = HttpErrorCode::DestinationUnavailable }, + }; + + [[nodiscard]] HttpError fromNet(net::NetError const& error, Direction direction) + { + auto const row = std::ranges::find(NetErrorRows, error.code, &NetErrorRow::net); + auto code = HttpErrorCode::InternalError; + if (row != NetErrorRows.end()) + code = direction == Direction::Read ? row->onRead : row->onWrite; + return detail::refusal(code, error.toString()); + } + + // --------------------------------------------------------------------------------------------- + // Heads as written: the framing fields the connection adds, as one row per framing. + + /// Which kind of message a head written is. + enum class Written : std::uint8_t + { + Request, + Response, + }; + + /// Whether a framing may be written in a context. + enum class Allowed : std::uint8_t + { + No, + Yes, + }; + + /// Whether bytes follow a head written with a framing. + enum class Carries : std::uint8_t + { + NoBody, + Body, + }; + + struct FramingWriteRow + { + BodyFraming kind; + Allowed inRequest; ///< UntilClose cannot end a request: its end is the response's start. + Allowed inHttp10; ///< HTTP/1.0 has no chunked coding. + Carries carries; ///< Whether the framing announces body bytes a status may forbid. + std::string_view field; ///< The framing field; `{}` is the length. Empty for none. + }; + + constexpr auto FramingWriteRows = std::array { + FramingWriteRow { .kind = BodyFraming::None, + .inRequest = Allowed::Yes, + .inHttp10 = Allowed::Yes, + .carries = Carries::NoBody, + .field = {} }, + FramingWriteRow { .kind = BodyFraming::Length, + .inRequest = Allowed::Yes, + .inHttp10 = Allowed::Yes, + .carries = Carries::Body, + .field = "Content-Length: {}\r\n" }, + FramingWriteRow { .kind = BodyFraming::Chunked, + .inRequest = Allowed::Yes, + .inHttp10 = Allowed::No, + .carries = Carries::Body, + .field = "Transfer-Encoding: chunked\r\n" }, + FramingWriteRow { .kind = BodyFraming::UntilClose, + .inRequest = Allowed::No, + .inHttp10 = Allowed::Yes, + .carries = Carries::Body, + .field = {} }, + }; + + /// What a status lets a response's framing announce and send. + enum class StatusBody : std::uint8_t + { + Permitted, ///< Any framing, and the body it announces. + LengthOnly, ///< A Content-Length may be announced, and no body follows (304, RFC 9110 8.6). + Forbidden, ///< No framing field and no body (1xx, 204; RFC 9110 8.6, RFC 9112 6.1). + }; + + struct StatusRow + { + std::uint16_t first; + std::uint16_t last; + StatusBody body; + }; + + /// The statuses that differ from @c StatusBody::Permitted. + constexpr auto StatusRows = std::array { + StatusRow { .first = 100, .last = 199, .body = StatusBody::Forbidden }, + StatusRow { .first = 204, .last = 204, .body = StatusBody::Forbidden }, + StatusRow { .first = 304, .last = 304, .body = StatusBody::LengthOnly }, + }; + + [[nodiscard]] StatusBody statusBodyOf(std::uint16_t status) + { + auto const row = std::ranges::find_if(StatusRows, [status](StatusRow const& candidate) { + return status >= candidate.first && status <= candidate.last; + }); + return row == StatusRows.end() ? StatusBody::Permitted : row->body; + } + + /// Whether a response's body is sent as its framing announces, or not at all (a HEAD's). + enum class ReplyBody : std::uint8_t + { + AsFramed, + Suppressed, + }; + + /// Whether body bytes follow a head written. + enum class Sends : std::uint8_t + { + Nothing, ///< The framing announces no body. + Body, ///< The body the framing announces follows. + Suppressed, ///< The framing announces a body that is not sent (a HEAD's, a 304's). + }; + + /// A head's framing lines and whether a body follows them. + struct HeadPlan + { + std::string lines; + Sends sends; + }; + + [[nodiscard]] std::string_view versionText(HttpVersion version) + { + return version == HttpVersion::Http10 ? "HTTP/1.0" : "HTTP/1.1"; + } + + /// The framing fields a head of @p written gets for @p framing, and the head's empty line. + /// @param status The response's status; ignored for a request. + /// @param reply Whether the response's body is sent; ignored for a request. + [[nodiscard]] HttpResult framingLines( + Written written, HttpVersion version, std::uint16_t status, Framing framing, ReplyBody reply) + { + auto const& row = FramingWriteRows.at(static_cast(framing.kind)); + Require(row.kind == framing.kind); + if (written == Written::Request && row.inRequest == Allowed::No) + return std::unexpected( + detail::refusal(HttpErrorCode::ProtocolError, "a request cannot be framed until close")); + if (version == HttpVersion::Http10 && row.inHttp10 == Allowed::No) + return std::unexpected( + detail::refusal(HttpErrorCode::ProtocolError, "HTTP/1.0 has no chunked transfer coding")); + auto const statusBody = written == Written::Request ? StatusBody::Permitted : statusBodyOf(status); + auto const sendsBody = written == Written::Request || reply == ReplyBody::AsFramed; + if (row.carries == Carries::Body && statusBody == StatusBody::Forbidden) + return std::unexpected(detail::refusal( + HttpErrorCode::ProtocolError, std::format("a {} response has no body to frame", status))); + if (row.carries == Carries::Body && statusBody == StatusBody::LengthOnly + && framing.kind != BodyFraming::Length) + return std::unexpected( + detail::refusal(HttpErrorCode::ProtocolError, + std::format("a {} response may announce only a length", status))); + + auto plan = HeadPlan { .lines = {}, .sends = Sends::Nothing }; + if (!row.field.empty()) + plan.lines += std::vformat(row.field, std::make_format_args(framing.length)); + // A response that may have a body and has none says so, or the peer reads it until close; a + // response to HEAD announces nothing it was not given. + if (framing.kind == BodyFraming::None && written == Written::Response + && statusBody == StatusBody::Permitted && sendsBody) + plan.lines += "Content-Length: 0\r\n"; + auto const closes = + framing.persistence == Persistence::Close || framing.kind == BodyFraming::UntilClose; + if (closes && version == HttpVersion::Http11) + plan.lines += "Connection: close\r\n"; + if (!closes && version == HttpVersion::Http10) + plan.lines += "Connection: keep-alive\r\n"; + plan.lines += "\r\n"; + auto const announcesBytes = + row.carries == Carries::Body && (framing.kind != BodyFraming::Length || framing.length != 0); + if (announcesBytes) + plan.sends = statusBody == StatusBody::Permitted && sendsBody ? Sends::Body : Sends::Suppressed; + return plan; + } + + /// The caller's field lines, refusing any field the connection writes itself. + [[nodiscard]] HttpResult appendCallerFields(std::string& out, Fields const& fields) + { + for (auto const& field: fields.entries()) + { + if (isFramingField(field.name)) + return std::unexpected(detail::refusal(HttpErrorCode::ProtocolError, + "the connection writes this framing field itself", + field.name)); + out += field.name; + out += ": "; + out += field.value; + out += "\r\n"; + } + return {}; + } + + [[nodiscard]] std::span bytesOf(std::string_view text) noexcept + { + return { reinterpret_cast(text.data()), text.size() }; + } + +} // namespace + +namespace +{ + + /// Where the read side is between messages. + enum class ReadPhase : std::uint8_t + { + Idle, ///< Between messages: the last body, if any, reached its end. + HeadRead, ///< A head was read; its body has no reader yet. + InBody, ///< A body is being read. + }; + + /// Where the write side is between messages. + enum class WritePhase : std::uint8_t + { + Idle, ///< Between messages. + BodyPending, ///< A head announcing a body was written; the body has not been. + }; + + /// Whether another message may follow this exchange. Not a failure: a `Connection: close` + /// exchange still runs to its end. + enum class Persist : std::uint8_t + { + KeepAlive, ///< Nothing has ruled out another message. + LastExchange, ///< A framing or a field ends the connection after this exchange. + Finished, ///< That exchange's last message has been read: no head follows. + }; + + /// Whether one direction's byte stream is still where the protocol thinks it is. Kept per + /// direction: a peer's malformed or stalled request breaks the read side, and the write side can + /// still answer it (400, 408). + enum class Stream : std::uint8_t + { + Sound, ///< Every byte read or written is accounted for. + Broken, ///< An error, a close, or a cancelled operation; nothing further moves on it. + }; + + /// Whether the request role still owes the response to the last request read. + enum class Answer : std::uint8_t + { + Given, ///< Every request read has its final response written in full. + Pending, ///< The last request's final response is not yet written in full. + }; + + /// Whether one direction has a socket operation outstanding. Set before each await and cleared + /// only when it resumes normally, so a flow cancelled (or destroyed) mid-await leaves it Busy: the + /// message on that side is cut off at a byte nobody knows. + enum class Wire : std::uint8_t + { + Idle, + Busy, + }; + +} // namespace + +namespace detail +{ + + /// The state a @c Connection and its body readers share. + struct ConnectionState + { + net::EventLoop* loop; + std::unique_ptr socket; + MessageRole role; + HttpLimits limits; + WireTimeouts timeouts; + /// The one read buffer, @c HttpLimits::maxReadChunk bytes; [begin, end) is unread. + std::vector buffer; + std::size_t begin = 0; + std::size_t end = 0; + ReadPhase readPhase = ReadPhase::Idle; + WritePhase writePhase = WritePhase::Idle; + Persist persist = Persist::KeepAlive; + Stream readStream = Stream::Sound; + Stream writeStream = Stream::Sound; + Answer answer = Answer::Given; + Wire readWire = Wire::Idle; + Wire writeWire = Wire::Idle; + /// Whether the next response written sends its body: not after a HEAD request. + ReplyBody replyBody = ReplyBody::AsFramed; + /// The framing the last head written announced, which writeBody must follow. + Framing announced; + /// Whether that head's body is sent, announced only (a HEAD's, a 304's), or none. + Sends announcedSends = Sends::Nothing; + /// Which head's body is current; a reader of an older one answers that its body is over. + std::uint64_t generation = 0; + /// The generation a live reader belongs to. + std::optional liveReader; + Framing body; + std::uint64_t remaining = 0; + /// How much of an UntilClose body has been handed out, for maxBodyBytes. + std::uint64_t untilCloseBytes = 0; + std::optional decoder; + Fields trailers; + /// The failure that ended the current body, repeated to every later read of it. + std::optional bodyError; + + ConnectionState(net::EventLoop* ownerLoop, + std::unique_ptr ownedSocket, + MessageRole readRole, + HttpLimits readLimits, + WireTimeouts readTimeouts): + loop { ownerLoop }, + socket { std::move(ownedSocket) }, + role { readRole }, + limits { readLimits }, + timeouts { readTimeouts }, + buffer(readLimits.maxReadChunk) + { + Require(loop != nullptr && socket != nullptr); + Require(!buffer.empty()); + } + + [[nodiscard]] std::string_view buffered() const noexcept + { + return { reinterpret_cast(buffer.data()) + begin, end - begin }; + } + + void consume(std::size_t count) noexcept { begin += count; } + + /// Marks the read side broken, and hands @p error back. + [[nodiscard]] HttpError fail(HttpError error) noexcept + { + readStream = Stream::Broken; + return error; + } + + /// Marks the write side broken, and hands @p error back. + [[nodiscard]] HttpError failWrite(HttpError error) noexcept + { + writeStream = Stream::Broken; + return error; + } + + /// As @c fail, and every later read of the current body repeats @p error. + [[nodiscard]] HttpError failBody(HttpError error) + { + bodyError = error; + return fail(std::move(error)); + } + + /// Ends the current body cleanly, and with it a last exchange's read side. + void reachEnd() noexcept + { + readPhase = ReadPhase::Idle; + if (persist == Persist::LastExchange) + persist = Persist::Finished; + } + }; + +} // namespace detail + +namespace +{ + + using detail::ConnectionState; + + /// Whether a read deadline has fired. + enum class Expiry : std::uint8_t + { + Pending, + Fired, + }; + + /// What a read deadline retires, and where it records that it did. + struct ReadDeadline + { + net::ISocket* socket; + Expiry expiry = Expiry::Pending; + }; + + /// Reads into the empty buffer, bounded by @p timeout unless it is zero (R31). + /// + /// The deadline is a @c net::DeadlineTimer that retires the parked read through + /// @c ISocket::cancelRead rather than a @c net::withTimeout race, for two reasons. The socket + /// stays open, so a server whose head read timed out can still answer 408 on it; and the read + /// answers the cancel as a VALUE (@c NetErrorCode::Cancelled), so the timeout is reported where + /// the read returns rather than as an @c OperationCancelled unwinding the caller's flow. The + /// timer callback runs on the loop's thread, where @c cancelRead must be called. A read that + /// settles with bytes despite the cancel -- a completion transport's whose receive had already + /// finished -- keeps them: the data wins. A socket decorator that does not forward + /// @c cancelRead leaves the deadline with nothing to retire, and the read unbounded. + /// + /// **The read side's one guard against a cut stream.** Every head and body read reaches the + /// socket through here, and a read side found broken, or busy from a read a cancel left behind, + /// is refused before any byte moves; @c send is the write side's. + /// @return The byte count, zero for the peer's EOF, or the failure (which breaks the stream). + async::Task> fill(std::shared_ptr state, + std::chrono::milliseconds timeout, + HttpErrorCode timeoutCode) + { + if (state->readWire == Wire::Busy || state->readStream == Stream::Broken) + co_return std::unexpected(state->fail(detail::refusal( + HttpErrorCode::ConnectionTerminated, "a cancelled or failed read cut the stream off"))); + Require(state->begin == state->end); + state->begin = 0; + state->end = 0; + auto deadline = ReadDeadline { .socket = state->socket.get(), .expiry = Expiry::Pending }; + auto timer = std::optional {}; + if (timeout > 0ms) + timer.emplace( + *state->loop, + state->loop->clock().now() + timeout, + [](void* target) { + auto& fired = *static_cast(target); + fired.expiry = Expiry::Fired; // before the cancel, which may resume the reader + fired.socket->cancelRead(); + }, + &deadline); + state->readWire = Wire::Busy; + auto const result = co_await state->socket->read(std::span { state->buffer }); + state->readWire = Wire::Idle; + timer.reset(); + if (!result.has_value() && deadline.expiry == Expiry::Fired) + co_return std::unexpected(state->fail( + detail::refusal(timeoutCode, std::format("no byte arrived within {} ms", timeout.count())))); + if (!result.has_value()) + co_return std::unexpected(state->fail(fromNet(result.error(), Direction::Read))); + state->end = *result; + co_return *result; + } + + /// Whether a head read has seen any of its bytes yet. + enum class HeadProgress : std::uint8_t + { + Nothing, + Started, + }; + + /// Reads one head through a @c HeadParser, from the buffer first, then the socket. + async::Task> readHead(std::shared_ptr state) + { + if (state->readStream == Stream::Broken || state->readWire == Wire::Busy) + co_return std::unexpected( + state->fail(detail::refusal(HttpErrorCode::ConnectionTerminated, + "the stream is broken, or a cancelled read cut it off"))); + if (state->persist == Persist::Finished) + co_return std::unexpected(detail::refusal(HttpErrorCode::ConnectionTerminated, + "the connection's last exchange is over")); + if (state->answer == Answer::Pending) + co_return std::unexpected(detail::refusal( + HttpErrorCode::ProtocolError, + "the request role is serial: the last request's response is not yet written")); + Require(state->readPhase == ReadPhase::Idle); + auto const& row = rowFor(state->role); + auto parser = HeadParser { state->role, state->limits }; + auto progress = HeadProgress::Nothing; + while (true) + { + if (auto const bytes = state->buffered(); !bytes.empty()) + { + progress = HeadProgress::Started; + auto fed = parser.feed(bytes); + if (!fed.has_value()) + co_return std::unexpected(state->fail(std::move(fed.error()))); + state->consume(fed->consumed); + if (fed->progress == Progress::Complete) + { + state->readPhase = ReadPhase::HeadRead; + ++state->generation; + state->liveReader.reset(); + state->bodyError.reset(); + state->trailers = Fields {}; + co_return parser; + } + continue; + } + auto const first = progress == HeadProgress::Nothing; + auto got = co_await fill(state, + first ? state->timeouts.firstByte : state->timeouts.betweenBytes, + first ? row.firstByteTimeout : HttpErrorCode::ConnectionReadTimeout); + if (!got.has_value()) + co_return std::unexpected(std::move(got.error())); + if (*got == 0) + co_return std::unexpected( + state->fail(first ? detail::refusal(HttpErrorCode::ConnectionTerminated, + "the peer closed before a head") + : detail::refusal(row.incomplete, "the peer closed inside a head"))); + } + } + + async::Task> readRequest(std::shared_ptr state) + { + auto parser = co_await readHead(state); + if (!parser.has_value()) + co_return std::unexpected(std::move(parser.error())); + auto head = parser->takeRequest(); + state->replyBody = head.method.text() == "HEAD" ? ReplyBody::Suppressed : ReplyBody::AsFramed; + state->answer = Answer::Pending; + co_return head; + } + + async::Task> readResponse(std::shared_ptr state) + { + auto parser = co_await readHead(state); + if (!parser.has_value()) + co_return std::unexpected(std::move(parser.error())); + auto head = parser->takeResponse(); + // An interim response has no body, whatever its fields say; the final one follows it. + if (head.status < 200) + state->readPhase = ReadPhase::Idle; + co_return head; + } + + /// Copies @p bytes out of the buffer into a chunk the caller owns. + [[nodiscard]] BodyChunk chunkOf(std::string_view bytes, BodyEnd end) + { + auto chunk = BodyChunk { .bytes = std::vector(bytes.size()), .end = end }; + std::ranges::transform( + bytes, chunk.bytes.begin(), [](char octet) { return static_cast(octet); }); + return chunk; + } + + /// Reads more of a body into the empty buffer; an EOF is the role's incomplete-message code. + async::Task> fillBody(std::shared_ptr state) + { + auto got = co_await fill(state, state->timeouts.betweenBytes, HttpErrorCode::ConnectionReadTimeout); + if (!got.has_value()) + co_return std::unexpected(state->failBody(std::move(got.error()))); + if (*got == 0) + co_return std::unexpected(state->failBody( + detail::refusal(rowFor(state->role).incomplete, "the peer closed inside a body"))); + co_return {}; + } + + async::Task> readLength(std::shared_ptr state, std::size_t want) + { + if (state->buffered().empty()) + if (auto filled = co_await fillBody(state); !filled.has_value()) + co_return std::unexpected(std::move(filled.error())); + auto const take = static_cast( + std::min({ want, state->remaining, state->buffered().size() })); + auto const bytes = state->buffered().substr(0, take); + state->consume(take); + state->remaining -= take; + if (state->remaining == 0) + state->reachEnd(); + co_return chunkOf(bytes, state->remaining == 0 ? BodyEnd::Reached : BodyEnd::More); + } + + async::Task> readUntilClose(std::shared_ptr state, + std::size_t want) + { + if (state->buffered().empty()) + { + auto got = + co_await fill(state, state->timeouts.betweenBytes, HttpErrorCode::ConnectionReadTimeout); + if (!got.has_value()) + co_return std::unexpected(state->failBody(std::move(got.error()))); + if (*got == 0) + { + state->reachEnd(); + co_return BodyChunk { .bytes = {}, .end = BodyEnd::Reached }; + } + } + auto const bytes = state->buffered().substr(0, want); + if (auto const limit = state->limits.maxBodyBytes; + limit.has_value() && state->untilCloseBytes + bytes.size() > *limit) + co_return std::unexpected( + state->failBody(detail::refusal(rowFor(state->role).readBodySize, + "the body is past maxBodyBytes", + std::nullopt, + state->untilCloseBytes + bytes.size()))); + state->untilCloseBytes += bytes.size(); + state->consume(bytes.size()); + co_return chunkOf(bytes, BodyEnd::More); + } + + async::Task> readChunked(std::shared_ptr state, std::size_t want) + { + while (true) + { + if (auto const bytes = state->buffered(); !bytes.empty()) + { + // At most `want` bytes go in, so no more than that comes out as data. + auto step = state->decoder->feed(bytes.substr(0, want)); + if (!step.has_value()) + co_return std::unexpected(state->failBody(std::move(step.error()))); + auto chunk = chunkOf(step->data, BodyEnd::More); + state->consume(step->consumed); + if (!chunk.bytes.empty()) + co_return chunk; + if (step->progress == Progress::Complete) + { + state->trailers = state->decoder->takeTrailers(); + state->reachEnd(); + co_return BodyChunk { .bytes = {}, .end = BodyEnd::Reached }; + } + continue; + } + if (auto filled = co_await fillBody(state); !filled.has_value()) + co_return std::unexpected(std::move(filled.error())); + } + } + + /// A body of the connection: a view of its shared state, for one head's body. + class BodyReader final: public IBodyReader + { + public: + BodyReader(std::shared_ptr state, std::uint64_t generation): + _state { std::move(state) }, _generation { generation } + { + _state->liveReader = _generation; + } + + ~BodyReader() override + { + if (_state->liveReader == _generation) + _state->liveReader.reset(); + } + + BodyReader(BodyReader const&) = delete; + BodyReader& operator=(BodyReader const&) = delete; + BodyReader(BodyReader&&) = delete; + BodyReader& operator=(BodyReader&&) = delete; + + [[nodiscard]] async::Task> read(std::size_t maxBytes) override + { + return readBody(_state, _generation, maxBytes); + } + + [[nodiscard]] async::Task> trailers() override + { + return trailersOf(_state, _generation); + } + + private: + [[nodiscard]] static async::Task> readBody( + std::shared_ptr state, std::uint64_t generation, std::size_t maxBytes) + { + if (generation != state->generation) + co_return BodyChunk { .bytes = {}, .end = BodyEnd::Reached }; + if (state->bodyError.has_value()) + co_return std::unexpected(*state->bodyError); + if (state->readPhase != ReadPhase::InBody) + co_return BodyChunk { .bytes = {}, .end = BodyEnd::Reached }; + // No explicit clamp to maxReadChunk: every framing hands out at most what the buffer + // holds, and the buffer is maxReadChunk bytes, so that is the bound (D3). + auto const want = maxBytes; + if (want == 0) + co_return BodyChunk { .bytes = {}, .end = BodyEnd::More }; + switch (state->body.kind) + { + case BodyFraming::Length: co_return co_await readLength(state, want); + case BodyFraming::Chunked: co_return co_await readChunked(state, want); + case BodyFraming::UntilClose: co_return co_await readUntilClose(state, want); + case BodyFraming::None: break; // never in ReadPhase::InBody: bodyReader ends it at once + } + co_return BodyChunk { .bytes = {}, .end = BodyEnd::Reached }; + } + + [[nodiscard]] static async::Task> trailersOf( + std::shared_ptr state, std::uint64_t generation) + { + if (generation != state->generation) + co_return Fields {}; + if (state->bodyError.has_value()) + co_return std::unexpected(*state->bodyError); + Require(state->readPhase != ReadPhase::InBody); // trailers() before BodyEnd::Reached + co_return std::move(state->trailers); + } + + std::shared_ptr _state; + std::uint64_t _generation; + }; + + /// Writes @p segments in full, as one gather write, bounded by WireTimeouts::write unless it is + /// zero. The deadline closes the socket (@c net::armSocketDeadline): a write cut off mid-message + /// leaves a stream nothing can resynchronise. Like @c fill for the read side, it is the write side's + /// one guard: every head and body write passes it, and a write side found broken, or busy from a + /// write a cancel left behind, is refused before any byte moves. + async::Task> send(std::shared_ptr state, + std::span const> segments) + { + if (state->writeWire == Wire::Busy || state->writeStream == Stream::Broken) + co_return std::unexpected(state->failWrite(detail::refusal( + HttpErrorCode::ConnectionTerminated, "a cancelled or failed write cut the stream off"))); + auto target = net::SocketDeadlineTarget { .socket = state->socket.get(), .expired = false }; + auto const deadline = net::armSocketDeadline(state->loop, state->timeouts.write, &target); + state->writeWire = Wire::Busy; + auto const wrote = co_await state->socket->writeVectored(segments); + state->writeWire = Wire::Idle; + if (!wrote.has_value() && target.expired) + co_return std::unexpected(state->failWrite(detail::refusal( + HttpErrorCode::ConnectionWriteTimeout, + std::format("a write did not finish within {} ms", state->timeouts.write.count())))); + if (!wrote.has_value()) + co_return std::unexpected(state->failWrite(fromNet(wrote.error(), Direction::Write))); + co_return {}; + } + + /// Writes one head: @p startLine, the caller's fields, and the framing fields, in one write. + async::Task> writeHead(std::shared_ptr state, + Written written, + std::string startLine, + Fields fields, + HttpVersion version, + std::uint16_t status, + Framing framing) + { + Require(state->writePhase == WritePhase::Idle); // the last head's body is written first + auto head = std::move(startLine); + // Refused before the first wire byte: the connection is left as it was, so the caller may + // send a corrected head (a handler's 500 after its own bad one). Nothing above changes state. + if (auto appended = appendCallerFields(head, fields); !appended.has_value()) + co_return std::unexpected(std::move(appended.error())); + auto const reply = written == Written::Response ? state->replyBody : ReplyBody::AsFramed; + auto plan = framingLines(written, version, status, framing, reply); + if (!plan.has_value()) + co_return std::unexpected(std::move(plan.error())); + auto const segments = std::array { bytesOf(head), bytesOf(plan->lines) }; + if (auto sent = co_await send(state, segments); !sent.has_value()) + co_return sent; + auto const answers = written == Written::Response && status >= 200; + if (answers) + state->replyBody = ReplyBody::AsFramed; // the HEAD request is answered; a 1xx does not answer it + state->announced = framing; + state->announcedSends = plan->sends; + state->writePhase = plan->sends == Sends::Body ? WritePhase::BodyPending : WritePhase::Idle; + if (answers && state->writePhase == WritePhase::Idle) + state->answer = Answer::Given; + if ((framing.persistence == Persistence::Close || framing.kind == BodyFraming::UntilClose) + && state->persist == Persist::KeepAlive) // never undoes Finished + state->persist = Persist::LastExchange; + co_return {}; + } + + /// Whether a framing holds the body to an exact count, and to which. + [[nodiscard]] std::optional exactLength(Framing framing) + { + if (framing.kind == BodyFraming::None) + return std::uint64_t { 0 }; + if (framing.kind == BodyFraming::Length) + return framing.length; + return std::nullopt; + } + + async::Task> writeBodyOf(std::shared_ptr state, + IBodySource* source, + Framing framing) + { + auto const announced = std::exchange(state->announced, Framing {}); + auto const sends = std::exchange(state->announcedSends, Sends::Nothing); + if (framing.kind != announced.kind || framing.length != announced.length) + co_return std::unexpected(state->failWrite(detail::refusal( + HttpErrorCode::ProtocolError, "the body's framing is not the one its head announced"))); + if (sends == Sends::Suppressed) + { + // Announced only: a response to HEAD, or a 304. Nothing follows the head. + state->writePhase = WritePhase::Idle; + state->answer = Answer::Given; + co_return {}; + } + auto const sizeCode = rowFor(state->role).writeBodySize; + auto const exact = exactLength(framing); + auto const intent = source != nullptr ? source->trailerIntent() : TrailerIntent::None; + if (intent == TrailerIntent::Possible && framing.kind != BodyFraming::Chunked) + co_return std::unexpected(state->failWrite( + detail::refusal(HttpErrorCode::ProtocolError, "trailers need the chunked framing"))); + if (auto const known = source != nullptr ? source->knownLength() : std::optional { 0 }; + exact.has_value() && known.has_value() && *known != *exact) + co_return std::unexpected(state->failWrite( + detail::refusal(sizeCode, + std::format("a body of {} bytes under a length of {}", *known, *exact), + std::nullopt, + known))); + + auto written = std::uint64_t { 0 }; + auto end = source != nullptr ? BodyEnd::More : BodyEnd::Reached; + while (end == BodyEnd::More) + { + auto chunk = co_await source->next(); + if (!chunk.has_value()) + co_return std::unexpected(state->failWrite(std::move(chunk.error()))); + end = chunk->end; + auto const bytes = std::span { chunk->bytes }; + if (exact.has_value() && written + bytes.size() > *exact) + co_return std::unexpected(state->failWrite( + detail::refusal(sizeCode, + std::format("the body runs past its length of {}", *exact), + std::nullopt, + written + bytes.size()))); + if (bytes.empty()) + continue; + written += bytes.size(); + if (framing.kind == BodyFraming::Chunked) + { + auto const header = chunkHeader(bytes.size()); + auto const segments = std::array { bytesOf(header), bytes, bytesOf("\r\n") }; + if (auto sent = co_await send(state, segments); !sent.has_value()) + co_return sent; + } + else + { + auto const segments = std::array { bytes }; + if (auto sent = co_await send(state, segments); !sent.has_value()) + co_return sent; + } + } + if (exact.has_value() && written != *exact) + co_return std::unexpected(state->failWrite( + detail::refusal(sizeCode, + std::format("the body ends short of its length of {}", *exact), + std::nullopt, + written))); + + if (framing.kind == BodyFraming::Chunked) + { + auto trailers = Fields {}; + if (intent == TrailerIntent::Possible) + { + auto given = co_await source->trailers(); + if (!given.has_value()) + co_return std::unexpected(state->failWrite(std::move(given.error()))); + trailers = std::move(*given); + } + for (auto const& field: trailers.entries()) + if (isFramingField(field.name)) + co_return std::unexpected(state->failWrite(detail::refusal( + HttpErrorCode::ProtocolError, "a trailer cannot be a framing field", field.name))); + auto const last = lastChunk(trailers); + auto const segments = std::array { bytesOf(last) }; + if (auto sent = co_await send(state, segments); !sent.has_value()) + co_return sent; + } + state->writePhase = WritePhase::Idle; + state->answer = Answer::Given; // a body written is a final response's: a 1xx has none + co_return {}; + } + +} // namespace + +Connection::Connection(net::EventLoop& loop, + std::unique_ptr socket, + MessageRole role, + HttpLimits limits, + WireTimeouts timeouts): + _state { std::make_shared(&loop, std::move(socket), role, limits, timeouts) } +{ +} + +Connection::~Connection() = default; +Connection::Connection(Connection&&) noexcept = default; +Connection& Connection::operator=(Connection&&) noexcept = default; + +async::Task> Connection::readRequestHead() +{ + Require(_state != nullptr && _state->role == MessageRole::Request); + return readRequest(_state); +} + +async::Task> Connection::readResponseHead() +{ + Require(_state != nullptr && _state->role == MessageRole::Response); + return readResponse(_state); +} + +std::unique_ptr Connection::bodyReader(Framing framing) +{ + Require(_state != nullptr && !hasLiveBodyReader()); + auto& state = *_state; + if (state.readPhase == ReadPhase::HeadRead) + { + state.body = framing; + state.remaining = framing.kind == BodyFraming::Length ? framing.length : 0; + // Emplaced or reset, never reset and then emplaced: GCC 15 reads the reset that emplace + // makes again as a destruction of fields it calls maybe uninitialized. + if (framing.kind == BodyFraming::Chunked) + state.decoder.emplace(state.role, state.limits); + else + state.decoder.reset(); + state.untilCloseBytes = 0; + if ((framing.persistence == Persistence::Close || framing.kind == BodyFraming::UntilClose) + && state.persist == Persist::KeepAlive) + state.persist = Persist::LastExchange; + auto const empty = + framing.kind == BodyFraming::None || (framing.kind == BodyFraming::Length && framing.length == 0); + state.readPhase = ReadPhase::InBody; + if (empty) + state.reachEnd(); + if (framing.kind == BodyFraming::Length && state.limits.maxBodyBytes.has_value() + && framing.length > *state.limits.maxBodyBytes) + std::ignore = state.failBody(detail::refusal(rowFor(state.role).readBodySize, + "the declared length is past maxBodyBytes", + std::nullopt, + framing.length)); + } + else if (state.readPhase == ReadPhase::InBody) + Require(framing.kind == state.body.kind && framing.length == state.body.length); // the same body + return std::make_unique(_state, state.generation); +} + +bool Connection::hasLiveBodyReader() const noexcept +{ + return _state != nullptr && _state->liveReader == _state->generation; +} + +async::Task> Connection::writeRequestHead(RequestHead head, Framing framing) +{ + Require(_state != nullptr && _state->role == MessageRole::Response); + auto startLine = + std::format("{} {} {}\r\n", head.method.text(), head.target.text(), versionText(head.version)); + return writeHead( + _state, Written::Request, std::move(startLine), std::move(head.fields), head.version, 0, framing); +} + +async::Task> Connection::writeResponseHead(ResponseHead head, Framing framing) +{ + Require(_state != nullptr && _state->role == MessageRole::Request); + auto startLine = std::format("{} {} {}\r\n", versionText(head.version), head.status, head.reason.text()); + return writeHead(_state, + Written::Response, + std::move(startLine), + std::move(head.fields), + head.version, + head.status, + framing); +} + +async::Task> Connection::writeBody(IBodySource* source, Framing framing) +{ + Require(_state != nullptr); + return writeBodyOf(_state, source, framing); +} + +Reuse Connection::reusable() const noexcept +{ + if (_state == nullptr) + return Reuse::No; + auto const& state = *_state; + auto const clean = state.readStream == Stream::Sound && state.writeStream == Stream::Sound + && state.persist == Persist::KeepAlive && !state.socket->isClosed() + && state.readPhase == ReadPhase::Idle && state.writePhase == WritePhase::Idle + && state.readWire == Wire::Idle && state.writeWire == Wire::Idle; + return clean ? Reuse::Yes : Reuse::No; +} + +net::ISocket& Connection::socket() noexcept +{ + Require(_state != nullptr); + return *_state->socket; +} + +void Connection::close() noexcept +{ + if (_state == nullptr) + return; + _state->readStream = Stream::Broken; + _state->writeStream = Stream::Broken; + _state->socket->close(); +} + +} // namespace core::http diff --git a/src/core/http/Connection.hpp b/src/core/http/Connection.hpp new file mode 100644 index 00000000..4c3776cc --- /dev/null +++ b/src/core/http/Connection.hpp @@ -0,0 +1,189 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// One HTTP/1.1 connection over an @c net::ISocket: heads and bodies read through the pure layer +/// (@c HeadParser, @c ChunkedDecoder) out of one read buffer of @c HttpLimits::maxReadChunk bytes, +/// heads and bodies written with the framing fields the connection adds itself, and whether the +/// connection may carry another message. The same type serves both ends; its @c MessageRole is what +/// it reads, which selects the error codes. + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace core::http +{ + +namespace detail +{ + struct ConnectionState; +} // namespace detail + +/// Whether a connection may carry another message. +enum class Reuse : std::uint8_t +{ + Yes, ///< The last exchange ended cleanly and both ends keep the connection. + No, ///< It must be closed. +}; + +/// The deadlines of a connection, on its loop's clock. +/// +/// **A zero duration means no deadline** (R31): that wait is not bounded by the connection at all, +/// rather than bounded by a deadline that fires at once. +/// +/// A read deadline retires the parked read through @c net::ISocket::cancelRead and leaves the +/// socket open, so a server can still answer 408; **a socket decorator that does not forward +/// `cancelRead` therefore disables the read deadlines.** A write deadline closes the socket, since a +/// write cut off mid-message leaves nothing worth keeping it open for. +struct WireTimeouts +{ + /// From the start of a head read to its first byte. In the response role this is the response + /// timeout (@c HttpErrorCode::ResponseTimeout); in the request role it is the idle time a client + /// may take before its next request (@c HttpErrorCode::ConnectionReadTimeout). + std::chrono::milliseconds firstByte { 0 }; + /// Between any two reads after that, the body's included (@c HttpErrorCode::ConnectionReadTimeout). + std::chrono::milliseconds betweenBytes { 0 }; + /// Each write, a head's or a body chunk's, to its last byte (@c HttpErrorCode::ConnectionWriteTimeout). + /// A peer that stops reading stalls a write at most this long. + std::chrono::milliseconds write { 0 }; +}; + +/// One HTTP/1.1 connection, either end. +/// +/// It holds one read and one write operation at a time, as the socket does: a head read and a body +/// read share the read side, and a head write and a body write the write side, so one read flow +/// and one write flow may run at once. A body reader shares the connection's state and may outlive +/// the @c Connection. Every failure, the peer's or the socket's, leaves the connection +/// @c Reuse::No, and so does a flow cancelled while it waited on the socket, whose message is cut +/// off at an unknown byte. Loop-affine: every call is made on the loop's thread. +/// +/// **The read side runs head, reader, head.** After every head read the caller frames it and asks +/// @c bodyReader for its body, a @c BodyFraming::None one included, before the next head read; only +/// an interim (1xx) response head needs none. Reading a head while the last one's body is unread +/// is a contract violation (`Require`), since the connection cannot know where that body ends. +/// A connection that announced or received @c Persistence::Close still finishes its exchange: a +/// client that sent `Connection: close` reads the response; only the next message is ruled out, +/// and a head read after that exchange's last message answers @c ConnectionTerminated. +/// +/// **The request role is serial.** A server reads request N+1's head only once response N is +/// written in full; asked earlier, the head read answers @c ProtocolError, as a value and without +/// consuming a byte, so the caller may answer and ask again. HTTP/1.1 lets a server answer +/// pipelined requests one at a time, and a WASI handler serves one request per connection at a +/// time, so the connection keeps one request's state (whether it was HEAD) rather than a queue. +/// +/// **Failures are kept per direction.** A failure on the read side -- a refused head, a read +/// timeout, a cancelled read -- leaves the write side free to answer (400, 408); a failure on the +/// write side stops further writes. **A refusal before the first wire byte leaves the connection as +/// it was; a failure after it breaks that direction:** a head refused for a caller framing field or +/// a framing its status cannot carry may be followed by a corrected head, while every failure of a +/// body write, and of any write once it reached the socket, ends the write side. A flow cancelled while it +/// waited on the socket breaks its side for good: the next operation on that side, a retry included, is +/// refused with +/// @c ConnectionTerminated. +class CORE_HTTP_API Connection +{ + public: + /// @param loop The loop whose clock the deadlines are measured on (not owned; outlives this and + /// every body reader). + /// @param socket The connected socket, owned from now on. + /// @param role What this end READS: Response on a client, Request on a server; selects the + /// error codes. + /// @param limits The bounds every message read is held to; its @c maxReadChunk is also the read + /// buffer's size, the most the connection ever holds of a peer's bytes. + /// @param timeouts The read deadlines; zero is none. + Connection(net::EventLoop& loop, + std::unique_ptr socket, + MessageRole role, + HttpLimits limits, + WireTimeouts timeouts); + ~Connection(); + Connection(Connection const&) = delete; + Connection& operator=(Connection const&) = delete; + Connection(Connection&&) noexcept; + Connection& operator=(Connection&&) noexcept; + + /// Reads the next request head. Requires the request role, and that the previous body has been + /// read to its end. A HEAD request makes the response written next bodiless whatever its + /// framing announces. + /// @return The head, or the failure: the role's limit and syntax codes, @c ProtocolError for a + /// close inside the head, @c ConnectionTerminated for one before its first byte, and + /// @c ConnectionReadTimeout. + [[nodiscard]] async::Task> readRequestHead(); + + /// Reads the next response head. Requires the response role, and that the previous body has + /// been read to its end. + /// @return The head, or the failure: as @c readRequestHead, with @c ResponseIncomplete for a close + /// inside the head and @c ResponseTimeout before its first byte. + [[nodiscard]] async::Task> readResponseHead(); + + /// A reader of the body that follows the last head read, framed by @p framing (from + /// @c requestFraming or @c responseFraming). It shares the connection state; one at a time. A + /// reader dropped before the end leaves the rest unread, and a later reader with the same + /// framing continues where it stopped. A Length body past @c HttpLimits::maxBodyBytes fails its + /// first read with the role's body-size code. + /// @param framing The body's framing; adopted with the first reader after a head. + /// @return The reader. + [[nodiscard]] std::unique_ptr bodyReader(Framing framing); + + /// Whether a body reader of this connection is alive. A @c bool because the name asks it. + [[nodiscard]] bool hasLiveBodyReader() const noexcept; + + /// Writes a request head, one @c writeVectored. Adds the framing fields itself; a + /// caller-supplied framing field (@c isFramingField) is refused (ProtocolError) before a byte + /// is written, as are @c BodyFraming::UntilClose and chunked in HTTP/1.0. Requires the response + /// role, whose end writes requests. + /// @param head The head. + /// @param framing The framing @c writeBody will follow. + /// @return Nothing, or the failure. + [[nodiscard]] async::Task> writeRequestHead(RequestHead head, Framing framing); + + /// Writes a response head, one @c writeVectored, as @c writeRequestHead does. A 1xx or 204 refuses + /// a body framing and gets no framing field; a 304 may announce a Length (RFC 9110 section 8.6) + /// and sends no body; any other status with @c BodyFraming::None is sent `Content-Length: 0`, and + /// @c BodyFraming::UntilClose is sent `Connection: close`. The response to a HEAD request + /// announces its framing as given and sends no body (RFC 9110 section 9.3.2), so @c writeBody + /// after it writes nothing. Requires the request role, and no body still pending from the last + /// head written. + /// @param head The head. + /// @param framing The framing @c writeBody will follow. + /// @return Nothing, or the failure. + [[nodiscard]] async::Task> writeResponseHead(ResponseHead head, Framing framing); + + /// Writes a body, pulling it from @p source a chunk at a time, framed by @p framing. + /// + /// A body longer or shorter than a Length framing is RequestBodySize/ResponseBodySize (by what + /// this end writes) and Reuse::No, and no byte past the length is written: a known length that + /// differs is refused before any body byte, and a streamed one at the chunk that would pass it. + /// Trailers need @c BodyFraming::Chunked and may hold no framing field (ProtocolError). An + /// @c BodyFraming::UntilClose body ends when the caller closes. @p framing must be the one the + /// last head written announced (ProtocolError otherwise); without a head, only none. + /// @param source The body (not owned; outlives the call), or null for none. + /// @param framing The framing the head announced. + /// @return Nothing, or the failure. + [[nodiscard]] async::Task> writeBody(IBodySource* source, Framing framing); + + /// No after UntilClose, Persistence::Close, an error, a close, a flow cancelled while it waited + /// on the socket, or an unread body (a head read whose body has not reached its end, or a head + /// written whose body has not been written). + [[nodiscard]] Reuse reusable() const noexcept; + + /// The socket, for its endpoints and TLS session. Requires a connection not moved from. + [[nodiscard]] net::ISocket& socket() noexcept; + + /// Closes the socket; the connection is @c Reuse::No from now on. + void close() noexcept; + + private: + std::shared_ptr _state; +}; + +} // namespace core::http diff --git a/src/core/http/ConnectionLoopback_test.cpp b/src/core/http/ConnectionLoopback_test.cpp new file mode 100644 index 00000000..063ef290 --- /dev/null +++ b/src/core/http/ConnectionLoopback_test.cpp @@ -0,0 +1,429 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// `Connection` over a real socket pair on every backend this platform builds: the deadlines, which +// the in-memory cases can only drive through the double's own `cancelRead`, and cancellation, which +// that double does not model at all. Every case bounds its whole flow with a watchdog, so a deadline +// that never fires fails the case in seconds instead of hanging it. +#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 + +using core::async::Task; +using core::http::BodyFraming; +using core::http::BufferBodySource; +using core::http::Connection; +using core::http::Framing; +using core::http::HttpErrorCode; +using core::http::HttpLimits; +using core::http::HttpResult; +using core::http::MessageRole; +using core::http::Method; +using core::http::RequestHead; +using core::http::RequestTarget; +using core::http::ResponseHead; +using core::http::Reuse; +using core::http::WireTimeouts; +using core::http::test::into; +using core::http::test::readAll; +using core::http::test::ReadBody; +using core::http::test::textOf; +using core::net::EventLoop; +using core::net::ISocket; +using core::net::testing::BackendMatrix; + +using namespace std::chrono_literals; + +namespace +{ + +/// The watchdog over each case's flow: two orders of magnitude over the deadlines below. +constexpr auto Watchdog = 10s; + +/// Long enough that a loaded runner does not deliver what the case never sent first. +constexpr auto Deadline = 50ms; + +/// The kernel buffers each end of a pair is asked for, so a little data fills them. +constexpr auto SmallBuffer = std::uint64_t { 4096 }; + +/// Many times what two `SmallBuffer`-sized kernel buffers hold (the kernel may round them up), so a +/// peer that does not read stalls a writer. +constexpr auto Flood = std::size_t { 4 } * 1024 * 1024; + +/// Asserts that a write against a peer that never reads stalled. Wine's IOCP sockets take the whole +/// flood whatever the buffer sizes, so there the case could not run and says so; on a native +/// kernel a write that finished is the defect this case exists to find. +/// @param finished Whether the write ran to its end. +void expectStalled(bool finished) +{ + if (finished && core::http::test::runsUnderWine()) + SKIP("wine's IOCP sockets buffer the whole flood however small SO_SNDBUF/SO_RCVBUF are, so " + "no write stalls there"); + REQUIRE_FALSE(finished); +} + +/// Writes @p text to @p socket in full. +Task send(ISocket* socket, std::string text) +{ + static_cast(co_await socket->write(core::http::test::bytesOf(text))); +} + +/// Waits @p delay on @p loop, then writes @p text to @p socket. +Task sendAfter(EventLoop* loop, ISocket* socket, std::chrono::milliseconds delay, std::string text) +{ + co_await loop->delay(delay); + static_cast(co_await socket->write(core::http::test::bytesOf(text))); +} + +/// Reads once from @p socket, bounded by @p limit: what a connection that gave up left there. +Task readOnceWithin(EventLoop* loop, ISocket* socket, std::chrono::milliseconds limit) +{ + auto buffer = std::vector(4096); + auto got = co_await core::net::withTimeout( + loop, core::async::asTask(socket->read(std::span { buffer })), limit); + if (!got.has_value() || !got->has_value()) + co_return std::string {}; + co_return textOf(std::span { buffer }.first(**got)); +} + +RequestHead getHead(std::string extraValue = {}) +{ + auto head = RequestHead {}; + auto target = RequestTarget::parse("/"); + REQUIRE(target.has_value()); + head.target = std::move(*target); + auto method = Method::parse(extraValue.empty() ? "GET" : "PUT"); + REQUIRE(method.has_value()); + head.method = std::move(*method); + REQUIRE(head.fields.append("Host", "h").has_value()); + if (!extraValue.empty()) + { + auto const appended = head.fields.append("X-Flood", std::move(extraValue)); + REQUIRE(appended.has_value()); + } + return head; +} + +/// Reads a response head and its body to the end; the first failure is the answer. +Task> receive(Connection* connection, std::size_t maxBytes) +{ + auto head = co_await connection->readResponseHead(); + if (!head.has_value()) + co_return std::unexpected(std::move(head.error())); + auto framing = core::http::responseFraming("GET", head->version, head->status, head->fields); + if (!framing.has_value()) + co_return std::unexpected(std::move(framing.error())); + auto reader = connection->bodyReader(*framing); + auto body = co_await readAll(reader.get(), maxBytes); + if (body.error.has_value()) + co_return std::unexpected(std::move(*body.error)); + co_return std::move(body.text); +} + +/// Writes a request head, then @p body under @p framing. +Task> upload(Connection* connection, + RequestHead head, + BufferBodySource* body, + Framing framing) +{ + auto wrote = co_await connection->writeRequestHead(std::move(head), framing); + if (!wrote.has_value()) + co_return wrote; + co_return co_await connection->writeBody(body, framing); +} + +/// The two ends of one case: a loop on a backend, a connection over one end of a real pair. +struct Ends +{ + std::unique_ptr backend; + std::unique_ptr loop; + std::unique_ptr peer; + std::unique_ptr connection; +}; + +/// @return The ends, or nothing where @p kind does not build here. +std::optional endsOn(core::net::BackendKind kind, MessageRole role, WireTimeouts timeouts) +{ + auto backend = core::net::makeBackend(kind); + if (!backend) + return std::nullopt; + auto loop = std::make_unique(*backend); + auto pair = core::net::testing::makeSocketPair(*loop); + REQUIRE(pair.has_value()); + // Best effort: a transport without the options keeps its defaults, and the flood still exceeds + // them on every native kernel. + std::ignore = pair->first->setOption(core::net::SocketOption::SendBufferSize, SmallBuffer); + std::ignore = pair->second->setOption(core::net::SocketOption::ReceiveBufferSize, SmallBuffer); + auto connection = + std::make_unique(*loop, std::move(pair->first), role, HttpLimits {}, timeouts); + return Ends { .backend = std::move(backend), + .loop = std::move(loop), + .peer = std::move(pair->second), + .connection = std::move(connection) }; +} + +/// Runs @p work against a withTimeout of `Deadline` and records whether the deadline won. +Task race(EventLoop* loop, Task work, std::optional* timedOut) +{ + *timedOut = !co_await core::net::withTimeout(loop, std::move(work), Deadline); +} + +/// @p task with its answer dropped, for a race that only asks whether it finished. +template +Task discard(Task task) +{ + static_cast(co_await std::move(task)); +} + +/// Whether @p kind builds on this platform; a case skips the backends that do not. +bool buildsHere(core::net::BackendKind kind) +{ + return core::net::makeBackend(kind) != nullptr; +} + +/// What every cancellation case asserts once its race is over: the deadline won, and the +/// connection is not offered for reuse. Called inside each SECTION, because code after a set of +/// sections also runs in Catch2's discovery pass that enters none of them. +void expectCutOff(std::optional const& timedOut, Connection const& connection) +{ + REQUIRE(timedOut.has_value()); + CHECK(*timedOut); + CHECK(connection.reusable() == Reuse::No); +} + +/// Runs @p task under the watchdog and REQUIREs it finished. +void runBounded(EventLoop& loop, Task task) +{ + auto const finished = core::net::testing::blockOnWithin(loop, std::move(task), Watchdog); + REQUIRE(finished); +} + +} // namespace + +TEST_CASE("ConnectionLoopback.aSilentPeerTimesOutOnEveryBackend", "[http][connection][loopback]") +{ + for (auto const& backend: BackendMatrix) + { + if (!buildsHere(backend.kind)) + continue; + DYNAMIC_SECTION("backend=" << backend.name) + { + SECTION("the first byte of a response head") + { + auto ends = endsOn(backend.kind, + MessageRole::Response, + WireTimeouts { .firstByte = Deadline, .betweenBytes = 0ms, .write = 0ms }); + REQUIRE(ends.has_value()); + auto answer = std::optional> {}; + runBounded(*ends->loop, into(receive(ends->connection.get(), 100), &answer)); + REQUIRE(answer.has_value()); + REQUIRE_FALSE(answer->has_value()); + CHECK(answer->error().code == HttpErrorCode::ResponseTimeout); + CHECK_FALSE(ends->connection->socket().isClosed()); // still open: a server can answer 408 + CHECK(ends->connection->reusable() == Reuse::No); + } + SECTION("between the bytes of a head") + { + auto ends = endsOn(backend.kind, + MessageRole::Response, + WireTimeouts { .firstByte = 0ms, .betweenBytes = Deadline, .write = 0ms }); + REQUIRE(ends.has_value()); + runBounded(*ends->loop, send(ends->peer.get(), "HTTP/1.1 200 OK\r\n")); + auto answer = std::optional> {}; + runBounded(*ends->loop, into(receive(ends->connection.get(), 100), &answer)); + REQUIRE(answer.has_value()); + REQUIRE_FALSE(answer->has_value()); + CHECK(answer->error().code == HttpErrorCode::ConnectionReadTimeout); + } + SECTION("between the bytes of a body") + { + auto ends = endsOn(backend.kind, + MessageRole::Response, + WireTimeouts { .firstByte = 0ms, .betweenBytes = Deadline, .write = 0ms }); + REQUIRE(ends.has_value()); + runBounded(*ends->loop, + send(ends->peer.get(), "HTTP/1.1 200 OK\r\nContent-Length: 9\r\n\r\nab")); + auto answer = std::optional> {}; + runBounded(*ends->loop, into(receive(ends->connection.get(), 100), &answer)); + REQUIRE(answer.has_value()); + REQUIRE_FALSE(answer->has_value()); + CHECK(answer->error().code == HttpErrorCode::ConnectionReadTimeout); + } + } + } +} + +TEST_CASE("ConnectionLoopback.bytesThatMeetTheDeadlineAreNeverLost", "[http][connection][loopback]") +{ + // The peer's bytes and the read deadline land together. Whichever wins -- the read (a readiness + // backend that saw them first, or a completion backend whose receive had already finished when + // the deadline retired it: the data wins), or the deadline -- no byte disappears: the connection + // either read the head, or the bytes are still on the socket for the next reader. + for (auto const& backend: BackendMatrix) + { + if (!buildsHere(backend.kind)) + continue; + DYNAMIC_SECTION("backend=" << backend.name) + { + auto ends = endsOn(backend.kind, + MessageRole::Response, + WireTimeouts { .firstByte = Deadline, .betweenBytes = 0ms, .write = 0ms }); + REQUIRE(ends.has_value()); + constexpr auto Wire = std::string_view { "HTTP/1.1 204 No Content\r\n\r\n" }; + // Spawned first, so its delay is armed before the connection's deadline: due together. + ends->loop->spawn(sendAfter(ends->loop.get(), ends->peer.get(), Deadline, std::string { Wire })); + auto answer = std::optional> {}; + runBounded(*ends->loop, into(receive(ends->connection.get(), 100), &answer)); + REQUIRE(answer.has_value()); + if (answer->has_value()) + { + CHECK(ends->connection->reusable() == Reuse::Yes); + } + else + { + CHECK(answer->error().code == HttpErrorCode::ResponseTimeout); + auto left = std::optional {}; + runBounded(*ends->loop, + into(readOnceWithin(ends->loop.get(), &ends->connection->socket(), 5s), &left)); + REQUIRE(left.has_value()); + CHECK(*left == Wire); + } + } + } +} + +TEST_CASE("ConnectionLoopback.aPeerThatStopsReadingTimesTheWriteOut", "[http][connection][loopback]") +{ + for (auto const& backend: BackendMatrix) + { + if (!buildsHere(backend.kind)) + continue; + DYNAMIC_SECTION("backend=" << backend.name) + { + auto ends = endsOn(backend.kind, + MessageRole::Response, + WireTimeouts { .firstByte = 0ms, .betweenBytes = 0ms, .write = Deadline }); + REQUIRE(ends.has_value()); + auto body = BufferBodySource { std::string(Flood, 'x') }; + auto sent = std::optional> {}; + runBounded( + *ends->loop, + into(upload(ends->connection.get(), getHead("v"), &body, core::http::framingFor(&body)), + &sent)); + REQUIRE(sent.has_value()); + expectStalled(sent->has_value()); + CHECK(sent->error().code == HttpErrorCode::ConnectionWriteTimeout); + CHECK(ends->connection->socket().isClosed()); + CHECK(ends->connection->reusable() == Reuse::No); + } + } +} + +TEST_CASE("ConnectionLoopback.aFlowCancelledOnTheWireLeavesTheConnectionUnreusable", + "[http][connection][loopback]") +{ + // A stop from the caller's own token (here a withTimeout race) unwinds the connection's flow in + // the middle of a message; whatever side it was on is cut off at an unknown byte. + for (auto const& backend: BackendMatrix) + { + if (!buildsHere(backend.kind)) + continue; + DYNAMIC_SECTION("backend=" << backend.name) + { + auto ends = endsOn(backend.kind, MessageRole::Response, WireTimeouts {}); + REQUIRE(ends.has_value()); + auto* const loop = ends->loop.get(); + auto* const connection = ends->connection.get(); + auto timedOut = std::optional {}; + SECTION("a head read") + { + runBounded(*loop, race(loop, discard(connection->readResponseHead()), &timedOut)); + CHECK(connection->reusable() == Reuse::No); // before anything else could say so + // A head that arrives now is not parsed from a stream cut off at an unknown byte. + runBounded(*loop, send(ends->peer.get(), "HTTP/1.1 204 No Content\r\n\r\n")); + auto next = std::optional> {}; + runBounded(*loop, into(connection->readResponseHead(), &next)); + REQUIRE(next.has_value()); + REQUIRE_FALSE(next->has_value()); + CHECK(next->error().code == HttpErrorCode::ConnectionTerminated); + expectCutOff(timedOut, *connection); + } + SECTION("a body read") + { + runBounded(*loop, send(ends->peer.get(), "HTTP/1.1 200 OK\r\nContent-Length: 9\r\n\r\nab")); + auto head = std::optional> {}; + runBounded(*loop, into(connection->readResponseHead(), &head)); + REQUIRE(head.has_value()); + REQUIRE(head->has_value()); + auto reader = connection->bodyReader( + Framing { .kind = BodyFraming::Length, .length = 9, .persistence = {} }); + runBounded(*loop, race(loop, discard(readAll(reader.get(), 100)), &timedOut)); + expectCutOff(timedOut, *connection); + // The rest arrives and the read is retried: still refused, for the cut is where nobody + // knows. + runBounded(*loop, send(ends->peer.get(), "cdefghi")); + auto retried = std::optional {}; + runBounded(*loop, into(readAll(reader.get(), 100), &retried)); + REQUIRE(retried.has_value()); + REQUIRE(retried->error.has_value()); + CHECK(retried->error->code == HttpErrorCode::ConnectionTerminated); + CHECK(connection->reusable() == Reuse::No); + } + SECTION("a head write") + { + runBounded( + *loop, + race(loop, + discard(connection->writeRequestHead(getHead(std::string(Flood, 'x')), Framing {})), + &timedOut)); + REQUIRE(timedOut.has_value()); + expectStalled(!*timedOut); + expectCutOff(timedOut, *connection); + // A retried head would follow the bytes the cancelled one left half-sent: refused. + auto retried = std::optional> {}; + runBounded(*loop, into(connection->writeRequestHead(getHead(), Framing {}), &retried)); + REQUIRE(retried.has_value()); + REQUIRE_FALSE(retried->has_value()); + CHECK(retried->error().code == HttpErrorCode::ConnectionTerminated); + CHECK(connection->reusable() == Reuse::No); + } + SECTION("a body write") + { + auto body = BufferBodySource { std::string(Flood, 'x') }; + runBounded( + *loop, + race(loop, + discard(upload(connection, getHead("v"), &body, core::http::framingFor(&body))), + &timedOut)); + REQUIRE(timedOut.has_value()); + expectStalled(!*timedOut); + expectCutOff(timedOut, *connection); + } + } + } +} diff --git a/src/core/http/Connection_test.cpp b/src/core/http/Connection_test.cpp new file mode 100644 index 00000000..ef50ed4c --- /dev/null +++ b/src/core/http/Connection_test.cpp @@ -0,0 +1,2098 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// `Connection` over an in-memory socket pair on a hand-driven loop: heads and bodies in both +// directions, the framing fields the connection writes itself, what a peer that closes or falls +// silent is reported as in each role, the window a streamed body is held to, and when a connection +// may carry another message. Every flow runs on a `TestLoop` over a `ManualClock`, so nothing here +// waits on anything but the loop the case drives, and a flow that never finishes leaves its answer +// empty instead of hanging the case. +#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 + +using core::async::Task; +using core::http::BodyChunk; +using core::http::BodyEnd; +using core::http::BodyFraming; +using core::http::BufferBodySource; +using core::http::Connection; +using core::http::Fields; +using core::http::Framing; +using core::http::HttpErrorCode; +using core::http::HttpLimits; +using core::http::HttpResult; +using core::http::HttpVersion; +using core::http::IBodySource; +using core::http::MessageRole; +using core::http::Method; +using core::http::Persistence; +using core::http::RequestHead; +using core::http::RequestTarget; +using core::http::ResponseHead; +using core::http::Reuse; +using core::http::TrailerIntent; +using core::http::WireTimeouts; +using core::http::test::into; +using core::http::test::readAll; +using core::http::test::ReadBody; +using core::http::test::readUntilClosed; +using core::http::test::writeAndClose; +using core::http::test::writeOnly; +using core::net::ISocket; +using core::net::NetError; +using core::net::NetErrorCode; +using core::net::testing::InMemorySocketPair; +using core::net::testing::SocketDecorator; +using core::net::testing::TestLoop; +using core::platform::ManualClock; + +using namespace std::chrono_literals; + +namespace +{ + +/// A loop driven by hand, over a clock moved by hand, and a pair whose directions each hold at most +/// 16 bytes in flight, so every body larger than that streams in steps. +struct Wire +{ + ManualClock clock {}; + TestLoop loop { clock }; + InMemorySocketPair pair = InMemorySocketPair::create(16); +}; + +/// @return A request head, its fields appended in order; a field the factories refuse fails the case. +RequestHead requestHead(std::string_view method, + std::string_view target, + std::vector> const& fields, + HttpVersion version = HttpVersion::Http11) +{ + auto head = RequestHead {}; + auto parsedMethod = Method::parse(method); + REQUIRE(parsedMethod.has_value()); + head.method = std::move(*parsedMethod); + auto parsedTarget = RequestTarget::parse(target); + REQUIRE(parsedTarget.has_value()); + head.target = std::move(*parsedTarget); + head.version = version; + for (auto const& [name, value]: fields) + REQUIRE(head.fields.append(name, value).has_value()); + return head; +} + +/// @return A response head of @p status with @p fields. +ResponseHead responseHead(std::uint16_t status, + std::vector> const& fields) +{ + auto head = ResponseHead {}; + head.status = status; + for (auto const& [name, value]: fields) + REQUIRE(head.fields.append(name, value).has_value()); + return head; +} + +/// @return @p fields as one list; an invalid field fails the case. +Fields fieldsOf(std::vector> const& fields) +{ + auto out = Fields {}; + for (auto const& [name, value]: fields) + REQUIRE(out.append(name, value).has_value()); + return out; +} + +/// @return @p size bytes of a repeating, position-dependent pattern, so a lost or reordered byte shows. +std::string patternOf(std::size_t size) +{ + auto text = std::string(size, '\0'); + auto index = std::size_t { 0 }; + for (auto& octet: text) + octet = static_cast('a' + (index++ % 26)); + return text; +} + +/// What a server end read of one request: the head, the body and its trailers. +struct ServedRequest +{ + std::optional head; + ReadBody body; + std::optional trailers; + std::optional error; +}; + +/// The server end of one exchange: reads a request head, frames it, and reads the body to its end. +Task serveOne(Connection* connection, std::size_t maxBytes) +{ + auto out = ServedRequest {}; + auto head = co_await connection->readRequestHead(); + if (!head.has_value()) + { + out.error = head.error().code; + co_return out; + } + auto framing = core::http::requestFraming(head->version, head->fields); + if (!framing.has_value()) + { + out.error = framing.error().code; + co_return out; + } + out.head = std::move(*head); + auto reader = connection->bodyReader(*framing); + out.body = co_await readAll(reader.get(), maxBytes); + if (out.body.error.has_value()) + co_return out; + auto trailers = co_await reader->trailers(); + if (trailers.has_value()) + out.trailers = std::move(*trailers); + else + out.error = trailers.error().code; + co_return out; +} + +/// The client end of one exchange: reads a response head to @p method and its body to the end. +struct ReadResponse +{ + std::optional head; + ReadBody body; + std::optional trailers; + std::optional error; +}; + +Task receiveOne(Connection* connection, std::string method, std::size_t maxBytes) +{ + auto out = ReadResponse {}; + auto head = co_await connection->readResponseHead(); + if (!head.has_value()) + { + out.error = head.error().code; + co_return out; + } + auto framing = core::http::responseFraming(method, head->version, head->status, head->fields); + if (!framing.has_value()) + { + out.error = framing.error().code; + co_return out; + } + out.head = std::move(*head); + auto reader = connection->bodyReader(*framing); + out.body = co_await readAll(reader.get(), maxBytes); + if (out.body.error.has_value()) + co_return out; + auto trailers = co_await reader->trailers(); + if (trailers.has_value()) + out.trailers = std::move(*trailers); + else + out.error = trailers.error().code; + co_return out; +} + +/// The client end of one upload: the request head, then the body, under one framing. +Task> sendRequest(Connection* connection, + RequestHead head, + IBodySource* body, + Framing framing) +{ + auto wrote = co_await connection->writeRequestHead(std::move(head), framing); + if (!wrote.has_value()) + co_return wrote; + co_return co_await connection->writeBody(body, framing); +} + +/// The client end of an upload that then closes, so the peer reads exactly what was written. +Task> sendRequestThenClose(Connection* connection, IBodySource* body, Framing framing) +{ + // The head is made before the co_await, not in its full-expression: MSVC at /O2 cannot keep the + // tail call a resumption needs past a call there (C4737). + auto head = requestHead("PUT", "/", { { "Host", "h" } }); + auto sending = sendRequest(connection, std::move(head), body, framing); + auto result = co_await std::move(sending); + connection->close(); + co_return result; +} + +/// Writes a request head and @p body under the body's own framing, and closes the socket. +Task> bodyThenClose(Connection* connection, IBodySource* body) +{ + auto head = requestHead("PUT", "/", { { "Host", "h" } }); + auto const framing = core::http::framingFor(body); + auto sending = sendRequest(connection, std::move(head), body, framing); + auto result = co_await std::move(sending); + connection->close(); + co_return result; +} + +/// Writes a request head announcing a length of 3, then a body under a chunked framing. +Task> headThenOtherBody(Connection* connection, IBodySource* body) +{ + auto head = co_await connection->writeRequestHead( + requestHead("PUT", "/", { { "Host", "h" } }), + Framing { .kind = BodyFraming::Length, .length = 3, .persistence = {} }); + if (!head.has_value()) + co_return head; + co_return co_await connection->writeBody( + body, Framing { .kind = BodyFraming::Chunked, .length = 0, .persistence = {} }); +} + +/// The server end of one reply: the response head, then the body, under one framing. +Task> sendResponse(Connection* connection, + ResponseHead head, + IBodySource* body, + Framing framing) +{ + auto wrote = co_await connection->writeResponseHead(std::move(head), framing); + if (!wrote.has_value()) + co_return wrote; + co_return co_await connection->writeBody(body, framing); +} + +/// Writes @p head under @p framing and closes the socket, so the peer reads exactly what was written. +Task> requestHeadThenClose(Connection* connection, RequestHead head, Framing framing) +{ + auto wrote = co_await connection->writeRequestHead(std::move(head), framing); + connection->close(); + co_return wrote; +} + +Task> responseHeadThenClose(Connection* connection, ResponseHead head, Framing framing) +{ + auto wrote = co_await connection->writeResponseHead(std::move(head), framing); + connection->close(); + co_return wrote; +} + +/// Records the largest buffer any read was given: the most the connection asks the socket for. +class WindowRecordingSocket final: public SocketDecorator +{ + public: + explicit WindowRecordingSocket(ISocket& inner, std::size_t* largest) noexcept: + SocketDecorator { inner }, _largest { largest } + { + } + + [[nodiscard]] core::net::IoAwaitable read(std::span buffer) override + { + *_largest = std::max(*_largest, buffer.size()); + return inner().read(buffer); + } + + private: + std::size_t* _largest; +}; + +/// A socket whose every read and write fails with one code, at once. +class FailingSocket final: public SocketDecorator +{ + public: + FailingSocket(ISocket& inner, NetErrorCode code) noexcept: SocketDecorator { inner }, _code { code } {} + + [[nodiscard]] core::net::IoAwaitable read(std::span /*buffer*/) override + { + return core::net::IoAwaitable { std::unexpected( + NetError { .code = _code, .systemCode = 0, .context = {} }) }; + } + + [[nodiscard]] core::net::IoAwaitable writeVectored( + std::span const> /*segments*/, + std::shared_ptr /*keepAlive*/) override + { + return core::net::IoAwaitable { std::unexpected( + NetError { .code = _code, .systemCode = 0, .context = {} }) }; + } + + [[nodiscard]] core::net::IoAwaitable write(std::span /*buffer*/) override + { + return core::net::IoAwaitable { std::unexpected( + NetError { .code = _code, .systemCode = 0, .context = {} }) }; + } + + private: + NetErrorCode _code; +}; + +/// A body that streams @p chunks in order and does not say how long it is. +class ChunksBodySource final: public IBodySource +{ + public: + /// @param chunks What @c next hands out, in order. + /// @param claimedLength What @c knownLength answers, which a lying source makes differ. + explicit ChunksBodySource(std::vector chunks, + std::optional claimedLength = {}): + _chunks { std::move(chunks) }, _claimedLength { claimedLength } + { + } + + [[nodiscard]] std::optional knownLength() const noexcept override + { + return _claimedLength; + } + [[nodiscard]] TrailerIntent trailerIntent() const noexcept override { return TrailerIntent::None; } + + [[nodiscard]] Task> next() override + { + auto chunk = BodyChunk {}; + if (_next < _chunks.size()) + { + auto const& text = _chunks.at(_next++); + auto const bytes = core::http::test::bytesOf(text); + chunk.bytes.assign(bytes.begin(), bytes.end()); + } + chunk.end = _next < _chunks.size() ? BodyEnd::More : BodyEnd::Reached; + co_return chunk; + } + + [[nodiscard]] Task> trailers() override { co_return Fields {}; } + + private: + std::vector _chunks; + std::optional _claimedLength; + std::size_t _next = 0; +}; + +constexpr auto NoTimeouts = WireTimeouts {}; + +} // namespace + +TEST_CASE("Connection.chunkedBodyWithTrailersStreamsAcross", "[http][connection]") +{ + // Both directions at once: the client end writes a 1000-byte chunked upload with a trailer, the + // server end reads it 100 bytes at a time through a 64-byte window. The pair holds 16 bytes in + // flight per direction, so the body crosses in dozens of steps. + auto wire = Wire {}; + auto largestRead = std::size_t { 0 }; + auto serverSocket = std::make_unique(*wire.pair.server, &largestRead); + auto serverLimits = HttpLimits {}; + serverLimits.maxReadChunk = 64; + auto server = + Connection { wire.loop, std::move(serverSocket), MessageRole::Request, serverLimits, NoTimeouts }; + auto client = Connection { + wire.loop, std::move(wire.pair.client), MessageRole::Response, HttpLimits {}, NoTimeouts + }; + + auto const body = patternOf(1000); + auto source = BufferBodySource { body, fieldsOf({ { "X-Checksum", "abc" } }) }; + REQUIRE(core::http::framingFor(&source).kind == BodyFraming::Chunked); + + auto sent = std::optional> {}; + auto served = std::optional {}; + wire.loop.spawn(into(sendRequest(&client, + requestHead("POST", "/upload", { { "Host", "example.test" } }), + &source, + core::http::framingFor(&source)), + &sent)); + wire.loop.spawn(into(serveOne(&server, 100), &served)); + std::ignore = wire.loop.drain(); + + REQUIRE(sent.has_value()); + CHECK(sent->has_value()); + REQUIRE(served.has_value()); + REQUIRE_FALSE(served->error.has_value()); + REQUIRE_FALSE(served->body.error.has_value()); + CHECK(served->head->method.text() == "POST"); + CHECK(served->body.text == body); + CHECK(std::ranges::all_of(served->body.chunkSizes, [](std::size_t size) { return size <= 64; })); + CHECK(largestRead <= 64); + CHECK(largestRead > 0); + REQUIRE(served->trailers.has_value()); + auto const checksum = served->trailers->get("x-checksum"); + REQUIRE(checksum.size() == 1); + CHECK(checksum.front() == "abc"); + CHECK_FALSE(server.hasLiveBodyReader()); + CHECK(server.reusable() == Reuse::Yes); + CHECK(client.reusable() == Reuse::Yes); +} + +TEST_CASE("Connection.lengthBodyRoundTripsBothWays", "[http][connection]") +{ + // A request with a Length body one way, a response with one the other, on one connection pair. + auto wire = Wire {}; + auto server = Connection { + wire.loop, std::move(wire.pair.server), MessageRole::Request, HttpLimits {}, NoTimeouts + }; + auto client = Connection { + wire.loop, std::move(wire.pair.client), MessageRole::Response, HttpLimits {}, NoTimeouts + }; + + auto upload = BufferBodySource { patternOf(300) }; + REQUIRE(core::http::framingFor(&upload).kind == BodyFraming::Length); + REQUIRE(core::http::framingFor(&upload).length == 300); + auto sent = std::optional> {}; + auto served = std::optional {}; + wire.loop.spawn(into(sendRequest(&client, + requestHead("PUT", "/thing", { { "Host", "example.test" } }), + &upload, + core::http::framingFor(&upload)), + &sent)); + wire.loop.spawn(into(serveOne(&server, 1000), &served)); + std::ignore = wire.loop.drain(); + REQUIRE(sent.has_value()); + CHECK(sent->has_value()); + REQUIRE(served.has_value()); + REQUIRE_FALSE(served->error.has_value()); + CHECK(served->body.text == patternOf(300)); + REQUIRE(served->trailers.has_value()); + CHECK(served->trailers->entries().empty()); + + auto reply = BufferBodySource { "done" }; + auto replied = std::optional> {}; + auto received = std::optional {}; + wire.loop.spawn( + into(sendResponse(&server, responseHead(200, {}), &reply, core::http::framingFor(&reply)), &replied)); + wire.loop.spawn(into(receiveOne(&client, "PUT", 1000), &received)); + std::ignore = wire.loop.drain(); + REQUIRE(replied.has_value()); + CHECK(replied->has_value()); + REQUIRE(received.has_value()); + REQUIRE_FALSE(received->error.has_value()); + CHECK(received->head->status == 200); + CHECK(received->body.text == "done"); + CHECK(server.reusable() == Reuse::Yes); + CHECK(client.reusable() == Reuse::Yes); +} + +TEST_CASE("Connection.peerClosingMidBodyIsReportedByRole", "[http][connection]") +{ + // The same truncation is the peer's broken promise in a response and a malformed request in a + // server's eyes: ResponseIncomplete and ProtocolError. Either way the connection is done. + struct Row + { + std::string_view name; + MessageRole role; + std::string_view wire; + HttpErrorCode code; + }; + constexpr auto Rows = std::array { + Row { "response, length", + MessageRole::Response, + "HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nabcd", + HttpErrorCode::ResponseIncomplete }, + Row { "response, chunked", + MessageRole::Response, + "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\na\r\nabcd", + HttpErrorCode::ResponseIncomplete }, + Row { "response, chunked, in the trailers", + MessageRole::Response, + "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n4\r\nabcd\r\n0\r\nX-A: b\r\n", + HttpErrorCode::ResponseIncomplete }, + Row { "request, length", + MessageRole::Request, + "POST / HTTP/1.1\r\nHost: h\r\nContent-Length: 10\r\n\r\nabcd", + HttpErrorCode::ProtocolError }, + Row { "request, chunked", + MessageRole::Request, + "POST / HTTP/1.1\r\nHost: h\r\nTransfer-Encoding: chunked\r\n\r\na\r\nabcd", + HttpErrorCode::ProtocolError }, + }; + for (auto const& row: Rows) + { + DYNAMIC_SECTION(row.name) + { + auto wire = Wire {}; + auto connection = + Connection { wire.loop, std::move(wire.pair.server), row.role, HttpLimits {}, NoTimeouts }; + wire.loop.spawn(writeAndClose(wire.pair.client.get(), std::string { row.wire })); + auto bodyError = std::optional {}; + if (row.role == MessageRole::Response) + { + auto received = std::optional {}; + wire.loop.spawn(into(receiveOne(&connection, "GET", 1000), &received)); + std::ignore = wire.loop.drain(); + REQUIRE(received.has_value()); + REQUIRE(received->head.has_value()); + REQUIRE(received->body.error.has_value()); + bodyError = received->body.error->code; + } + else + { + auto served = std::optional {}; + wire.loop.spawn(into(serveOne(&connection, 1000), &served)); + std::ignore = wire.loop.drain(); + REQUIRE(served.has_value()); + REQUIRE(served->head.has_value()); + REQUIRE(served->body.error.has_value()); + bodyError = served->body.error->code; + } + CHECK(bodyError == row.code); + CHECK(connection.reusable() == Reuse::No); + } + } +} + +TEST_CASE("Connection.peerClosingInOrBeforeAHead", "[http][connection]") +{ + // A close before any byte of a head is the connection ending, which a server sees between + // keep-alive requests and a client sees on a stale pooled connection; a close inside a head is + // the role's incomplete-message code. + struct Row + { + std::string_view name; + MessageRole role; + std::string_view wire; + HttpErrorCode code; + }; + constexpr auto Rows = std::array { + Row { "response, before", MessageRole::Response, "", HttpErrorCode::ConnectionTerminated }, + Row { "request, before", MessageRole::Request, "", HttpErrorCode::ConnectionTerminated }, + Row { "response, inside", + MessageRole::Response, + "HTTP/1.1 200 OK\r\nA: b", + HttpErrorCode::ResponseIncomplete }, + Row { "request, inside", MessageRole::Request, "GET / HTTP/1.1\r\nHo", HttpErrorCode::ProtocolError }, + }; + for (auto const& row: Rows) + { + DYNAMIC_SECTION(row.name) + { + auto wire = Wire {}; + auto connection = + Connection { wire.loop, std::move(wire.pair.server), row.role, HttpLimits {}, NoTimeouts }; + wire.loop.spawn(writeAndClose(wire.pair.client.get(), std::string { row.wire })); + auto code = std::optional {}; + if (row.role == MessageRole::Response) + { + auto received = std::optional {}; + wire.loop.spawn(into(receiveOne(&connection, "GET", 1000), &received)); + std::ignore = wire.loop.drain(); + REQUIRE(received.has_value()); + code = received->error; + } + else + { + auto served = std::optional {}; + wire.loop.spawn(into(serveOne(&connection, 1000), &served)); + std::ignore = wire.loop.drain(); + REQUIRE(served.has_value()); + code = served->error; + } + CHECK(code == row.code); + CHECK(connection.reusable() == Reuse::No); + } + } +} + +TEST_CASE("Connection.readIsClampedToMaxReadChunk", "[http][connection]") +{ + // A guest may ask for a gigabyte; the host hands out at most maxReadChunk, whatever the framing. + constexpr auto Rows = std::array, 2> { + std::pair { "length", "HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\n" }, + std::pair { "chunked", "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n64\r\n" }, + }; + for (auto const& [name, head]: Rows) + { + DYNAMIC_SECTION(name) + { + auto wire = Wire {}; + auto limits = HttpLimits {}; + limits.maxReadChunk = 32; + auto connection = Connection { + wire.loop, std::move(wire.pair.client), MessageRole::Response, limits, NoTimeouts + }; + wire.loop.spawn(writeOnly(wire.pair.server.get(), std::string { head } + patternOf(100))); + auto received = std::optional {}; + wire.loop.spawn(into(receiveOne(&connection, "GET", std::size_t { 1 } << 30), &received)); + std::ignore = wire.loop.drain(); + wire.pair.server->close(); + std::ignore = wire.loop.drain(); + REQUIRE(received.has_value()); + REQUIRE(received->head.has_value()); + REQUIRE_FALSE(received->body.chunkSizes.empty()); + CHECK( + std::ranges::all_of(received->body.chunkSizes, [](std::size_t size) { return size <= 32; })); + CHECK(received->body.text.starts_with(patternOf(100).substr(0, 32))); + } + } +} + +TEST_CASE("Connection.aSmallReadTakesOnlyWhatItAsks", "[http][connection]") +{ + // Bytes past a small read stay in the connection's buffer for the next one, in order. + auto wire = Wire {}; + auto connection = Connection { + wire.loop, std::move(wire.pair.client), MessageRole::Response, HttpLimits {}, NoTimeouts + }; + wire.loop.spawn( + writeOnly(wire.pair.server.get(), + "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n0a\r\n0123456789\r\n0\r\n\r\n")); + auto received = std::optional {}; + wire.loop.spawn(into(receiveOne(&connection, "GET", 3), &received)); + std::ignore = wire.loop.drain(); + REQUIRE(received.has_value()); + REQUIRE_FALSE(received->body.error.has_value()); + CHECK(received->body.text == "0123456789"); + CHECK(std::ranges::all_of(received->body.chunkSizes, [](std::size_t size) { return size <= 3; })); + CHECK(connection.reusable() == Reuse::Yes); +} + +TEST_CASE("Connection.aCallerFramingFieldIsRefused", "[http][connection]") +{ + // The connection writes every framing field itself; one the caller brought could contradict it, + // so it is refused before a byte is written. + for (auto const name: + { "Content-Length", "transfer-encoding", "Connection", "Keep-Alive", "TE", "Upgrade" }) + { + DYNAMIC_SECTION(name) + { + SECTION("in a request head") + { + auto wire = Wire {}; + auto client = Connection { + wire.loop, std::move(wire.pair.client), MessageRole::Response, HttpLimits {}, NoTimeouts + }; + auto wrote = std::optional> {}; + auto peer = std::optional {}; + wire.loop.spawn(into( + requestHeadThenClose( + &client, requestHead("GET", "/", { { "Host", "h" }, { name, "5" } }), Framing {}), + &wrote)); + wire.loop.spawn(into(readUntilClosed(wire.pair.server.get()), &peer)); + std::ignore = wire.loop.drain(); + REQUIRE(wrote.has_value()); + REQUIRE_FALSE(wrote->has_value()); + CHECK(wrote->error().code == HttpErrorCode::ProtocolError); + REQUIRE(peer.has_value()); + CHECK(peer->empty()); + } + SECTION("then a corrected head") + { + // A refusal before the first wire byte leaves the connection as it was: the handler + // that added the field can still send its 500, and the connection stays reusable. + auto wire = Wire {}; + auto server = Connection { + wire.loop, std::move(wire.pair.server), MessageRole::Request, HttpLimits {}, NoTimeouts + }; + wire.loop.spawn(writeOnly(wire.pair.client.get(), "GET / HTTP/1.1\r\nHost: h\r\n\r\n")); + auto served = std::optional {}; + wire.loop.spawn(into(serveOne(&server, 100), &served)); + std::ignore = wire.loop.drain(); + REQUIRE(served.has_value()); + REQUIRE(served->head.has_value()); + + auto peer = std::optional {}; + wire.loop.spawn(into(readUntilClosed(wire.pair.client.get()), &peer)); + auto refused = std::optional> {}; + wire.loop.spawn(into( + server.writeResponseHead(responseHead(200, { { name, "5" } }), Framing {}), &refused)); + std::ignore = wire.loop.drain(); + REQUIRE(refused.has_value()); + REQUIRE_FALSE(refused->has_value()); + CHECK(refused->error().code == HttpErrorCode::ProtocolError); + auto corrected = std::optional> {}; + wire.loop.spawn( + into(server.writeResponseHead(responseHead(500, {}), Framing {}), &corrected)); + std::ignore = wire.loop.drain(); + REQUIRE(corrected.has_value()); + CHECK(corrected->has_value()); + CHECK(server.reusable() == Reuse::Yes); + server.close(); + std::ignore = wire.loop.drain(); + REQUIRE(peer.has_value()); + CHECK(*peer == "HTTP/1.1 500 \r\nContent-Length: 0\r\n\r\n"); + } + SECTION("in a response head") + { + auto wire = Wire {}; + auto server = Connection { + wire.loop, std::move(wire.pair.server), MessageRole::Request, HttpLimits {}, NoTimeouts + }; + auto wrote = std::optional> {}; + auto peer = std::optional {}; + wire.loop.spawn( + into(responseHeadThenClose(&server, responseHead(200, { { name, "5" } }), Framing {}), + &wrote)); + wire.loop.spawn(into(readUntilClosed(wire.pair.client.get()), &peer)); + std::ignore = wire.loop.drain(); + REQUIRE(wrote.has_value()); + REQUIRE_FALSE(wrote->has_value()); + CHECK(wrote->error().code == HttpErrorCode::ProtocolError); + REQUIRE(peer.has_value()); + CHECK(peer->empty()); + } + } + } +} + +TEST_CASE("Connection.headsCarryTheFramingFieldsItWrites", "[http][connection]") +{ + // What each framing puts on the wire, exactly; and the framings a head cannot carry. + struct Row + { + std::string_view name; + HttpVersion version; + Framing framing; + std::optional wire; ///< Empty when the head is refused. + }; + auto const rows = std::array { + Row { "none", HttpVersion::Http11, Framing {}, "GET / HTTP/1.1\r\nHost: h\r\n\r\n" }, + Row { "length", + HttpVersion::Http11, + Framing { .kind = BodyFraming::Length, .length = 5, .persistence = {} }, + "GET / HTTP/1.1\r\nHost: h\r\nContent-Length: 5\r\n\r\n" }, + Row { "chunked", + HttpVersion::Http11, + Framing { .kind = BodyFraming::Chunked, .length = 0, .persistence = {} }, + "GET / HTTP/1.1\r\nHost: h\r\nTransfer-Encoding: chunked\r\n\r\n" }, + Row { "close", + HttpVersion::Http11, + Framing { .kind = BodyFraming::None, .length = 0, .persistence = Persistence::Close }, + "GET / HTTP/1.1\r\nHost: h\r\nConnection: close\r\n\r\n" }, + Row { "HTTP/1.0 keep-alive", + HttpVersion::Http10, + Framing {}, + "GET / HTTP/1.0\r\nHost: h\r\nConnection: keep-alive\r\n\r\n" }, + Row { "HTTP/1.0 close", + HttpVersion::Http10, + Framing { .kind = BodyFraming::None, .length = 0, .persistence = Persistence::Close }, + "GET / HTTP/1.0\r\nHost: h\r\n\r\n" }, + Row { "HTTP/1.0 chunked", + HttpVersion::Http10, + Framing { .kind = BodyFraming::Chunked, .length = 0, .persistence = {} }, + std::nullopt }, + Row { "until close", + HttpVersion::Http11, + Framing { .kind = BodyFraming::UntilClose, .length = 0, .persistence = Persistence::Close }, + std::nullopt }, + }; + for (auto const& row: rows) + { + DYNAMIC_SECTION(row.name) + { + auto wire = Wire {}; + auto client = Connection { + wire.loop, std::move(wire.pair.client), MessageRole::Response, HttpLimits {}, NoTimeouts + }; + auto wrote = std::optional> {}; + auto peer = std::optional {}; + wire.loop.spawn( + into(requestHeadThenClose( + &client, requestHead("GET", "/", { { "Host", "h" } }, row.version), row.framing), + &wrote)); + wire.loop.spawn(into(readUntilClosed(wire.pair.server.get()), &peer)); + std::ignore = wire.loop.drain(); + REQUIRE(wrote.has_value()); + REQUIRE(peer.has_value()); + if (row.wire.has_value()) + { + CHECK(wrote->has_value()); + CHECK(*peer == *row.wire); + } + else + { + REQUIRE_FALSE(wrote->has_value()); + CHECK(wrote->error().code == HttpErrorCode::ProtocolError); + CHECK(peer->empty()); + } + } + } +} + +TEST_CASE("Connection.responseHeadsFollowTheirStatus", "[http][connection]") +{ + // A response with no body still says so unless its status says it for it; a status that has no + // body refuses a body framing. + struct Row + { + std::string_view name; + std::uint16_t status; + Framing framing; + std::optional wire; + }; + auto const rows = std::array { + Row { "200 none", 200, Framing {}, "HTTP/1.1 200 \r\nContent-Length: 0\r\n\r\n" }, + Row { "204 none", 204, Framing {}, "HTTP/1.1 204 \r\n\r\n" }, + Row { "304 none", 304, Framing {}, "HTTP/1.1 304 \r\n\r\n" }, + Row { "101 none", 101, Framing {}, "HTTP/1.1 101 \r\n\r\n" }, + Row { "204 length", + 204, + Framing { .kind = BodyFraming::Length, .length = 3, .persistence = {} }, + std::nullopt }, + Row { "100 chunked", + 100, + Framing { .kind = BodyFraming::Chunked, .length = 0, .persistence = {} }, + std::nullopt }, + Row { "304 length", + 304, + Framing { .kind = BodyFraming::Length, .length = 3, .persistence = {} }, + "HTTP/1.1 304 \r\nContent-Length: 3\r\n\r\n" }, + Row { "304 chunked", + 304, + Framing { .kind = BodyFraming::Chunked, .length = 0, .persistence = {} }, + std::nullopt }, + Row { "200 until close", + 200, + Framing { .kind = BodyFraming::UntilClose, .length = 0, .persistence = Persistence::Close }, + "HTTP/1.1 200 \r\nConnection: close\r\n\r\n" }, + }; + for (auto const& row: rows) + { + DYNAMIC_SECTION(row.name) + { + auto wire = Wire {}; + auto server = Connection { + wire.loop, std::move(wire.pair.server), MessageRole::Request, HttpLimits {}, NoTimeouts + }; + auto wrote = std::optional> {}; + auto peer = std::optional {}; + wire.loop.spawn( + into(responseHeadThenClose(&server, responseHead(row.status, {}), row.framing), &wrote)); + wire.loop.spawn(into(readUntilClosed(wire.pair.client.get()), &peer)); + std::ignore = wire.loop.drain(); + REQUIRE(wrote.has_value()); + REQUIRE(peer.has_value()); + if (row.wire.has_value()) + { + CHECK(wrote->has_value()); + CHECK(*peer == *row.wire); + } + else + { + REQUIRE_FALSE(wrote->has_value()); + CHECK(wrote->error().code == HttpErrorCode::ProtocolError); + CHECK(peer->empty()); + } + } + } +} + +TEST_CASE("Connection.aBodyThatBreaksItsLengthIsRefused", "[http][connection]") +{ + // A body longer than its Length framing would put bytes on the wire that the peer reads as the + // next message; shorter, it would leave the peer waiting. Both are the writer's body-size code, + // and not one byte past the framing reaches the peer. + auto const head = std::string { "PUT / HTTP/1.1\r\nHost: h\r\nContent-Length: 5\r\n\r\n" }; + auto const length5 = Framing { .kind = BodyFraming::Length, .length = 5, .persistence = {} }; + + SECTION("a known length of 6 is refused before any body byte") + { + auto wire = Wire {}; + auto client = Connection { + wire.loop, std::move(wire.pair.client), MessageRole::Response, HttpLimits {}, NoTimeouts + }; + auto source = BufferBodySource { "abcdef" }; + auto sent = std::optional> {}; + auto peer = std::optional {}; + wire.loop.spawn(into(sendRequestThenClose(&client, &source, length5), &sent)); + wire.loop.spawn(into(readUntilClosed(wire.pair.server.get()), &peer)); + std::ignore = wire.loop.drain(); + REQUIRE(sent.has_value()); + REQUIRE_FALSE(sent->has_value()); + CHECK(sent->error().code == HttpErrorCode::RequestBodySize); + REQUIRE(peer.has_value()); + CHECK(*peer == head); + CHECK(client.reusable() == Reuse::No); + } + SECTION("a streamed body that runs past the length stops at the chunk that would pass it") + { + auto wire = Wire {}; + auto client = Connection { + wire.loop, std::move(wire.pair.client), MessageRole::Response, HttpLimits {}, NoTimeouts + }; + auto source = ChunksBodySource { { "abc", "def" } }; + auto sent = std::optional> {}; + auto peer = std::optional {}; + wire.loop.spawn(into(sendRequestThenClose(&client, &source, length5), &sent)); + wire.loop.spawn(into(readUntilClosed(wire.pair.server.get()), &peer)); + std::ignore = wire.loop.drain(); + REQUIRE(sent.has_value()); + REQUIRE_FALSE(sent->has_value()); + CHECK(sent->error().code == HttpErrorCode::RequestBodySize); + REQUIRE(peer.has_value()); + CHECK(*peer == head + "abc"); + CHECK(client.reusable() == Reuse::No); + } + SECTION("a streamed body that ends short of the length") + { + auto wire = Wire {}; + auto client = Connection { + wire.loop, std::move(wire.pair.client), MessageRole::Response, HttpLimits {}, NoTimeouts + }; + auto source = ChunksBodySource { { "ab", "cd" } }; + auto sent = std::optional> {}; + wire.loop.spawn(into( + sendRequest(&client, requestHead("PUT", "/", { { "Host", "h" } }), &source, length5), &sent)); + auto peer = std::optional {}; + wire.loop.spawn(into(readUntilClosed(wire.pair.server.get()), &peer)); + std::ignore = wire.loop.drain(); + REQUIRE(sent.has_value()); + REQUIRE_FALSE(sent->has_value()); + CHECK(sent->error().code == HttpErrorCode::RequestBodySize); + CHECK(sent->error().size == std::uint64_t { 4 }); + CHECK(client.reusable() == Reuse::No); + client.close(); + std::ignore = wire.loop.drain(); + } + SECTION("a server's reply is held to the response's code") + { + auto wire = Wire {}; + auto server = Connection { + wire.loop, std::move(wire.pair.server), MessageRole::Request, HttpLimits {}, NoTimeouts + }; + auto source = BufferBodySource { "abcdef" }; + auto sent = std::optional> {}; + wire.loop.spawn(into(sendResponse(&server, responseHead(200, {}), &source, length5), &sent)); + auto peer = std::optional {}; + wire.loop.spawn(into(readUntilClosed(wire.pair.client.get()), &peer)); + std::ignore = wire.loop.drain(); + server.close(); + std::ignore = wire.loop.drain(); + REQUIRE(sent.has_value()); + REQUIRE_FALSE(sent->has_value()); + CHECK(sent->error().code == HttpErrorCode::ResponseBodySize); + REQUIRE(peer.has_value()); + CHECK(*peer == "HTTP/1.1 200 \r\nContent-Length: 5\r\n\r\n"); + } +} + +TEST_CASE("Connection.trailersNeedAChunkedFramingAndNoFramingField", "[http][connection]") +{ + // Trailers can only ride a chunked body, and a framing field among them would reframe the + // message after the fact. + SECTION("a trailer source under a Length framing") + { + auto wire = Wire {}; + auto client = Connection { + wire.loop, std::move(wire.pair.client), MessageRole::Response, HttpLimits {}, NoTimeouts + }; + auto source = BufferBodySource { "abc", fieldsOf({ { "X-A", "b" } }) }; + auto sent = std::optional> {}; + auto peer = std::optional {}; + wire.loop.spawn(into(readUntilClosed(wire.pair.server.get()), &peer)); + wire.loop.spawn( + into(sendRequest(&client, + requestHead("PUT", "/", { { "Host", "h" } }), + &source, + Framing { .kind = BodyFraming::Length, .length = 3, .persistence = {} }), + &sent)); + std::ignore = wire.loop.drain(); + REQUIRE(sent.has_value()); + REQUIRE_FALSE(sent->has_value()); + CHECK(sent->error().code == HttpErrorCode::ProtocolError); + CHECK(client.reusable() == Reuse::No); + client.close(); + std::ignore = wire.loop.drain(); + REQUIRE(peer.has_value()); + CHECK(peer->ends_with("Content-Length: 3\r\n\r\n")); // the head only, no body byte + } + SECTION("a framing field among the trailers") + { + auto wire = Wire {}; + auto client = Connection { + wire.loop, std::move(wire.pair.client), MessageRole::Response, HttpLimits {}, NoTimeouts + }; + auto source = BufferBodySource { "abc", fieldsOf({ { "Content-Length", "3" } }) }; + auto sent = std::optional> {}; + auto peer = std::optional {}; + wire.loop.spawn(into(bodyThenClose(&client, &source), &sent)); + wire.loop.spawn(into(readUntilClosed(wire.pair.server.get()), &peer)); + std::ignore = wire.loop.drain(); + REQUIRE(sent.has_value()); + REQUIRE_FALSE(sent->has_value()); + CHECK(sent->error().code == HttpErrorCode::ProtocolError); + REQUIRE(peer.has_value()); + CHECK_FALSE(peer->contains("Content-Length")); + } +} + +TEST_CASE("Connection.trailersCountAgainstTheLimits", "[http][connection]") +{ + // The connection's limits reach the chunked decoder: a trailer section past maxFields is the + // role's trailer-section code, as a head past it is the head's. + auto wire = Wire {}; + auto limits = HttpLimits {}; + limits.maxFields = 2; + auto connection = + Connection { wire.loop, std::move(wire.pair.client), MessageRole::Response, limits, NoTimeouts }; + wire.loop.spawn(writeAndClose(wire.pair.server.get(), + "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n" + "1\r\na\r\n0\r\nA: 1\r\nB: 2\r\nC: 3\r\n\r\n")); + auto received = std::optional {}; + wire.loop.spawn(into(receiveOne(&connection, "GET", 100), &received)); + std::ignore = wire.loop.drain(); + REQUIRE(received.has_value()); + REQUIRE(received->body.error.has_value()); + CHECK(received->body.error->code == HttpErrorCode::ResponseTrailerSectionSize); + CHECK(connection.reusable() == Reuse::No); +} + +TEST_CASE("Connection.aLengthBodyIsHeldToMaxBodyBytes", "[http][connection]") +{ + // The chunked decoder holds a chunked body to maxBodyBytes; a declared length is held to it here. + auto wire = Wire {}; + auto limits = HttpLimits {}; + limits.maxBodyBytes = 50; + auto connection = + Connection { wire.loop, std::move(wire.pair.server), MessageRole::Request, limits, NoTimeouts }; + wire.loop.spawn( + writeOnly(wire.pair.client.get(), "POST / HTTP/1.1\r\nHost: h\r\nContent-Length: 51\r\n\r\n")); + auto served = std::optional {}; + wire.loop.spawn(into(serveOne(&connection, 100), &served)); + std::ignore = wire.loop.drain(); + REQUIRE(served.has_value()); + REQUIRE(served->body.error.has_value()); + CHECK(served->body.error->code == HttpErrorCode::RequestBodySize); + CHECK(served->body.error->size == std::uint64_t { 51 }); + CHECK(connection.reusable() == Reuse::No); + wire.pair.client->close(); + std::ignore = wire.loop.drain(); +} + +TEST_CASE("Connection.aSilentPeerTimesOut", "[http][connection]") +{ + // Each deadline is asserted parked before the clock moves, so a read that never waited passes + // nothing. The first byte of a response head is the response's own timeout; every other wait is + // a read timeout. + struct Row + { + std::string_view name; + MessageRole role; + WireTimeouts timeouts; + std::string_view sent; ///< What the peer sends before it falls silent. + HttpErrorCode code; + }; + constexpr auto Rows = std::array { + Row { "request head, first byte", + MessageRole::Request, + WireTimeouts { .firstByte = 100ms, .betweenBytes = 0ms }, + "", + HttpErrorCode::ConnectionReadTimeout }, + Row { "response head, first byte", + MessageRole::Response, + WireTimeouts { .firstByte = 100ms, .betweenBytes = 0ms }, + "", + HttpErrorCode::ResponseTimeout }, + Row { "response head, between bytes", + MessageRole::Response, + WireTimeouts { .firstByte = 0ms, .betweenBytes = 100ms }, + "HTTP/1.1 200 OK\r\n", + HttpErrorCode::ConnectionReadTimeout }, + Row { "response body, between bytes", + MessageRole::Response, + WireTimeouts { .firstByte = 0ms, .betweenBytes = 100ms }, + "HTTP/1.1 200 OK\r\nContent-Length: 9\r\n\r\nab", + HttpErrorCode::ConnectionReadTimeout }, + Row { "request body, between bytes", + MessageRole::Request, + WireTimeouts { .firstByte = 0ms, .betweenBytes = 100ms }, + "POST / HTTP/1.1\r\nHost: h\r\nContent-Length: 9\r\n\r\nab", + HttpErrorCode::ConnectionReadTimeout }, + }; + for (auto const& row: Rows) + { + DYNAMIC_SECTION(row.name) + { + auto wire = Wire {}; + auto connection = + Connection { wire.loop, std::move(wire.pair.server), row.role, HttpLimits {}, row.timeouts }; + if (!row.sent.empty()) + wire.loop.spawn(writeOnly(wire.pair.client.get(), std::string { row.sent })); + auto code = std::optional {}; + auto received = std::optional {}; + auto served = std::optional {}; + if (row.role == MessageRole::Response) + wire.loop.spawn(into(receiveOne(&connection, "GET", 100), &received)); + else + wire.loop.spawn(into(serveOne(&connection, 100), &served)); + std::ignore = wire.loop.drain(); + REQUIRE_FALSE(received.has_value()); + REQUIRE_FALSE(served.has_value()); + + wire.clock.advance(99ms); + std::ignore = wire.loop.drain(); + REQUIRE_FALSE(received.has_value()); + REQUIRE_FALSE(served.has_value()); + + wire.clock.advance(1ms); + std::ignore = wire.loop.drain(); + if (row.role == MessageRole::Response) + { + REQUIRE(received.has_value()); + code = received->body.error.has_value() ? std::optional { received->body.error->code } + : received->error; + } + else + { + REQUIRE(served.has_value()); + code = served->body.error.has_value() ? std::optional { served->body.error->code } + : served->error; + } + CHECK(code == row.code); + CHECK(connection.reusable() == Reuse::No); + } + } +} + +TEST_CASE("Connection.aZeroTimeoutIsNone", "[http][connection]") +{ + // R31: a zero duration means no deadline, not one that fires at once. + auto wire = Wire {}; + auto connection = Connection { + wire.loop, std::move(wire.pair.client), MessageRole::Response, HttpLimits {}, NoTimeouts + }; + auto received = std::optional {}; + wire.loop.spawn(into(receiveOne(&connection, "GET", 100), &received)); + std::ignore = wire.loop.drain(); + wire.clock.advance(24h); + std::ignore = wire.loop.drain(); + REQUIRE_FALSE(received.has_value()); + + wire.loop.spawn(writeAndClose(wire.pair.server.get(), "HTTP/1.1 204 No Content\r\n\r\n")); + std::ignore = wire.loop.drain(); + REQUIRE(received.has_value()); + CHECK_FALSE(received->error.has_value()); + REQUIRE(received->head.has_value()); + CHECK(received->head->status == 204); + CHECK(connection.reusable() == Reuse::Yes); // a bodiless response is a finished one +} + +TEST_CASE("Connection.socketErrorsMapThroughTheTable", "[http][connection]") +{ + // A transport failure is classified once, by a row per NetErrorCode, and the direction decides + // what a timeout means. + struct Row + { + NetErrorCode net; + HttpErrorCode onRead; + HttpErrorCode onWrite; + }; + constexpr auto Rows = std::array { + Row { NetErrorCode::ConnReset, + HttpErrorCode::ConnectionTerminated, + HttpErrorCode::ConnectionTerminated }, + Row { NetErrorCode::Timeout, + HttpErrorCode::ConnectionReadTimeout, + HttpErrorCode::ConnectionWriteTimeout }, + Row { NetErrorCode::BadHandle, + HttpErrorCode::ConnectionTerminated, + HttpErrorCode::ConnectionTerminated }, + Row { NetErrorCode::HostUnreach, + HttpErrorCode::DestinationUnavailable, + HttpErrorCode::DestinationUnavailable }, + Row { NetErrorCode::SystemError, HttpErrorCode::InternalError, HttpErrorCode::InternalError }, + }; + for (auto const& row: Rows) + { + DYNAMIC_SECTION(core::net::toString(row.net)) + { + auto wire = Wire {}; + auto connection = Connection { wire.loop, + std::make_unique(*wire.pair.client, row.net), + MessageRole::Response, + HttpLimits {}, + NoTimeouts }; + auto head = std::optional> {}; + auto wrote = std::optional> {}; + wire.loop.spawn(into(connection.readResponseHead(), &head)); + wire.loop.spawn( + into(connection.writeRequestHead(requestHead("GET", "/", { { "Host", "h" } }), Framing {}), + &wrote)); + std::ignore = wire.loop.drain(); + REQUIRE(head.has_value()); + REQUIRE_FALSE(head->has_value()); + CHECK(head->error().code == row.onRead); + REQUIRE(wrote.has_value()); + REQUIRE_FALSE(wrote->has_value()); + CHECK(wrote->error().code == row.onWrite); + CHECK(connection.reusable() == Reuse::No); + } + } +} + +TEST_CASE("Connection.reuseFollowsTheExchange", "[http][connection]") +{ + SECTION("a second response in the same bytes is read after the first") + { + // Bytes past a body stay buffered for the next head. + auto wire = Wire {}; + auto connection = Connection { + wire.loop, std::move(wire.pair.client), MessageRole::Response, HttpLimits {}, NoTimeouts + }; + wire.loop.spawn(writeOnly(wire.pair.server.get(), + "HTTP/1.1 200 OK\r\nContent-Length: 3\r\n\r\nabcHTTP/1.1 201 " + "Created\r\nContent-Length: 2\r\n\r\nde")); + auto first = std::optional {}; + wire.loop.spawn(into(receiveOne(&connection, "GET", 100), &first)); + std::ignore = wire.loop.drain(); + REQUIRE(first.has_value()); + CHECK(first->body.text == "abc"); + CHECK(connection.reusable() == Reuse::Yes); + auto second = std::optional {}; + wire.loop.spawn(into(receiveOne(&connection, "GET", 100), &second)); + std::ignore = wire.loop.drain(); + REQUIRE(second.has_value()); + REQUIRE(second->head.has_value()); + CHECK(second->head->status == 201); + CHECK(second->body.text == "de"); + CHECK(connection.reusable() == Reuse::Yes); + wire.pair.server->close(); + std::ignore = wire.loop.drain(); + } + SECTION("a body left unread, and the same body read later") + { + auto wire = Wire {}; + auto connection = Connection { + wire.loop, std::move(wire.pair.client), MessageRole::Response, HttpLimits {}, NoTimeouts + }; + wire.loop.spawn(writeOnly(wire.pair.server.get(), "HTTP/1.1 200 OK\r\nContent-Length: 3\r\n\r\nabc")); + auto head = std::optional> {}; + wire.loop.spawn(into(connection.readResponseHead(), &head)); + std::ignore = wire.loop.drain(); + REQUIRE(head.has_value()); + REQUIRE(head->has_value()); + CHECK(connection.reusable() == Reuse::No); // a head read, its body not yet + + auto const framing = Framing { .kind = BodyFraming::Length, .length = 3, .persistence = {} }; + { + auto reader = connection.bodyReader(framing); + CHECK(connection.hasLiveBodyReader()); + auto chunk = std::optional> {}; + wire.loop.spawn(into(reader->read(1), &chunk)); + std::ignore = wire.loop.drain(); + REQUIRE(chunk.has_value()); + REQUIRE(chunk->has_value()); + CHECK(core::http::test::textOf((*chunk)->bytes) == "a"); + } + CHECK_FALSE(connection.hasLiveBodyReader()); + CHECK(connection.reusable() == Reuse::No); // two bytes unread + + auto reader = connection.bodyReader(framing); + auto rest = std::optional {}; + wire.loop.spawn(into(readAll(reader.get(), 100), &rest)); + std::ignore = wire.loop.drain(); + REQUIRE(rest.has_value()); + CHECK(rest->text == "bc"); + CHECK(connection.reusable() == Reuse::Yes); + wire.pair.server->close(); + std::ignore = wire.loop.drain(); + } + SECTION("persistence close") + { + auto wire = Wire {}; + auto connection = Connection { + wire.loop, std::move(wire.pair.client), MessageRole::Response, HttpLimits {}, NoTimeouts + }; + wire.loop.spawn(writeOnly(wire.pair.server.get(), + "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Length: 1\r\n\r\na")); + auto received = std::optional {}; + wire.loop.spawn(into(receiveOne(&connection, "GET", 100), &received)); + std::ignore = wire.loop.drain(); + REQUIRE(received.has_value()); + CHECK(received->body.text == "a"); + CHECK(connection.reusable() == Reuse::No); + wire.pair.server->close(); + std::ignore = wire.loop.drain(); + } + SECTION("until close reads to the peer's close") + { + auto wire = Wire {}; + auto connection = Connection { + wire.loop, std::move(wire.pair.client), MessageRole::Response, HttpLimits {}, NoTimeouts + }; + wire.loop.spawn(writeAndClose(wire.pair.server.get(), "HTTP/1.1 200 OK\r\n\r\n" + patternOf(100))); + auto received = std::optional {}; + wire.loop.spawn(into(receiveOne(&connection, "GET", 10), &received)); // under the pair's 16 + std::ignore = wire.loop.drain(); + REQUIRE(received.has_value()); + REQUIRE_FALSE(received->body.error.has_value()); + CHECK(received->body.text == patternOf(100)); + CHECK(std::ranges::all_of(received->body.chunkSizes, [](std::size_t size) { return size <= 10; })); + CHECK(connection.reusable() == Reuse::No); + } + SECTION("a head written with a body pending") + { + auto wire = Wire {}; + auto client = Connection { + wire.loop, std::move(wire.pair.client), MessageRole::Response, HttpLimits {}, NoTimeouts + }; + auto wrote = std::optional> {}; + wire.loop.spawn(into( + client.writeRequestHead(requestHead("PUT", "/", { { "Host", "h" } }), + Framing { .kind = BodyFraming::Length, .length = 2, .persistence = {} }), + &wrote)); + auto peer = std::optional {}; + wire.loop.spawn(into(readUntilClosed(wire.pair.server.get()), &peer)); + std::ignore = wire.loop.drain(); + REQUIRE(wrote.has_value()); + CHECK(wrote->has_value()); + CHECK(client.reusable() == Reuse::No); + auto source = BufferBodySource { "ab" }; + auto body = std::optional> {}; + wire.loop.spawn(into(client.writeBody(&source, core::http::framingFor(&source)), &body)); + std::ignore = wire.loop.drain(); + REQUIRE(body.has_value()); + CHECK(body->has_value()); + CHECK(client.reusable() == Reuse::Yes); + client.close(); + std::ignore = wire.loop.drain(); + REQUIRE(peer.has_value()); + CHECK(peer->ends_with("\r\n\r\nab")); + } + SECTION("close") + { + auto wire = Wire {}; + auto client = Connection { + wire.loop, std::move(wire.pair.client), MessageRole::Response, HttpLimits {}, NoTimeouts + }; + CHECK(client.reusable() == Reuse::Yes); + client.close(); + CHECK(client.reusable() == Reuse::No); + CHECK(client.socket().isClosed()); + } + SECTION("a socket closed past the connection") + { + // A lingering close goes through socket(), which the connection must still notice. + auto wire = Wire {}; + auto client = Connection { + wire.loop, std::move(wire.pair.client), MessageRole::Response, HttpLimits {}, NoTimeouts + }; + client.socket().close(); + CHECK(client.reusable() == Reuse::No); + } + SECTION("a head written with persistence close") + { + auto wire = Wire {}; + auto client = Connection { + wire.loop, std::move(wire.pair.client), MessageRole::Response, HttpLimits {}, NoTimeouts + }; + auto wrote = std::optional> {}; + wire.loop.spawn( + into(client.writeRequestHead( + requestHead("GET", "/", { { "Host", "h" } }), + Framing { .kind = BodyFraming::None, .length = 0, .persistence = Persistence::Close }), + &wrote)); + auto peer = std::optional {}; + wire.loop.spawn(into(readUntilClosed(wire.pair.server.get()), &peer)); + std::ignore = wire.loop.drain(); + REQUIRE(wrote.has_value()); + CHECK(wrote->has_value()); + CHECK_FALSE(client.socket().isClosed()); + CHECK(client.reusable() == Reuse::No); + client.close(); + std::ignore = wire.loop.drain(); + } +} + +TEST_CASE("Connection.aBodyReaderOutlivesItsConnection", "[http][connection]") +{ + // The reader shares the connection's state, so a pool that hands a body out may drop the + // connection first. + auto wire = Wire {}; + auto connection = std::make_unique( + wire.loop, std::move(wire.pair.client), MessageRole::Response, HttpLimits {}, NoTimeouts); + wire.loop.spawn( + writeAndClose(wire.pair.server.get(), "HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\nwxyz")); + auto head = std::optional> {}; + wire.loop.spawn(into(connection->readResponseHead(), &head)); + std::ignore = wire.loop.drain(); + REQUIRE(head.has_value()); + REQUIRE(head->has_value()); + auto reader = + connection->bodyReader(Framing { .kind = BodyFraming::Length, .length = 4, .persistence = {} }); + connection.reset(); + auto body = std::optional {}; + wire.loop.spawn(into(readAll(reader.get(), 100), &body)); + std::ignore = wire.loop.drain(); + REQUIRE(body.has_value()); + CHECK(body->text == "wxyz"); +} + +TEST_CASE("Connection.framingForAndBufferBodySource", "[http][connection]") +{ + CHECK(core::http::framingFor(nullptr).kind == BodyFraming::None); + + auto plain = BufferBodySource { "hello" }; + CHECK(plain.knownLength() == std::uint64_t { 5 }); + CHECK(plain.trailerIntent() == TrailerIntent::None); + auto const length = core::http::framingFor(&plain); + CHECK(length.kind == BodyFraming::Length); + CHECK(length.length == 5); + CHECK(length.persistence == Persistence::KeepAlive); + + auto withTrailers = BufferBodySource { "hello", fieldsOf({ { "X-A", "b" } }) }; + CHECK(withTrailers.trailerIntent() == TrailerIntent::Possible); + CHECK(core::http::framingFor(&withTrailers).kind == BodyFraming::Chunked); + + auto unknown = ChunksBodySource { { "a" } }; + CHECK(core::http::framingFor(&unknown).kind == BodyFraming::Chunked); + + auto clock = ManualClock {}; + auto loop = TestLoop { clock }; + auto chunk = std::optional> {}; + loop.spawn(into(plain.next(), &chunk)); + std::ignore = loop.drain(); + REQUIRE(chunk.has_value()); + REQUIRE(chunk->has_value()); + CHECK(core::http::test::textOf((*chunk)->bytes) == "hello"); + CHECK((*chunk)->end == BodyEnd::Reached); + auto trailers = std::optional> {}; + loop.spawn(into(withTrailers.trailers(), &trailers)); + std::ignore = loop.drain(); + REQUIRE(trailers.has_value()); + REQUIRE(trailers->has_value()); + CHECK((*trailers)->get("x-a").size() == 1); +} + +TEST_CASE("Connection.aFailedConnectionReadsNoFurtherHead", "[http][connection]") +{ + // After a timeout the peer may still send a head; it is not read, because the connection has + // already ruled itself out and the bytes it would parse are of unknown framing. + auto wire = Wire {}; + auto connection = Connection { wire.loop, + std::move(wire.pair.client), + MessageRole::Response, + HttpLimits {}, + WireTimeouts { .firstByte = 10ms, .betweenBytes = 0ms } }; + auto first = std::optional> {}; + wire.loop.spawn(into(connection.readResponseHead(), &first)); + std::ignore = wire.loop.drain(); + wire.clock.advance(10ms); + std::ignore = wire.loop.drain(); + REQUIRE(first.has_value()); + REQUIRE_FALSE(first->has_value()); + CHECK(first->error().code == HttpErrorCode::ResponseTimeout); + + wire.loop.spawn(writeOnly(wire.pair.server.get(), "HTTP/1.1 204 No Content\r\n\r\n")); + auto second = std::optional> {}; + wire.loop.spawn(into(connection.readResponseHead(), &second)); + std::ignore = wire.loop.drain(); + REQUIRE(second.has_value()); + REQUIRE_FALSE(second->has_value()); + CHECK(second->error().code == HttpErrorCode::ConnectionTerminated); + wire.pair.server->close(); + std::ignore = wire.loop.drain(); +} + +TEST_CASE("Connection.aReaderOfAnEarlierBodyReadsNothingOfTheNext", "[http][connection]") +{ + // A pool may re-use a connection while the reader of its last body is still held: that reader + // answers that its body is over, and never reads the next message's bytes. + auto wire = Wire {}; + auto connection = Connection { + wire.loop, std::move(wire.pair.client), MessageRole::Response, HttpLimits {}, NoTimeouts + }; + wire.loop.spawn( + writeOnly(wire.pair.server.get(), + "HTTP/1.1 200 OK\r\nContent-Length: 1\r\n\r\na" + "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n1\r\nb\r\n0\r\nX-T: 2\r\n\r\n")); + auto first = std::optional {}; + wire.loop.spawn(into(receiveOne(&connection, "GET", 100), &first)); + std::ignore = wire.loop.drain(); + REQUIRE(first.has_value()); + REQUIRE(first->head.has_value()); + CHECK(first->body.text == "a"); + + // A reader of the first body, made after it ended, then the second head. + auto stale = + connection.bodyReader(Framing { .kind = BodyFraming::Length, .length = 1, .persistence = {} }); + auto head = std::optional> {}; + wire.loop.spawn(into(connection.readResponseHead(), &head)); + std::ignore = wire.loop.drain(); + REQUIRE(head.has_value()); + REQUIRE(head->has_value()); + CHECK_FALSE(connection.hasLiveBodyReader()); + + // The next body is adopted first, so only the generation tells the stale reader apart. + auto current = + connection.bodyReader(Framing { .kind = BodyFraming::Chunked, .length = 0, .persistence = {} }); + auto staleRead = std::optional {}; + wire.loop.spawn(into(readAll(stale.get(), 100), &staleRead)); + std::ignore = wire.loop.drain(); + REQUIRE(staleRead.has_value()); + CHECK(staleRead->text.empty()); + + auto body = std::optional {}; + wire.loop.spawn(into(readAll(current.get(), 100), &body)); + std::ignore = wire.loop.drain(); + REQUIRE(body.has_value()); + CHECK(body->text == "b"); + auto staleTrailers = std::optional> {}; + wire.loop.spawn(into(stale->trailers(), &staleTrailers)); + auto trailers = std::optional> {}; + wire.loop.spawn(into(current->trailers(), &trailers)); + std::ignore = wire.loop.drain(); + REQUIRE(staleTrailers.has_value()); + REQUIRE(staleTrailers->has_value()); + CHECK((*staleTrailers)->entries().empty()); + REQUIRE(trailers.has_value()); + REQUIRE(trailers->has_value()); + CHECK((*trailers)->get("x-t").size() == 1); + wire.pair.server->close(); + std::ignore = wire.loop.drain(); +} + +TEST_CASE("Connection.anInterimResponseHasNoBodyToRead", "[http][connection]") +{ + // A 100 Continue is followed by the final response with no body reader between them. + auto wire = Wire {}; + auto connection = Connection { + wire.loop, std::move(wire.pair.client), MessageRole::Response, HttpLimits {}, NoTimeouts + }; + wire.loop.spawn(writeOnly(wire.pair.server.get(), + "HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok")); + auto interim = std::optional> {}; + wire.loop.spawn(into(connection.readResponseHead(), &interim)); + std::ignore = wire.loop.drain(); + REQUIRE(interim.has_value()); + REQUIRE(interim->has_value()); + CHECK((*interim)->status == 100); + auto finalResponse = std::optional {}; + wire.loop.spawn(into(receiveOne(&connection, "GET", 100), &finalResponse)); + std::ignore = wire.loop.drain(); + REQUIRE(finalResponse.has_value()); + REQUIRE(finalResponse->head.has_value()); + CHECK(finalResponse->head->status == 200); + CHECK(finalResponse->body.text == "ok"); + CHECK(connection.reusable() == Reuse::Yes); + wire.pair.server->close(); + std::ignore = wire.loop.drain(); +} + +TEST_CASE("Connection.aFailedBodyRepeatsItsFailure", "[http][connection]") +{ + // Once a body has failed, a later read of it reports the same failure instead of reading on. + auto wire = Wire {}; + auto connection = Connection { + wire.loop, std::move(wire.pair.client), MessageRole::Response, HttpLimits {}, NoTimeouts + }; + wire.loop.spawn( + writeOnly(wire.pair.server.get(), "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\nzz\r\n")); + auto received = std::optional {}; + wire.loop.spawn(into(receiveOne(&connection, "GET", 100), &received)); + std::ignore = wire.loop.drain(); + REQUIRE(received.has_value()); + REQUIRE(received->body.error.has_value()); + CHECK(received->body.error->code == HttpErrorCode::ProtocolError); + auto again = + connection.bodyReader(Framing { .kind = BodyFraming::Chunked, .length = 0, .persistence = {} }); + auto chunk = std::optional> {}; + wire.loop.spawn(into(again->read(100), &chunk)); + std::ignore = wire.loop.drain(); + REQUIRE(chunk.has_value()); + REQUIRE_FALSE(chunk->has_value()); + CHECK(chunk->error().code == HttpErrorCode::ProtocolError); + wire.pair.server->close(); + std::ignore = wire.loop.drain(); +} + +TEST_CASE("Connection.aSourceIsHeldToWhatTheHeadAnnounced", "[http][connection]") +{ + SECTION("a source that claims one length and streams another is refused before any body byte") + { + auto wire = Wire {}; + auto client = Connection { + wire.loop, std::move(wire.pair.client), MessageRole::Response, HttpLimits {}, NoTimeouts + }; + auto source = ChunksBodySource { { "abc", "de" }, std::uint64_t { 6 } }; + auto sent = std::optional> {}; + auto peer = std::optional {}; + wire.loop.spawn(into( + sendRequestThenClose( + &client, &source, Framing { .kind = BodyFraming::Length, .length = 5, .persistence = {} }), + &sent)); + wire.loop.spawn(into(readUntilClosed(wire.pair.server.get()), &peer)); + std::ignore = wire.loop.drain(); + REQUIRE(sent.has_value()); + REQUIRE_FALSE(sent->has_value()); + CHECK(sent->error().code == HttpErrorCode::RequestBodySize); + CHECK(sent->error().size == std::uint64_t { 6 }); + REQUIRE(peer.has_value()); + CHECK(*peer == "PUT / HTTP/1.1\r\nHost: h\r\nContent-Length: 5\r\n\r\n"); + } + SECTION("a head with no body, and a source with bytes") + { + auto wire = Wire {}; + auto client = Connection { + wire.loop, std::move(wire.pair.client), MessageRole::Response, HttpLimits {}, NoTimeouts + }; + auto source = ChunksBodySource { { "x" } }; + auto sent = std::optional> {}; + auto peer = std::optional {}; + wire.loop.spawn(into(sendRequestThenClose(&client, &source, Framing {}), &sent)); + wire.loop.spawn(into(readUntilClosed(wire.pair.server.get()), &peer)); + std::ignore = wire.loop.drain(); + REQUIRE(sent.has_value()); + REQUIRE_FALSE(sent->has_value()); + CHECK(sent->error().code == HttpErrorCode::RequestBodySize); + REQUIRE(peer.has_value()); + CHECK(*peer == "PUT / HTTP/1.1\r\nHost: h\r\n\r\n"); + } + SECTION("no source under a chunked framing still ends the body") + { + auto wire = Wire {}; + auto client = Connection { + wire.loop, std::move(wire.pair.client), MessageRole::Response, HttpLimits {}, NoTimeouts + }; + auto sent = std::optional> {}; + auto peer = std::optional {}; + wire.loop.spawn(into( + sendRequestThenClose( + &client, nullptr, Framing { .kind = BodyFraming::Chunked, .length = 0, .persistence = {} }), + &sent)); + wire.loop.spawn(into(readUntilClosed(wire.pair.server.get()), &peer)); + std::ignore = wire.loop.drain(); + REQUIRE(sent.has_value()); + CHECK(sent->has_value()); + REQUIRE(peer.has_value()); + CHECK(peer->ends_with("Transfer-Encoding: chunked\r\n\r\n0\r\n\r\n")); + } +} + +TEST_CASE("Connection.aRefusedHeadIsTheParsersRefusal", "[http][connection]") +{ + // The head parser's refusal reaches the caller as it is, and rules the connection out. + auto wire = Wire {}; + auto connection = Connection { + wire.loop, std::move(wire.pair.server), MessageRole::Request, HttpLimits {}, NoTimeouts + }; + wire.loop.spawn(writeOnly(wire.pair.client.get(), "GET / HTTP/1.1\nHost: h\r\n\r\n")); + auto head = std::optional> {}; + wire.loop.spawn(into(connection.readRequestHead(), &head)); + std::ignore = wire.loop.drain(); + REQUIRE(head.has_value()); + REQUIRE_FALSE(head->has_value()); + CHECK(head->error().code == HttpErrorCode::ProtocolError); + CHECK(connection.reusable() == Reuse::No); + wire.pair.client->close(); + std::ignore = wire.loop.drain(); +} + +TEST_CASE("Connection.aZeroByteReadReadsNothing", "[http][connection]") +{ + // Over a chunked body, where feeding the decoder nothing would make no progress at all. + auto wire = Wire {}; + auto connection = Connection { + wire.loop, std::move(wire.pair.client), MessageRole::Response, HttpLimits {}, NoTimeouts + }; + wire.loop.spawn(writeOnly(wire.pair.server.get(), + "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n2\r\nok\r\n0\r\n\r\n")); + auto head = std::optional> {}; + wire.loop.spawn(into(connection.readResponseHead(), &head)); + std::ignore = wire.loop.drain(); + REQUIRE(head.has_value()); + REQUIRE(head->has_value()); + auto reader = + connection.bodyReader(Framing { .kind = BodyFraming::Chunked, .length = 0, .persistence = {} }); + auto empty = std::optional> {}; + wire.loop.spawn(into(reader->read(0), &empty)); + std::ignore = wire.loop.drain(); + REQUIRE(empty.has_value()); + REQUIRE(empty->has_value()); + CHECK((*empty)->bytes.empty()); + CHECK((*empty)->end == BodyEnd::More); + auto rest = std::optional {}; + wire.loop.spawn(into(readAll(reader.get(), 100), &rest)); + std::ignore = wire.loop.drain(); + REQUIRE(rest.has_value()); + CHECK(rest->text == "ok"); + wire.pair.server->close(); + std::ignore = wire.loop.drain(); +} + +TEST_CASE("Connection.aCloseExchangeStillReadsItsAnswer", "[http][connection]") +{ + // Persistence::Close rules out the NEXT message, not the rest of this one. + SECTION("a client that sent Connection: close reads the response") + { + auto wire = Wire {}; + auto client = Connection { + wire.loop, std::move(wire.pair.client), MessageRole::Response, HttpLimits {}, NoTimeouts + }; + auto server = Connection { + wire.loop, std::move(wire.pair.server), MessageRole::Request, HttpLimits {}, NoTimeouts + }; + auto const close = + Framing { .kind = BodyFraming::None, .length = 0, .persistence = Persistence::Close }; + auto sent = std::optional> {}; + auto served = std::optional {}; + wire.loop.spawn( + into(sendRequest(&client, requestHead("GET", "/", { { "Host", "h" } }), nullptr, close), &sent)); + wire.loop.spawn(into(serveOne(&server, 100), &served)); + std::ignore = wire.loop.drain(); + REQUIRE(sent.has_value()); + CHECK(sent->has_value()); + REQUIRE(served.has_value()); + REQUIRE(served->head.has_value()); + CHECK(server.reusable() == Reuse::No); // it read Connection: close + + auto reply = BufferBodySource { "bye" }; + auto replied = std::optional> {}; + auto received = std::optional {}; + auto replyFraming = core::http::framingFor(&reply); + replyFraming.persistence = Persistence::Close; + wire.loop.spawn(into(sendResponse(&server, responseHead(200, {}), &reply, replyFraming), &replied)); + wire.loop.spawn(into(receiveOne(&client, "GET", 100), &received)); + std::ignore = wire.loop.drain(); + REQUIRE(replied.has_value()); + CHECK(replied->has_value()); + REQUIRE(received.has_value()); + REQUIRE_FALSE(received->error.has_value()); + CHECK(received->body.text == "bye"); + CHECK(client.reusable() == Reuse::No); + CHECK(server.reusable() == Reuse::No); + + // The exchange is over on both ends: no further head is read, whatever arrives. + auto nextResponse = std::optional> {}; + auto nextRequest = std::optional> {}; + wire.loop.spawn(into(client.readResponseHead(), &nextResponse)); + wire.loop.spawn(into(server.readRequestHead(), &nextRequest)); + std::ignore = wire.loop.drain(); + REQUIRE(nextResponse.has_value()); + REQUIRE_FALSE(nextResponse->has_value()); + CHECK(nextResponse->error().code == HttpErrorCode::ConnectionTerminated); + REQUIRE(nextRequest.has_value()); + REQUIRE_FALSE(nextRequest->has_value()); + CHECK(nextRequest->error().code == HttpErrorCode::ConnectionTerminated); + } + SECTION("an HTTP/1.0 exchange, both ends") + { + auto wire = Wire {}; + auto client = Connection { + wire.loop, std::move(wire.pair.client), MessageRole::Response, HttpLimits {}, NoTimeouts + }; + auto server = Connection { + wire.loop, std::move(wire.pair.server), MessageRole::Request, HttpLimits {}, NoTimeouts + }; + auto const close = + Framing { .kind = BodyFraming::None, .length = 0, .persistence = Persistence::Close }; + auto sent = std::optional> {}; + auto served = std::optional {}; + wire.loop.spawn(into( + sendRequest( + &client, requestHead("GET", "/", { { "Host", "h" } }, HttpVersion::Http10), nullptr, close), + &sent)); + wire.loop.spawn(into(serveOne(&server, 100), &served)); + std::ignore = wire.loop.drain(); + REQUIRE(served.has_value()); + REQUIRE(served->head.has_value()); + CHECK(served->head->version == HttpVersion::Http10); + + auto reply = BufferBodySource { "old" }; + auto head = responseHead(200, {}); + head.version = HttpVersion::Http10; + auto replyFraming = core::http::framingFor(&reply); + replyFraming.persistence = Persistence::Close; + auto replied = std::optional> {}; + auto received = std::optional {}; + wire.loop.spawn(into(sendResponse(&server, std::move(head), &reply, replyFraming), &replied)); + wire.loop.spawn(into(receiveOne(&client, "GET", 100), &received)); + std::ignore = wire.loop.drain(); + REQUIRE(received.has_value()); + REQUIRE_FALSE(received->error.has_value()); + CHECK(received->body.text == "old"); + CHECK(client.reusable() == Reuse::No); + } +} + +TEST_CASE("Connection.aResponseToHeadAnnouncesItsLengthAndSendsNoBody", "[http][connection]") +{ + // RFC 9110 9.3.2: the response to HEAD carries the fields a GET's would, and no body; the + // connection stays reusable on both ends and carries the next exchange. + auto wire = Wire {}; + auto client = Connection { + wire.loop, std::move(wire.pair.client), MessageRole::Response, HttpLimits {}, NoTimeouts + }; + auto server = Connection { + wire.loop, std::move(wire.pair.server), MessageRole::Request, HttpLimits {}, NoTimeouts + }; + auto exchange = [&](std::string_view method, std::string_view expectedBody) { + auto sent = std::optional> {}; + auto served = std::optional {}; + wire.loop.spawn(into( + sendRequest(&client, requestHead(method, "/", { { "Host", "h" } }), nullptr, Framing {}), &sent)); + wire.loop.spawn(into(serveOne(&server, 100), &served)); + std::ignore = wire.loop.drain(); + REQUIRE(served.has_value()); + REQUIRE(served->head.has_value()); + auto reply = BufferBodySource { "hello" }; + auto replied = std::optional> {}; + auto received = std::optional {}; + wire.loop.spawn(into( + sendResponse(&server, responseHead(200, {}), &reply, core::http::framingFor(&reply)), &replied)); + wire.loop.spawn(into(receiveOne(&client, std::string { method }, 100), &received)); + std::ignore = wire.loop.drain(); + REQUIRE(replied.has_value()); + CHECK(replied->has_value()); + REQUIRE(received.has_value()); + REQUIRE_FALSE(received->error.has_value()); + REQUIRE(received->head.has_value()); + auto const length = received->head->fields.get("content-length"); + REQUIRE(length.size() == 1); + CHECK(length.front() == "5"); + CHECK(received->body.text == expectedBody); + CHECK(server.reusable() == Reuse::Yes); + CHECK(client.reusable() == Reuse::Yes); + }; + exchange("HEAD", ""); + exchange("GET", "hello"); // the HEAD left no stray body bytes behind +} + +TEST_CASE("Connection.aHeadResponseWithNoFramingSaysNothing", "[http][connection]") +{ + // A HEAD reply with BodyFraming::None must not claim Content-Length: 0 for the GET it stands for. + auto wire = Wire {}; + auto server = Connection { + wire.loop, std::move(wire.pair.server), MessageRole::Request, HttpLimits {}, NoTimeouts + }; + wire.loop.spawn(writeOnly(wire.pair.client.get(), "HEAD / HTTP/1.1\r\nHost: h\r\n\r\n")); + auto served = std::optional {}; + wire.loop.spawn(into(serveOne(&server, 100), &served)); + std::ignore = wire.loop.drain(); + REQUIRE(served.has_value()); + REQUIRE(served->head.has_value()); + auto wrote = std::optional> {}; + auto peer = std::optional {}; + wire.loop.spawn(into(responseHeadThenClose(&server, responseHead(200, {}), Framing {}), &wrote)); + wire.loop.spawn(into(readUntilClosed(wire.pair.client.get()), &peer)); + std::ignore = wire.loop.drain(); + REQUIRE(peer.has_value()); + CHECK(*peer == "HTTP/1.1 200 \r\n\r\n"); +} + +TEST_CASE("Connection.aBodyFollowsTheFramingItsHeadAnnounced", "[http][connection]") +{ + // writeBody under a framing other than the head's would contradict the wire; refused, with + // nothing of the body written. + auto wire = Wire {}; + auto client = Connection { + wire.loop, std::move(wire.pair.client), MessageRole::Response, HttpLimits {}, NoTimeouts + }; + auto source = BufferBodySource { "abc" }; + auto body = std::optional> {}; + auto peer = std::optional {}; + wire.loop.spawn(into(readUntilClosed(wire.pair.server.get()), &peer)); + wire.loop.spawn(into(headThenOtherBody(&client, &source), &body)); + std::ignore = wire.loop.drain(); + REQUIRE(body.has_value()); + REQUIRE_FALSE(body->has_value()); + CHECK(body->error().code == HttpErrorCode::ProtocolError); + CHECK(client.reusable() == Reuse::No); + client.close(); + std::ignore = wire.loop.drain(); + REQUIRE(peer.has_value()); + CHECK(peer->ends_with("Content-Length: 3\r\n\r\n")); +} + +TEST_CASE("Connection.anUntilCloseBodyIsHeldToMaxBodyBytes", "[http][connection]") +{ + auto wire = Wire {}; + auto limits = HttpLimits {}; + limits.maxBodyBytes = 50; + auto connection = + Connection { wire.loop, std::move(wire.pair.client), MessageRole::Response, limits, NoTimeouts }; + wire.loop.spawn(writeAndClose(wire.pair.server.get(), "HTTP/1.1 200 OK\r\n\r\n" + patternOf(100))); + auto received = std::optional {}; + wire.loop.spawn(into(receiveOne(&connection, "GET", 10), &received)); + std::ignore = wire.loop.drain(); + REQUIRE(received.has_value()); + REQUIRE(received->body.error.has_value()); + CHECK(received->body.error->code == HttpErrorCode::ResponseBodySize); + CHECK(received->body.text.size() <= 50); // never more than the limit handed out + CHECK(patternOf(100).starts_with(received->body.text)); +} + +TEST_CASE("Connection.theRequestRoleIsSerial", "[http][connection]") +{ + // Two pipelined requests: the second head is not read until the first response is written, + // and then it is, intact. + auto wire = Wire {}; + auto server = Connection { + wire.loop, std::move(wire.pair.server), MessageRole::Request, HttpLimits {}, NoTimeouts + }; + wire.loop.spawn(writeOnly(wire.pair.client.get(), + "GET /one HTTP/1.1\r\nHost: h\r\n\r\nGET /two HTTP/1.1\r\nHost: h\r\n\r\n" + "GET /three HTTP/1.1\r\nHost: h\r\n\r\n")); + auto first = std::optional {}; + wire.loop.spawn(into(serveOne(&server, 100), &first)); + std::ignore = wire.loop.drain(); + REQUIRE(first.has_value()); + REQUIRE(first->head.has_value()); + CHECK(first->head->target.text() == "/one"); + + auto early = std::optional> {}; + wire.loop.spawn(into(server.readRequestHead(), &early)); + std::ignore = wire.loop.drain(); + REQUIRE(early.has_value()); + REQUIRE_FALSE(early->has_value()); + CHECK(early->error().code == HttpErrorCode::ProtocolError); + + auto reply = BufferBodySource { "1" }; + auto replied = std::optional> {}; + auto peer = std::optional {}; + wire.loop.spawn(into(readUntilClosed(wire.pair.client.get()), &peer)); + wire.loop.spawn( + into(sendResponse(&server, responseHead(200, {}), &reply, core::http::framingFor(&reply)), &replied)); + std::ignore = wire.loop.drain(); + REQUIRE(replied.has_value()); + CHECK(replied->has_value()); + + auto second = std::optional {}; + wire.loop.spawn(into(serveOne(&server, 100), &second)); + std::ignore = wire.loop.drain(); + REQUIRE(second.has_value()); + REQUIRE(second->head.has_value()); + CHECK(second->head->target.text() == "/two"); + + // A bodiless final response answers its request with the head alone. + auto noContent = std::optional> {}; + wire.loop.spawn(into(server.writeResponseHead(responseHead(204, {}), Framing {}), &noContent)); + std::ignore = wire.loop.drain(); + REQUIRE(noContent.has_value()); + CHECK(noContent->has_value()); + auto third = std::optional {}; + wire.loop.spawn(into(serveOne(&server, 100), &third)); + std::ignore = wire.loop.drain(); + REQUIRE(third.has_value()); + REQUIRE(third->head.has_value()); + CHECK(third->head->target.text() == "/three"); + server.close(); + std::ignore = wire.loop.drain(); +} + +TEST_CASE("Connection.anInterimResponseLeavesAHeadReplyBodiless", "[http][connection]") +{ + // 100 Continue answers nothing; the final response to the HEAD is still sent without a body. + auto wire = Wire {}; + auto server = Connection { + wire.loop, std::move(wire.pair.server), MessageRole::Request, HttpLimits {}, NoTimeouts + }; + wire.loop.spawn(writeOnly(wire.pair.client.get(), "HEAD / HTTP/1.1\r\nHost: h\r\n\r\n")); + auto served = std::optional {}; + wire.loop.spawn(into(serveOne(&server, 100), &served)); + std::ignore = wire.loop.drain(); + REQUIRE(served.has_value()); + REQUIRE(served->head.has_value()); + + auto peer = std::optional {}; + wire.loop.spawn(into(readUntilClosed(wire.pair.client.get()), &peer)); + auto interim = std::optional> {}; + wire.loop.spawn(into(server.writeResponseHead(responseHead(100, {}), Framing {}), &interim)); + std::ignore = wire.loop.drain(); + REQUIRE(interim.has_value()); + REQUIRE(interim->has_value()); + auto reply = BufferBodySource { "hello" }; + auto replied = std::optional> {}; + wire.loop.spawn( + into(sendResponse(&server, responseHead(200, {}), &reply, core::http::framingFor(&reply)), &replied)); + std::ignore = wire.loop.drain(); + REQUIRE(replied.has_value()); + CHECK(replied->has_value()); + CHECK(server.reusable() == Reuse::Yes); + server.close(); + std::ignore = wire.loop.drain(); + REQUIRE(peer.has_value()); + CHECK(*peer == "HTTP/1.1 100 \r\n\r\nHTTP/1.1 200 \r\nContent-Length: 5\r\n\r\n"); +} + +TEST_CASE("Connection.aRefusedRequestCanStillBeAnswered", "[http][connection]") +{ + // A failure on the read side leaves the write side free: the server answers 400, then closes. + auto wire = Wire {}; + auto server = Connection { + wire.loop, std::move(wire.pair.server), MessageRole::Request, HttpLimits {}, NoTimeouts + }; + wire.loop.spawn(writeOnly(wire.pair.client.get(), "GET / HTTP/1.1\nHost: h\r\n\r\n")); + auto head = std::optional> {}; + wire.loop.spawn(into(server.readRequestHead(), &head)); + std::ignore = wire.loop.drain(); + REQUIRE(head.has_value()); + REQUIRE_FALSE(head->has_value()); + + auto peer = std::optional {}; + wire.loop.spawn(into(readUntilClosed(wire.pair.client.get()), &peer)); + auto answered = std::optional> {}; + wire.loop.spawn( + into(responseHeadThenClose( + &server, + responseHead(400, {}), + Framing { .kind = BodyFraming::None, .length = 0, .persistence = Persistence::Close }), + &answered)); + std::ignore = wire.loop.drain(); + REQUIRE(answered.has_value()); + CHECK(answered->has_value()); + REQUIRE(peer.has_value()); + CHECK(*peer == "HTTP/1.1 400 \r\nContent-Length: 0\r\nConnection: close\r\n\r\n"); +} + +TEST_CASE("Connection.aRefusedHeadDoesNotParseWhatFollowsIt", "[http][connection]") +{ + // The bytes after a refused head are already buffered, and of unknown framing: never parsed. + auto wire = Wire {}; + auto server = Connection { + wire.loop, std::move(wire.pair.server), MessageRole::Request, HttpLimits {}, NoTimeouts + }; + wire.loop.spawn( + writeOnly(wire.pair.client.get(), "GET / HTTP/1.1\nX\r\n\r\nGET / HTTP/1.1\r\nHost: h\r\n\r\n")); + auto first = std::optional> {}; + wire.loop.spawn(into(server.readRequestHead(), &first)); + std::ignore = wire.loop.drain(); + REQUIRE(first.has_value()); + REQUIRE_FALSE(first->has_value()); + auto second = std::optional> {}; + wire.loop.spawn(into(server.readRequestHead(), &second)); + std::ignore = wire.loop.drain(); + REQUIRE(second.has_value()); + REQUIRE_FALSE(second->has_value()); + CHECK(second->error().code == HttpErrorCode::ConnectionTerminated); + server.close(); + std::ignore = wire.loop.drain(); +} + +TEST_CASE("Connection.aHeadRefusedForItsFramingCanBeCorrected", "[http][connection]") +{ + // A framing the status cannot carry is refused before the first wire byte, so a corrected head + // follows it and the connection stays reusable. + auto wire = Wire {}; + auto server = Connection { + wire.loop, std::move(wire.pair.server), MessageRole::Request, HttpLimits {}, NoTimeouts + }; + wire.loop.spawn(writeOnly(wire.pair.client.get(), "GET / HTTP/1.1\r\nHost: h\r\n\r\n")); + auto served = std::optional {}; + wire.loop.spawn(into(serveOne(&server, 100), &served)); + std::ignore = wire.loop.drain(); + REQUIRE(served.has_value()); + REQUIRE(served->head.has_value()); + + auto peer = std::optional {}; + wire.loop.spawn(into(readUntilClosed(wire.pair.client.get()), &peer)); + auto refused = std::optional> {}; + wire.loop.spawn(into( + server.writeResponseHead(responseHead(204, {}), + Framing { .kind = BodyFraming::Length, .length = 3, .persistence = {} }), + &refused)); + std::ignore = wire.loop.drain(); + REQUIRE(refused.has_value()); + REQUIRE_FALSE(refused->has_value()); + CHECK(refused->error().code == HttpErrorCode::ProtocolError); + auto corrected = std::optional> {}; + wire.loop.spawn(into(server.writeResponseHead(responseHead(204, {}), Framing {}), &corrected)); + std::ignore = wire.loop.drain(); + REQUIRE(corrected.has_value()); + CHECK(corrected->has_value()); + CHECK(server.reusable() == Reuse::Yes); + server.close(); + std::ignore = wire.loop.drain(); + REQUIRE(peer.has_value()); + CHECK(*peer == "HTTP/1.1 204 \r\n\r\n"); +} diff --git a/src/core/http/HttpTestSupport.hpp b/src/core/http/HttpTestSupport.hpp new file mode 100644 index 00000000..69a56713 --- /dev/null +++ b/src/core/http/HttpTestSupport.hpp @@ -0,0 +1,120 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// Test-only helpers the `core::http` cases share: raw wire text written to a socket, a body read +/// to its end, and a flow run on a hand-driven loop until it has an answer. Test-only: in no +/// `FILE_SET`, so never installed. + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace core::http::test +{ + +/// Whether this process runs under wine rather than on Windows or a POSIX system. Defined per +/// platform (`posix/HttpTestSupport.cpp`, `windows/HttpTestSupport.cpp`); only a binary that links +/// one of them may call it. A case uses it to accept a behaviour wine has and no native kernel +/// does, and to fail where the same behaviour shows natively. A @c bool because the name asks it. +[[nodiscard]] bool runsUnderWine() noexcept; + +/// @param text The bytes to view. +/// @return @p text as the byte span a socket write takes. +[[nodiscard]] inline std::span bytesOf(std::string_view text) noexcept +{ + return { reinterpret_cast(text.data()), text.size() }; +} + +/// @param bytes Bytes a socket or a body reader handed out. +/// @return The same bytes as text. +[[nodiscard]] inline std::string textOf(std::span bytes) +{ + return { reinterpret_cast(bytes.data()), bytes.size() }; +} + +/// Writes @p text to @p socket in full, then closes it: a peer that sends exactly these bytes. +/// @param socket The writer; must outlive the returned task. +/// @param text The wire bytes, owned by the frame. +inline async::Task writeAndClose(net::ISocket* socket, std::string text) +{ + if (!text.empty()) + static_cast(co_await socket->write(bytesOf(text))); + socket->close(); +} + +/// Writes @p text to @p socket in full and leaves it open: a peer that then falls silent. +/// @param socket The writer; must outlive the returned task. +/// @param text The wire bytes, owned by the frame. +inline async::Task writeOnly(net::ISocket* socket, std::string text) +{ + static_cast(co_await socket->write(bytesOf(text))); +} + +/// Reads from @p socket until EOF or an error: what a peer received. +/// @param socket The reader; must outlive the returned task. +/// @return Every byte read, in order. +inline async::Task readUntilClosed(net::ISocket* socket) +{ + auto text = std::string {}; + auto chunk = std::vector(256); + while (true) + { + auto const got = co_await socket->read(std::span { chunk }); + if (!got.has_value() || *got == 0) + co_return text; + text += textOf(std::span { chunk }.first(*got)); + } +} + +/// A body read to its end, chunk by chunk. +struct ReadBody +{ + std::string text; ///< Every body byte, in order. + std::vector chunkSizes; ///< The size of each chunk @c read handed out. + std::optional error; ///< What ended the read early, if anything did. +}; + +/// Reads @p reader until @c BodyEnd::Reached or an error, @p maxBytes at a time. +/// @param reader The body; must outlive the returned task. +/// @param maxBytes What each @c read asks for. +/// @return What was read and what, if anything, ended it. +inline async::Task readAll(IBodyReader* reader, std::size_t maxBytes) +{ + auto out = ReadBody {}; + while (true) + { + auto chunk = co_await reader->read(maxBytes); + if (!chunk.has_value()) + { + out.error = std::move(chunk.error()); + co_return out; + } + out.chunkSizes.push_back(chunk->bytes.size()); + out.text += textOf(chunk->bytes); + if (chunk->end == BodyEnd::Reached) + co_return out; + } +} + +/// Runs @p task and stores its answer in @p out, for a case that drives the loop by hand and then +/// asserts the answer is there: a flow that never finishes leaves @p out empty, never a hang. +/// @tparam T The task's result. +/// @param task The flow. +/// @param out Where its answer goes; must outlive the returned task. +template +async::Task into(async::Task task, std::optional* out) +{ + *out = co_await std::move(task); +} + +} // namespace core::http::test diff --git a/src/core/http/posix/HttpTestSupport.cpp b/src/core/http/posix/HttpTestSupport.cpp new file mode 100644 index 00000000..2d7d156f --- /dev/null +++ b/src/core/http/posix/HttpTestSupport.cpp @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The POSIX half of HttpTestSupport.hpp's platform questions: no POSIX process runs under wine. +#include + +namespace core::http::test +{ + +bool runsUnderWine() noexcept +{ + return false; +} + +} // namespace core::http::test diff --git a/src/core/http/windows/HttpTestSupport.cpp b/src/core/http/windows/HttpTestSupport.cpp new file mode 100644 index 00000000..780cc0e6 --- /dev/null +++ b/src/core/http/windows/HttpTestSupport.cpp @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The Windows half of HttpTestSupport.hpp's platform questions. Wine's ntdll exports +// `wine_get_version`, and no Windows ntdll does: that export is wine's own documented way for a +// program to tell, and the one a case uses before it accepts a behaviour only wine has. +#include + +#include + +namespace core::http::test +{ + +bool runsUnderWine() noexcept +{ + auto* const ntdll = GetModuleHandleW(L"ntdll.dll"); + return ntdll != nullptr && GetProcAddress(ntdll, "wine_get_version") != nullptr; +} + +} // namespace core::http::test From c07908cc9ee6f4dcd343895b5c8f928a15165171 Mon Sep 17 00:00:00 2001 From: Christian Parpart Date: Fri, 27 Nov 2026 03:48:52 +0100 Subject: [PATCH 13/19] feat(http): coroutine HTTP/1.1 client with TLS, a keep-alive pool and classified errors Coroutine HTTP/1.1 client with TLS and classified errors. HttpClient sends one request over a connection of its own: the dial through an injected IConnector, TLS through an injected ITlsContext, the exchange through a Connection, and every failure on the way classified. - Refused before the dial: an empty or malformed host (RequestUriInvalid), a caller's Host or framing field (ProtocolError), and https without a TLS context (ConfigurationError). Host is written first, from the origin: bracketed for IPv6, with the port unless it is the scheme's. - Dial and handshake-transport failures map through one row table (NameNotFound, ResolverTemporaryFailure, AddressError -> DnsError; ConnRefused -> ConnectionRefused; HostUnreach -> DestinationUnavailable; Timeout -> ConnectionTimeout; ConnReset, Eof -> ConnectionTerminated). - TLS: wrapClient binds the bare host (no port, no brackets). A context that cannot verify a per-connection name -- every legacy one (R23) -- is ConfigurationError. The handshake runs at once, bounded by the connect timeout, before any request byte; a session failure is TlsProtocolError, TlsCertificateError or TlsAlertReceived with the TlsFailure attached, during the handshake and during the exchange alike. - The request is written while the response head is read (whenAll). Interim responses are skipped; a 101 is a ProtocolError. A failed read closes the connection, ending a write in progress; a failed write closes it too and is the answer, unless the peer cut the connection, when the read goes on so an answering-then-closing server (a 413) is heard. Connection's response timeout no longer runs while a request is being written: under whenAll a slow upload saw a false ResponseTimeout. The first-byte deadline of a response head read is held from the call of writeRequestHead or writeBody to its return, the body source's waits included, and starts afresh when it ends; a head written alone (Expect: 100-continue) leaves it running. Pinned in memory and over real sockets on every backend. testing::ScriptedConnector dials in memory, with refusals and a dial log. HttpTestSupport.hpp gains a scripted TLS context and a legacy one (R29: the http binary links no net_tls), a scripted server end and a slow body source. HttpClient keeps no idle connection yet; the pool is next. Keep-alive pool with a per-origin cap and a safe retry rule. HttpClient keeps idle connections per origin (scheme, lowercased host, effective port) under maxIdlePerOrigin, idleTimeout on the loop's clock and maxConnectionsPerOrigin (ConnectionLimitReached past it). A response body gives its connection back at BodyEnd::Reached only when Connection::reusable() says Yes, holding the pool weakly; otherwise, on failure, drop or a destroyed client it closes it. A pooled connection that fails before any response head with a transport failure is retried once on a fresh dial, only for an idempotent method with no body handed over. Client timeouts default to 600 seconds. HttpTimeouts defaulted every deadline to zero, which bounds nothing, so a client built with no options waited for a silent server for ever. connect, firstByte and betweenBytes now default to 600 s, wasmtime's wasi:http default; zero still means no deadline. Also in this commit: - wasmtime's first-byte timeout, a stopped write, strict hosts - a total connection cap, an origin swept before its idle cap, a guarded moved-from client - never pool a response connection holding unread bytes - more than 32 interim responses are a ProtocolError Signed-off-by: Christian Parpart --- .agent/reference/provenance.md | 9 +- src/core/http/CMakeLists.txt | 16 +- src/core/http/Connection.cpp | 6 +- src/core/http/Connection.hpp | 7 +- src/core/http/ConnectionLoopback_test.cpp | 141 +- src/core/http/Connection_test.cpp | 82 +- src/core/http/HttpClient.cpp | 906 ++++++++++ src/core/http/HttpClient.hpp | 260 +++ src/core/http/HttpClient_test.cpp | 1806 +++++++++++++++++++ src/core/http/HttpTestSupport.hpp | 460 ++++- src/core/http/testing/ScriptedConnector.cpp | 57 + src/core/http/testing/ScriptedConnector.hpp | 77 + 12 files changed, 3814 insertions(+), 13 deletions(-) create mode 100644 src/core/http/HttpClient.cpp create mode 100644 src/core/http/HttpClient.hpp create mode 100644 src/core/http/HttpClient_test.cpp create mode 100644 src/core/http/testing/ScriptedConnector.cpp create mode 100644 src/core/http/testing/ScriptedConnector.hpp diff --git a/.agent/reference/provenance.md b/.agent/reference/provenance.md index dc520622..5400edc1 100644 --- a/.agent/reference/provenance.md +++ b/.agent/reference/provenance.md @@ -235,18 +235,23 @@ others in notes. | `src/core/http/CMakeLists.txt` | origin: core-cpp | - | - | 0.24.0 (P13): the module and its test binary | | `src/core/http/Connection.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the role, socket-error and write-framing row tables; one read buffer per connection | | `src/core/http/Connection.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): `Connection`, `WireTimeouts` (zero is none), `Reuse` | -| `src/core/http/ConnectionLoopback_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): deadlines and cancellation over a real pair on every backend | +| `src/core/http/ConnectionLoopback_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): deadlines and cancellation over a real pair on every backend, and the client's response timeout against a slow upload | | `src/core/http/Connection_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): both ends over an in-memory pair on a `TestLoop` | | `src/core/http/Framing.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the RFC 9112 section 6.3 row table, the head parser and the chunked codec's transition table | | `src/core/http/Framing.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): limits, body framing, `HeadParser`, `ChunkedDecoder` | | `src/core/http/Framing_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the smuggling corpus, whole and one byte at a time; the framing tables; the parsers' bounds | -| `src/core/http/HttpTestSupport.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): test-only helpers the http cases share | +| `src/core/http/HttpClient.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the dial, wrap and TLS-failure row tables; the exchange as two halves under `whenAll` | +| `src/core/http/HttpClient.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): `HttpClient`, `Origin`, `HttpTimeouts` (zero is none), `OutgoingRequest`, `IncomingResponse` | +| `src/core/http/HttpClient_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the client over `testing::ScriptedConnector` on a `TestLoop`, TLS scripted | +| `src/core/http/HttpTestSupport.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): test-only helpers the http cases share: a scripted server end, a slow body source, and a scripted TLS context (R29) | | `src/core/http/Message.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | | `src/core/http/Message.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): one `HttpErrorCode` per WASI 0.3 `wasi:http` `error-code` case, the validating field, method, target and reason factories | | `src/core/http/Message_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | | `src/core/http/SmugglingCorpus.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): test-only request-smuggling corpus, shared with the server's tests | | `src/core/http/detail/Syntax.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): the RFC 9110/3986 character-class table both parsers and the factories share | | `src/core/http/posix/HttpTestSupport.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): test-only; `runsUnderWine` is false | +| `src/core/http/testing/ScriptedConnector.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/http/testing/ScriptedConnector.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): an `IConnector` over in-memory pairs, with refusals and a dial log | | `src/core/http/windows/HttpTestSupport.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): test-only; `runsUnderWine` from ntdll's `wine_get_version` | | `src/core/SystemRandomSource.hpp` | origin: core-cpp | - | - | the platform half of `Random.hpp`: one `fillFromSystemRandom()` per platform | | `src/core/log/Assert.hpp` | contour-terminal/contour | `src/crispy/Assert.hpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | `fatal()`/`SoftRequire()` moved here from crispy's `Assert.hpp` to close a base→log layering cycle; `Require`/`Guarantee`/`todo`/`unreachable`/`setFailHandler` stay in `src/core/Assert.hpp` | diff --git a/src/core/http/CMakeLists.txt b/src/core/http/CMakeLists.txt index c663a068..8ad2ef93 100644 --- a/src/core/http/CMakeLists.txt +++ b/src/core/http/CMakeLists.txt @@ -4,27 +4,37 @@ # factories, the framing rules of RFC 9112 section 6.3 as one row table, the incremental head parser # and the chunked codec -- holds no socket, so every framing rule is tested from a table # (Framing_test.cpp, over the shared SmugglingCorpus.hpp). Connection puts it on an ISocket: heads -# and streamed bodies with trailers, read through one buffer of maxReadChunk bytes. +# and streamed bodies with trailers, read through one buffer of maxReadChunk bytes. HttpClient sends +# a request over a connection of its own: the dial through an injected IConnector, TLS through an +# injected ITlsContext, and every failure on the way classified. testing/ScriptedConnector is the +# connector a consumer's test dials in memory with. core_cpp_add_module(http KIND STATIC HEADERS Body.hpp Connection.hpp Framing.hpp + HttpClient.hpp Message.hpp + testing/ScriptedConnector.hpp SOURCES Body.cpp Connection.cpp Framing.cpp + HttpClient.cpp Message.cpp + testing/ScriptedConnector.cpp PUBLIC_LIBS core::base core::net) # One binary. SmugglingCorpus.hpp is the test-only corpus the server's cases run too, and -# HttpTestSupport.hpp the helpers the cases share; Connection_test.cpp drives both ends over -# net::testing's in-memory pair on a TestLoop, so nothing in it waits on anything but the loop. +# HttpTestSupport.hpp the helpers the cases share, a scripted TLS context among them (R29: the binary +# links no net_tls and builds without CORE_CPP_WITH_TLS); Connection_test.cpp and HttpClient_test.cpp +# drive both ends over net::testing's in-memory pair on a TestLoop, so nothing in them waits on +# anything but the loop. core_cpp_add_test(http SOURCES Connection_test.cpp Framing_test.cpp + HttpClient_test.cpp HttpTestSupport.hpp Message_test.cpp SmugglingCorpus.hpp) diff --git a/src/core/http/Connection.cpp b/src/core/http/Connection.cpp index f42ee202..82a30ce9 100644 --- a/src/core/http/Connection.cpp +++ b/src/core/http/Connection.cpp @@ -1033,7 +1033,11 @@ Reuse Connection::reusable() const noexcept && state.persist == Persist::KeepAlive && !state.socket->isClosed() && state.readPhase == ReadPhase::Idle && state.writePhase == WritePhase::Idle && state.readWire == Wire::Idle && state.writeWire == Wire::Idle; - return clean ? Reuse::Yes : Reuse::No; + // Bytes a response role holds past the end of its last response answer no request it sent: pooled, + // they would be read as the next request's response. A request role keeps them, as the start of the + // next pipelined request. + auto const answered = state.role == MessageRole::Request || state.begin == state.end; + return clean && answered ? Reuse::Yes : Reuse::No; } net::ISocket& Connection::socket() noexcept diff --git a/src/core/http/Connection.hpp b/src/core/http/Connection.hpp index 4c3776cc..fba1438f 100644 --- a/src/core/http/Connection.hpp +++ b/src/core/http/Connection.hpp @@ -49,6 +49,10 @@ struct WireTimeouts /// From the start of a head read to its first byte. In the response role this is the response /// timeout (@c HttpErrorCode::ResponseTimeout); in the request role it is the idle time a client /// may take before its next request (@c HttpErrorCode::ConnectionReadTimeout). + /// + /// **A request still being written counts toward it**, as `wasi:http`'s first-byte timeout does + /// in wasmtime: a head read alongside an upload times out after this long whether or not the + /// upload is done, which also bounds a server that never reads the body. std::chrono::milliseconds firstByte { 0 }; /// Between any two reads after that, the body's included (@c HttpErrorCode::ConnectionReadTimeout). std::chrono::milliseconds betweenBytes { 0 }; @@ -173,7 +177,8 @@ class CORE_HTTP_API Connection /// No after UntilClose, Persistence::Close, an error, a close, a flow cancelled while it waited /// on the socket, or an unread body (a head read whose body has not reached its end, or a head - /// written whose body has not been written). + /// written whose body has not been written), or, for a response role, bytes read past the end of + /// the last response (they answer no request this side sent). [[nodiscard]] Reuse reusable() const noexcept; /// The socket, for its endpoints and TLS session. Requires a connection not moved from. diff --git a/src/core/http/ConnectionLoopback_test.cpp b/src/core/http/ConnectionLoopback_test.cpp index 063ef290..2ac283ba 100644 --- a/src/core/http/ConnectionLoopback_test.cpp +++ b/src/core/http/ConnectionLoopback_test.cpp @@ -2,16 +2,20 @@ // // `Connection` over a real socket pair on every backend this platform builds: the deadlines, which // the in-memory cases can only drive through the double's own `cancelRead`, and cancellation, which -// that double does not model at all. Every case bounds its whole flow with a watchdog, so a deadline -// that never fires fails the case in seconds instead of hanging it. +// that double does not model at all; and `HttpClient`'s response timeout bounding a peer that never +// reads, on real timers. Every case bounds its whole flow with a watchdog, so a deadline that never fires +// fails the case in seconds instead of hanging it. #include #include +#include #include #include #include +#include #include #include #include +#include #include #include #include @@ -223,6 +227,45 @@ void runBounded(EventLoop& loop, Task task) REQUIRE(finished); } +/// A connector that hands out the sockets it was given, one per dial, in order. +class QueuedSocketConnector final: public core::net::IConnector +{ + public: + explicit QueuedSocketConnector(std::vector> sockets): + _sockets { std::move(sockets) } + { + } + + [[nodiscard]] Task connect(std::string /*host*/, + std::uint16_t /*port*/, + core::net::DialOptions /*options*/) override + { + return handOut(&_sockets, _dials++); + } + + /// @return How many dials were asked for. + [[nodiscard]] std::size_t connects() const noexcept { return _dials; } + + private: + static Task handOut(std::vector>* sockets, + std::size_t index) + { + if (index >= sockets->size()) + co_return std::unexpected( + core::net::makeNetError(core::net::NetErrorCode::BadHandle, 0, "dialled once too often")); + co_return std::move(sockets->at(index)); + } + + std::vector> _sockets; + std::size_t _dials = 0; +}; + +/// Runs @p server and @p client together, to both ends. +Task both(Task server, Task client) +{ + co_await core::async::whenAll(std::move(server), std::move(client)); +} + } // namespace TEST_CASE("ConnectionLoopback.aSilentPeerTimesOutOnEveryBackend", "[http][connection][loopback]") @@ -427,3 +470,97 @@ TEST_CASE("ConnectionLoopback.aFlowCancelledOnTheWireLeavesTheConnectionUnreusab } } } + +TEST_CASE("ConnectionLoopback.aServerThatNeverReadsIsBoundedByTheResponseTimeout", "[http][client][loopback]") +{ + // HttpClient reads the response head while it uploads a flood the peer never reads, so the write + // stalls in the kernel. The response timeout runs through the upload (P13 Task 16 ruling, as + // wasmtime's first-byte timeout does), ends the request, and its close ends the stalled write. + for (auto const& backend: BackendMatrix) + { + if (!buildsHere(backend.kind)) + continue; + DYNAMIC_SECTION("backend=" << backend.name) + { + auto ioBackend = core::net::makeBackend(backend.kind); + REQUIRE(ioBackend != nullptr); + auto loop = EventLoop { *ioBackend }; + auto pair = core::net::testing::makeSocketPair(loop); + REQUIRE(pair.has_value()); + std::ignore = pair->first->setOption(core::net::SocketOption::SendBufferSize, SmallBuffer); + std::ignore = pair->second->setOption(core::net::SocketOption::ReceiveBufferSize, SmallBuffer); + auto sockets = std::vector> {}; + sockets.push_back(std::move(pair->first)); + auto connector = QueuedSocketConnector { std::move(sockets) }; + auto options = core::http::HttpClientOptions {}; + options.timeouts = + core::http::HttpTimeouts { .connect = 0ms, .firstByte = Deadline, .betweenBytes = 0ms }; + auto client = core::http::HttpClient { loop, connector, nullptr, options }; + auto request = core::http::test::get("http://example.test/upload", "PUT"); + request.body = std::make_unique(std::string(Flood, 'x')); + auto answer = std::optional> {}; + runBounded(loop, into(client.send(std::move(request)), &answer)); + REQUIRE(answer.has_value()); + REQUIRE_FALSE(answer->has_value()); + CHECK(answer->error().code == HttpErrorCode::ResponseTimeout); + } + } +} + +TEST_CASE("ConnectionLoopback.aKeptAliveConnectionTheServerClosedIsRetried", "[http][client][pool][loopback]") +{ + // A server closes a kept-alive connection while it sits in the client's pool, as servers do at + // their own idle timeout. On a real socket the reuse sees the close as an end of stream or a + // reset, depending on the kernel and the timing; either is a stale connection, and the bodiless + // GET is sent again on a fresh one. + for (auto const& backend: BackendMatrix) + { + if (!buildsHere(backend.kind)) + continue; + DYNAMIC_SECTION("backend=" << backend.name) + { + auto ioBackend = core::net::makeBackend(backend.kind); + REQUIRE(ioBackend != nullptr); + auto loop = EventLoop { *ioBackend }; + auto pooled = core::net::testing::makeSocketPair(loop); + REQUIRE(pooled.has_value()); + auto fresh = core::net::testing::makeSocketPair(loop); + REQUIRE(fresh.has_value()); + auto sockets = std::vector> {}; + sockets.push_back(std::move(pooled->first)); + sockets.push_back(std::move(fresh->first)); + auto connector = QueuedSocketConnector { std::move(sockets) }; + auto client = core::http::HttpClient { loop, connector, nullptr }; + constexpr auto Reply = std::string_view { "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok" }; + + auto firstLine = std::optional {}; + auto first = std::optional> {}; + runBounded( + loop, + both(into(core::http::test::answerHeadOnly(pooled->second.get(), std::string { Reply }), + &firstLine), + into(client.send(core::http::test::get("http://example.test/one")), &first))); + REQUIRE(firstLine == "GET /one HTTP/1.1"); + REQUIRE(first.has_value()); + REQUIRE(first->has_value()); + auto firstBody = std::optional {}; + runBounded(loop, into(readAll((*first)->body.get(), 100), &firstBody)); + REQUIRE(firstBody.has_value()); + CHECK(firstBody->text == "ok"); + REQUIRE(client.idleConnections() == 1); + + pooled->second->close(); + auto secondLine = std::optional {}; + auto second = std::optional> {}; + runBounded(loop, + both(into(core::http::test::answerHeadOnly(fresh->second.get(), std::string { Reply }), + &secondLine), + into(client.send(core::http::test::get("http://example.test/two")), &second))); + CHECK(connector.connects() == 2); + CHECK(secondLine == "GET /two HTTP/1.1"); + REQUIRE(second.has_value()); + REQUIRE(second->has_value()); + CHECK((*second)->head.status == 200); + } + } +} diff --git a/src/core/http/Connection_test.cpp b/src/core/http/Connection_test.cpp index ef50ed4c..0d987564 100644 --- a/src/core/http/Connection_test.cpp +++ b/src/core/http/Connection_test.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -30,6 +31,7 @@ #include #include #include +#include #include #include #include @@ -63,6 +65,7 @@ using core::http::test::into; using core::http::test::readAll; using core::http::test::ReadBody; using core::http::test::readUntilClosed; +using core::http::test::SlowBodySource; using core::http::test::writeAndClose; using core::http::test::writeOnly; using core::net::ISocket; @@ -1167,6 +1170,80 @@ TEST_CASE("Connection.aZeroTimeoutIsNone", "[http][connection]") CHECK(connection.reusable() == Reuse::Yes); // a bodiless response is a finished one } +TEST_CASE("Connection.anUploadInProgressCountsTowardTheResponseTimeout", "[http][connection]") +{ + // The response timeout follows wasmtime's first-byte timeout (P13 Task 16 ruling): it runs from + // the head read's start, and a request body still being written -- here one chunk every three + // timeouts -- does not hold it. + auto wire = Wire {}; + auto server = Connection { + wire.loop, std::move(wire.pair.server), MessageRole::Request, HttpLimits {}, NoTimeouts + }; + auto client = Connection { wire.loop, + std::move(wire.pair.client), + MessageRole::Response, + HttpLimits {}, + WireTimeouts { .firstByte = 100ms, .betweenBytes = 0ms, .write = 0ms } }; + auto upload = SlowBodySource { wire.loop, { "aaaa", "bbbb", "cccc" }, 300ms }; + auto const framing = core::http::framingFor(&upload); + auto sent = std::optional> {}; + auto received = std::optional {}; + auto served = std::optional {}; + wire.loop.spawn( + into(sendRequest(&client, requestHead("PUT", "/", { { "Host", "h" } }), &upload, framing), &sent)); + wire.loop.spawn(into(receiveOne(&client, "PUT", 100), &received)); + wire.loop.spawn(into(serveOne(&server, 100), &served)); + std::ignore = wire.loop.drain(); + wire.clock.advance(99ms); + std::ignore = wire.loop.drain(); + REQUIRE_FALSE(received.has_value()); + wire.clock.advance(1ms); + std::ignore = wire.loop.drain(); + REQUIRE(received.has_value()); + CHECK(received->error == HttpErrorCode::ResponseTimeout); + REQUIRE_FALSE(sent.has_value()); // the upload was still in progress + for ([[maybe_unused]] auto const chunk: std::views::iota(0, 3)) + { + wire.clock.advance(300ms); + std::ignore = wire.loop.drain(); + } + REQUIRE(sent.has_value()); + CHECK(sent->has_value()); +} + +TEST_CASE("Connection.aHeadWrittenAloneLeavesTheResponseTimeoutRunning", "[http][connection]") +{ + // Only a write in progress holds the timeout. A client that writes its head and waits for an + // interim answer before the body (Expect: 100-continue) is waiting on the server, and is bounded. + auto wire = Wire {}; + auto client = Connection { wire.loop, + std::move(wire.pair.client), + MessageRole::Response, + HttpLimits {}, + WireTimeouts { .firstByte = 100ms, .betweenBytes = 0ms, .write = 0ms } }; + auto drained = std::optional {}; + auto wrote = std::optional> {}; + auto received = std::optional {}; + wire.loop.spawn(into(readUntilClosed(wire.pair.server.get()), &drained)); + wire.loop.spawn(into( + client.writeRequestHead(requestHead("PUT", "/", { { "Host", "h" }, { "Expect", "100-continue" } }), + Framing { .kind = BodyFraming::Length, .length = 4 }), + &wrote)); + std::ignore = wire.loop.drain(); + REQUIRE(wrote.has_value()); + REQUIRE(wrote->has_value()); + wire.loop.spawn(into(receiveOne(&client, "PUT", 100), &received)); + std::ignore = wire.loop.drain(); + wire.clock.advance(99ms); + std::ignore = wire.loop.drain(); + REQUIRE_FALSE(received.has_value()); + wire.clock.advance(1ms); + std::ignore = wire.loop.drain(); + REQUIRE(received.has_value()); + CHECK(received->error == HttpErrorCode::ResponseTimeout); + client.close(); +} + TEST_CASE("Connection.socketErrorsMapThroughTheTable", "[http][connection]") { // A transport failure is classified once, by a row per NetErrorCode, and the direction decides @@ -1224,7 +1301,8 @@ TEST_CASE("Connection.reuseFollowsTheExchange", "[http][connection]") { SECTION("a second response in the same bytes is read after the first") { - // Bytes past a body stay buffered for the next head. + // Bytes past a body stay buffered for the next head; while they wait, the connection is not + // one a pool may hand to a request they do not answer. auto wire = Wire {}; auto connection = Connection { wire.loop, std::move(wire.pair.client), MessageRole::Response, HttpLimits {}, NoTimeouts @@ -1237,7 +1315,7 @@ TEST_CASE("Connection.reuseFollowsTheExchange", "[http][connection]") std::ignore = wire.loop.drain(); REQUIRE(first.has_value()); CHECK(first->body.text == "abc"); - CHECK(connection.reusable() == Reuse::Yes); + CHECK(connection.reusable() == Reuse::No); auto second = std::optional {}; wire.loop.spawn(into(receiveOne(&connection, "GET", 100), &second)); std::ignore = wire.loop.drain(); diff --git a/src/core/http/HttpClient.cpp b/src/core/http/HttpClient.cpp new file mode 100644 index 00000000..4c6b3f53 --- /dev/null +++ b/src/core/http/HttpClient.cpp @@ -0,0 +1,906 @@ +// SPDX-License-Identifier: Apache-2.0 +#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 core::http +{ + +namespace +{ + + using namespace std::chrono_literals; + + // --------------------------------------------------------------------------------------------- + // Failures before the exchange, classified once: a row per code, each table with its default. + + struct NetCodeRow + { + net::NetErrorCode net; + HttpErrorCode http; + }; + + /// A failed dial, or a handshake the transport cut (no TLS failure behind it). Every code not + /// listed is @c HttpErrorCode::InternalError, with the socket's words as detail. + constexpr auto TransportErrorRows = std::array { + NetCodeRow { .net = net::NetErrorCode::NameNotFound, .http = HttpErrorCode::DnsError }, + NetCodeRow { .net = net::NetErrorCode::ResolverTemporaryFailure, .http = HttpErrorCode::DnsError }, + // A permanent resolver failure, and any lookup failure nothing classified further. + NetCodeRow { .net = net::NetErrorCode::AddressError, .http = HttpErrorCode::DnsError }, + NetCodeRow { .net = net::NetErrorCode::ConnRefused, .http = HttpErrorCode::ConnectionRefused }, + NetCodeRow { .net = net::NetErrorCode::HostUnreach, .http = HttpErrorCode::DestinationUnavailable }, + NetCodeRow { .net = net::NetErrorCode::Timeout, .http = HttpErrorCode::ConnectionTimeout }, + NetCodeRow { .net = net::NetErrorCode::ConnReset, .http = HttpErrorCode::ConnectionTerminated }, + NetCodeRow { .net = net::NetErrorCode::Eof, .http = HttpErrorCode::ConnectionTerminated }, + }; + + /// @c net::ITlsContext::wrapClient's refusals. Every code not listed is + /// @c HttpErrorCode::InternalError. + constexpr auto WrapErrorRows = std::array { + // The context cannot verify a per-connection name: a legacy or trust-on-first-use one (R23). + NetCodeRow { .net = net::NetErrorCode::Unsupported, .http = HttpErrorCode::ConfigurationError }, + // A name the wire cannot carry: the origin's host is no host. + NetCodeRow { .net = net::NetErrorCode::AddressError, .http = HttpErrorCode::RequestUriInvalid }, + }; + + [[nodiscard]] HttpError classify(std::span rows, net::NetError const& error) + { + auto const row = std::ranges::find(rows, error.code, &NetCodeRow::net); + return detail::refusal(row != rows.end() ? row->http : HttpErrorCode::InternalError, + error.toString()); + } + + struct TlsFailureRow + { + net::TlsFailureKind kind; + HttpErrorCode http; + }; + + /// What a TLS session's failure is, by its kind; one row per @c net::TlsFailureKind. + constexpr auto TlsFailureRows = std::array { + TlsFailureRow { .kind = net::TlsFailureKind::Protocol, .http = HttpErrorCode::TlsProtocolError }, + TlsFailureRow { .kind = net::TlsFailureKind::Certificate, + .http = HttpErrorCode::TlsCertificateError }, + TlsFailureRow { .kind = net::TlsFailureKind::AlertReceived, .http = HttpErrorCode::TlsAlertReceived }, + }; + + /// @return The TLS failure behind @p socket's connection as an error with it attached, if its + /// session reports one. + [[nodiscard]] std::optional tlsFailureOf(net::ISocket const& socket) + { + auto const* session = socket.tlsSession(); + if (session == nullptr) + return std::nullopt; + auto failure = session->failure(); + if (!failure.has_value()) + return std::nullopt; + auto const row = std::ranges::find(TlsFailureRows, failure->kind, &TlsFailureRow::kind); + auto error = detail::refusal( + row != TlsFailureRows.end() ? row->http : HttpErrorCode::TlsProtocolError, failure->message); + error.tls = std::move(*failure); + return error; + } + + // --------------------------------------------------------------------------------------------- + // The origin as the dial, TLS and the Host field each want it. + + /// The host without the brackets an IPv6 literal may come with: what the dial and TLS take. + [[nodiscard]] std::string_view bareHost(std::string_view host) noexcept + { + if (host.size() >= 2 && host.starts_with('[') && host.ends_with(']')) + return host.substr(1, host.size() - 2); + return host; + } + + /// Whether @p host can only be read one way: a host with a `:` is an IPv6 literal, so it may hold + /// nothing but hex digits, `:` and the `.` of an embedded IPv4 address, and at least two `:`. + /// That refuses `host:port` (the port belongs in @c Origin::port) and a zone (`%eth0`, RFC 6874 + /// section 4). Anything else is left to the Host field's authority check. + [[nodiscard]] bool isHostSyntax(std::string_view host) noexcept + { + if (!host.contains(':')) + return true; + auto const ipv6Octet = [](char octet) { + return detail::allIn(std::string_view { &octet, 1 }, detail::CharClass::Hex) || octet == ':' + || octet == '.'; + }; + return std::ranges::all_of(host, ipv6Octet) && std::ranges::count(host, ':') >= 2; + } + + /// The Host field's value (RFC 9110 section 7.2): the host, bracketed if it is an IPv6 literal, + /// and the port unless it is the scheme's default. + [[nodiscard]] std::string authorityOf(Origin const& origin) + { + auto const host = bareHost(origin.host); + auto authority = host.contains(':') ? std::format("[{}]", host) : std::string { host }; + if (origin.effectivePort() != defaultPort(origin.scheme)) + authority += std::format(":{}", origin.effectivePort()); + return authority; + } + + /// The request head as written: `Host` first, then the caller's fields, which may hold neither a + /// `Host` nor a framing field. + [[nodiscard]] HttpResult headFor(Origin const& origin, RequestHead head) + { + if (bareHost(origin.host).empty()) + return std::unexpected( + detail::refusal(HttpErrorCode::RequestUriInvalid, "the origin has no host")); + if (!isHostSyntax(bareHost(origin.host))) + return std::unexpected(detail::refusal(HttpErrorCode::RequestUriInvalid, + std::format("'{}' is not a host", origin.host))); + auto const authority = authorityOf(origin); + if (!detail::isAuthority(authority, detail::PortRule::Optional)) + return std::unexpected(detail::refusal(HttpErrorCode::RequestUriInvalid, + std::format("'{}' is not a host", origin.host))); + auto fields = Fields {}; + if (!fields.append("Host", authority).has_value()) + return std::unexpected(detail::refusal(HttpErrorCode::RequestUriInvalid, + std::format("'{}' is not a host", origin.host))); + for (auto const& field: head.fields.entries()) + { + if (isFramingField(field.name) || detail::equalsIgnoringCase(field.name, "Host")) + return std::unexpected(detail::refusal( + HttpErrorCode::ProtocolError, "the client writes this field itself", field.name)); + // Validated when the caller appended it. + std::ignore = fields.append(field.name, field.value); + } + head.fields = std::move(fields); + return head; + } + + // --------------------------------------------------------------------------------------------- + // The exchange: the request written while the response head is read. + + /// Whether a failed request write still leaves the response worth reading: only when the peer + /// cut the connection, which a server that refuses an upload does after answering it. + [[nodiscard]] bool wasCutByPeer(HttpError const& error) noexcept + { + return error.code == HttpErrorCode::ConnectionTerminated; + } + + /// Writes the request head and its body. A failure the peer did not cause closes the connection, + /// so a head read still waiting on the peer ends too. + async::Task writeRequest(Connection* connection, + RequestHead head, + IBodySource* body, + Framing framing, + std::optional>* out) + { + auto wrote = co_await connection->writeRequestHead(std::move(head), framing); + if (wrote.has_value()) + wrote = co_await connection->writeBody(body, framing); + if (!wrote.has_value() && !wasCutByPeer(wrote.error())) + connection->close(); + *out = std::move(wrote); + } + + /// Closed by the read half when it fails, which stops the write half: never pushed to. + using ReadFailure = async::AsyncQueue; + + /// Returns once @p readFailure is closed; stopped (OperationCancelled) otherwise. + async::Task untilClosed(ReadFailure* readFailure) + { + std::ignore = co_await readFailure->pop(); + } + + /// The write half: @c writeRequest, stopped when the read half fails. A write parked on the socket + /// ends with the close the read half makes; one parked on a body source ends here, through its + /// flow's stop token, if the source honours it. A stopped write leaves @p out empty. + async::Task writeUnlessReadFails(Connection* connection, + RequestHead head, + IBodySource* body, + Framing framing, + std::optional>* out, + ReadFailure* readFailure) + { + auto arms = std::vector> {}; + arms.push_back(writeRequest(connection, std::move(head), body, framing, out)); + arms.push_back(untilClosed(readFailure)); + std::ignore = co_await async::whenAny(std::move(arms)); + } + + /// Whether a response had begun when its exchange failed: an interim head counts, since the server + /// had then read the request. + enum class ResponseSeen : std::uint8_t + { + None, ///< Not a head of it arrived. + Some, ///< An interim head did. + }; + + /// What the read half answers. + struct ReadAnswer + { + std::optional> response; + ResponseSeen seen = ResponseSeen::None; + }; + + /// The most interim (1xx) responses read before the final one; one more is a ProtocolError. Each + /// costs a read and nothing else, so without it a server could keep a request reading for ever. + constexpr auto MaxInterimResponses = 32; + + /// Reads response heads until the final one, and frames its body. A failure closes the connection + /// and @p readFailure, so a request write still in progress ends too. + async::Task readFinalHead(Connection* connection, + std::string method, + ReadAnswer* out, + ReadFailure* readFailure) + { + auto answer = HttpResult {}; + auto interim = 0; + while (true) + { + auto head = co_await connection->readResponseHead(); + if (!head.has_value()) + { + answer = std::unexpected(std::move(head.error())); + break; + } + out->seen = ResponseSeen::Some; + if (head->status == 101) + { + answer = std::unexpected(detail::refusal(HttpErrorCode::ProtocolError, + "a 101 to a request that asked for no upgrade")); + break; + } + if (head->status < 200 && ++interim > MaxInterimResponses) + { + answer = std::unexpected(detail::refusal( + HttpErrorCode::ProtocolError, + std::format("more than {} interim responses before the final one", MaxInterimResponses))); + break; + } + if (head->status < 200) + continue; // interim: the final response follows + auto framing = responseFraming(method, head->version, head->status, head->fields); + if (!framing.has_value()) + { + answer = std::unexpected(std::move(framing.error())); + break; + } + auto reader = connection->bodyReader(*framing); + answer = IncomingResponse { .head = std::move(*head), .body = std::move(reader) }; + break; + } + if (!answer.has_value()) + { + connection->close(); + readFailure->close(); + } + out->response = std::move(answer); + } + + /// One exchange's answer, and whether any of the response had arrived when it failed. + struct Exchanged + { + HttpResult answer; + ResponseSeen seen = ResponseSeen::None; + }; + + /// The answer of an exchange whose two halves have finished: the write's own failure first, since + /// the read's is then the close it caused; else the read's, which is the response. A write the + /// read's failure stopped has no answer of its own. + [[nodiscard]] Exchanged answerOf(std::optional> wrote, ReadAnswer read) + { + Require(read.response.has_value()); + if (wrote.has_value() && !wrote->has_value() && !wasCutByPeer(wrote->error())) + return Exchanged { .answer = std::unexpected(std::move(wrote->error())), .seen = read.seen }; + return Exchanged { .answer = std::move(*read.response), .seen = read.seen }; + } + + /// Writes @p head and @p body on @p connection while the response head is read (step 4). + async::Task exchange(net::EventLoop* loop, + Connection* connection, + RequestHead head, + IBodySource* body) + { + auto const framing = framingFor(body); + auto method = std::string { head.method.text() }; + auto wrote = std::optional> {}; + auto read = ReadAnswer {}; + auto readFailure = ReadFailure { *loop, async::AsyncQueueOptions {} }; + auto halves = std::vector> {}; + halves.push_back( + writeUnlessReadFails(connection, std::move(head), body, framing, &wrote, &readFailure)); + halves.push_back(readFinalHead(connection, std::move(method), &read, &readFailure)); + co_await async::whenAll(std::move(halves)); + auto exchanged = answerOf(std::move(wrote), std::move(read)); + if (!exchanged.answer.has_value()) + if (auto failure = tlsFailureOf(connection->socket()); failure.has_value()) + exchanged.answer = std::unexpected(std::move(*failure)); + co_return exchanged; + } + + /// Bounds @p handshake by @p timeout unless it is zero (R31). + async::Task::Result>> boundedHandshake( + net::EventLoop* loop, net::ISocket* socket, std::chrono::milliseconds timeout) + { + if (timeout == 0ms) + co_return co_await socket->handshakeIfNeeded(); + co_return co_await net::withTimeout(loop, async::asTask(socket->handshakeIfNeeded()), timeout); + } + + /// A connection's read deadlines for a request's @p timeouts. The write deadline is none: WASI has + /// no write timeout, so a peer that stops reading is bounded by @c HttpTimeouts::firstByte and the + /// caller's stop token. + [[nodiscard]] WireTimeouts wireTimeoutsOf(HttpTimeouts const& timeouts) noexcept + { + return WireTimeouts { .firstByte = timeouts.firstByte, + .betweenBytes = timeouts.betweenBytes, + .write = 0ms }; + } + + /// What a dial needs of the client, by value for the coroutine's frame. + struct Dialler + { + net::EventLoop* loop; + net::IConnector* connector; + net::ITlsContext* tls; + HttpLimits limits; + }; + + /// A fresh connection to @p origin (steps 2 and 3): the dial, then for @c Scheme::Https TLS bound + /// to its host, the handshake settled before any request byte. + async::Task> dial(Dialler dialler, Origin origin, HttpTimeouts timeouts) + { + auto const host = std::string { bareHost(origin.host) }; + auto options = net::DialOptions {}; + options.connectTimeout = timeouts.connect; + auto dialled = co_await dialler.connector->connect(host, origin.effectivePort(), options); + if (!dialled.has_value()) + co_return std::unexpected(classify(TransportErrorRows, dialled.error())); + auto socket = std::move(*dialled); + if (origin.scheme == Scheme::Https) + { + auto wrapped = dialler.tls->wrapClient( + std::move(socket), *dialler.loop, net::TlsPeer { .serverName = host }); + if (!wrapped.has_value()) + co_return std::unexpected(classify(WrapErrorRows, wrapped.error())); + socket = std::move(*wrapped); + auto const handshake = co_await boundedHandshake(dialler.loop, socket.get(), timeouts.connect); + if (!handshake.has_value()) + co_return std::unexpected(detail::refusal( + HttpErrorCode::ConnectionTimeout, + std::format("the TLS handshake did not finish within {} ms", timeouts.connect.count()))); + if (!handshake->has_value()) + { + if (auto failure = tlsFailureOf(*socket); failure.has_value()) + co_return std::unexpected(std::move(*failure)); + co_return std::unexpected(classify(TransportErrorRows, handshake->error())); + } + } + co_return Connection { + *dialler.loop, std::move(socket), MessageRole::Response, dialler.limits, wireTimeoutsOf(timeouts) + }; + } + + // --------------------------------------------------------------------------------------------- + // The retry rule: which requests may be sent twice, and which failures say the server had closed + // a pooled connection before the request came. + + /// The idempotent methods (RFC 9110 section 9.2.2): sent twice, they have the effect of once. + constexpr auto IdempotentMethods = std::array { + "GET", "HEAD", "OPTIONS", "TRACE", "PUT", "DELETE", + }; + + /// The failures of a pooled connection, before any head of the response, that mean the server + /// had closed it while it sat idle. Which one a close surfaces as, and from which half of the + /// exchange, depends on the kernel and the timing (measured; each row has the test that needs it): + constexpr auto StaleConnectionCodes = std::array { + // The head read saw the server's FIN, or a reset (ECONNRESET, WSAECONNRESET): the in-memory + // half-closed rows. + HttpErrorCode::ConnectionTerminated, + // An OS error nothing classifies further, from either half: the request write found the + // reset already in (EPIPE from sendmsg on Linux, the loopback case; WSAECONNABORTED on + // Windows), or the write went out after the FIN, drew the reset, and the read reports it + // (Linux answers a reset in CLOSE_WAIT with EPIPE; the in-memory closed rows). A bodiless + // request has no body source, so on this path nothing but the socket answers InternalError. + // Narrowing this to the write half would leave the read-side EPIPE unretried. + HttpErrorCode::InternalError, + }; + + /// Whether a request may be sent again: its method is idempotent and it hands over no body. + enum class Replay : std::uint8_t + { + Refused, + Allowed, + }; + + [[nodiscard]] Replay replayOf(RequestHead const& head, IBodySource const* body) noexcept + { + auto const bodiless = + body == nullptr + || (body->knownLength() == std::uint64_t { 0 } && body->trailerIntent() == TrailerIntent::None); + auto const idempotent = std::ranges::contains(IdempotentMethods, head.method.text()); + return bodiless && idempotent ? Replay::Allowed : Replay::Refused; + } + + /// Where a request's connection came from. + enum class Provenance : std::uint8_t + { + Dialled, ///< Opened for it. + Pooled, ///< Reused from the pool. + }; + + /// Whether @p exchanged failed as a stale connection does; that it was a pooled one is the + /// caller's half of the rule. + [[nodiscard]] bool isStale(Exchanged const& exchanged) noexcept + { + return !exchanged.answer.has_value() && exchanged.seen == ResponseSeen::None + && std::ranges::contains(StaleConnectionCodes, exchanged.answer.error().code); + } + +} // namespace + +// ------------------------------------------------------------------------------------------------- +// The pool. + +namespace detail +{ + + /// Every origin's connections. Loop-affine, as the client. + struct Pool + { + /// An idle connection, with the read deadlines it was opened under and when it expires. + struct IdleConnection + { + Connection connection; + WireTimeouts timeouts; + SteadyTimePoint since; ///< When it came back: the oldest goes first. + std::optional expires; ///< None: no idle timeout. + }; + + /// One origin's connections: those idle, oldest first, and how many are lent out. + struct OriginConnections + { + std::deque idle; + std::size_t lent = 0; + }; + + IClock const* clock; + std::size_t maxIdlePerOrigin; + std::size_t maxConnectionsPerOrigin; + std::size_t maxConnectionsTotal; + std::chrono::milliseconds idleTimeout; + std::map origins; + + [[nodiscard]] static bool hasExpired(IdleConnection const& idle, SteadyTimePoint now) noexcept + { + return idle.expires.has_value() && *idle.expires <= now; + } + + /// Closes @p connections' idle connections past their deadline. + void sweep(OriginConnections& connections) const + { + auto const now = clock->now(); + for (auto& idle: connections.idle) + if (hasExpired(idle, now)) + idle.connection.close(); + std::erase_if(connections.idle, + [now](IdleConnection const& idle) { return hasExpired(idle, now); }); + } + + /// Closes every idle connection past its deadline, and forgets an origin with nothing left. + void sweep() + { + for (auto& [origin, connections]: origins) + sweep(connections); + forgetEmpty(); + } + + /// @return Every connection open, idle or lent out, to every origin. + [[nodiscard]] std::size_t openCount() const noexcept + { + auto count = std::size_t { 0 }; + for (auto const& [origin, connections]: origins) + count += connections.lent + connections.idle.size(); + return count; + } + + /// Closes the idle connection that came back first, of any origin. + /// @return Whether there was one to close. + [[nodiscard]] bool evictOldestIdle() + { + auto* oldest = static_cast(nullptr); + for (auto& [origin, connections]: origins) + if (!connections.idle.empty() + && (oldest == nullptr || connections.idle.front().since < oldest->idle.front().since)) + oldest = &connections; + if (oldest == nullptr) + return false; + oldest->idle.front().connection.close(); + oldest->idle.pop_front(); + return true; + } + + void forgetEmpty() + { + std::erase_if(origins, [](auto const& entry) { + return entry.second.idle.empty() && entry.second.lent == 0; + }); + } + + [[nodiscard]] std::size_t idleCount() const noexcept + { + auto const now = clock->now(); + auto count = std::size_t { 0 }; + for (auto const& [origin, connections]: origins) + count += static_cast(std::ranges::count_if( + connections.idle, [now](IdleConnection const& idle) { return !hasExpired(idle, now); })); + return count; + } + }; + +} // namespace detail + +namespace +{ + + /// The pool's key for @p origin: one origin however its host is cased and whether its port is + /// named or the scheme's default. + [[nodiscard]] Origin poolKeyOf(Origin const& origin) + { + auto host = std::string { bareHost(origin.host) }; + std::ranges::transform(host, host.begin(), detail::toLowerAscii); + return Origin { .scheme = origin.scheme, .host = std::move(host), .port = origin.effectivePort() }; + } + + [[nodiscard]] bool sameDeadlines(WireTimeouts const& a, WireTimeouts const& b) noexcept + { + return a.firstByte == b.firstByte && a.betweenBytes == b.betweenBytes && a.write == b.write; + } + + /// Whether a lease still counts against its origin's cap. + enum class Place : std::uint8_t + { + Released, + Held, + }; + + /// One connection's place under its origin's cap, from the request that took it to the end of its + /// response body. It holds the pool weakly: once the client is gone, nothing goes back. + class Lease + { + public: + Lease(std::weak_ptr pool, Origin key, WireTimeouts timeouts): + _pool { std::move(pool) }, _key { std::move(key) }, _timeouts { timeouts } + { + } + + ~Lease() { release(); } + + Lease(Lease const&) = delete; + Lease& operator=(Lease const&) = delete; + + Lease(Lease&& other) noexcept: + _pool { std::move(other._pool) }, + _key { std::move(other._key) }, + _timeouts { other._timeouts }, + _place { std::exchange(other._place, Place::Released) } + { + } + + Lease& operator=(Lease&& other) noexcept + { + if (this != &other) + { + release(); + _pool = std::move(other._pool); + _key = std::move(other._key); + _timeouts = other._timeouts; + _place = std::exchange(other._place, Place::Released); + } + return *this; + } + + /// Puts @p connection back among its origin's idle connections if it may carry another + /// exchange, the client is alive and the idle cap has room; closes it otherwise. Releases the + /// place either way. + void giveBack(Connection connection) + { + auto const pool = _pool.lock(); + auto* const connections = + _place == Place::Held && pool != nullptr && connection.reusable() == Reuse::Yes + ? &pool->origins[_key] + : nullptr; + if (connections != nullptr) + pool->sweep(*connections); // an expired idle connection holds no room under the cap + if (connections != nullptr && connections->idle.size() < pool->maxIdlePerOrigin) + { + auto const now = pool->clock->now(); + auto expires = std::optional {}; + if (pool->idleTimeout != 0ms) + expires = now + pool->idleTimeout; + connections->idle.push_back( + detail::Pool::IdleConnection { .connection = std::move(connection), + .timeouts = _timeouts, + .since = now, + .expires = expires }); + } + else + connection.close(); + release(); + } + + /// Gives up the place, the connection having been closed or never opened. + void release() noexcept + { + if (std::exchange(_place, Place::Released) == Place::Released) + return; + if (auto const pool = _pool.lock(); pool != nullptr) + { + if (auto const found = pool->origins.find(_key); found != pool->origins.end()) + { + --found->second.lent; + if (found->second.lent == 0 && found->second.idle.empty()) + pool->origins.erase(found); + } + } + } + + private: + std::weak_ptr _pool; + Origin _key; + WireTimeouts _timeouts; + Place _place = Place::Held; + }; + + /// A place under the cap, and the idle connection that came with it, if one could be reused. + struct Acquired + { + Lease lease; + std::optional idle; + }; + + /// Takes a place under @p key's cap for a request under @p timeouts, with the most recently used + /// idle connection opened under the same deadlines, if there is one. + [[nodiscard]] HttpResult acquire(std::shared_ptr const& pool, + Origin const& key, + WireTimeouts timeouts) + { + pool->sweep(); + auto& connections = pool->origins[key]; + auto& idle = connections.idle; + auto const reusable = [timeouts](detail::Pool::IdleConnection const& candidate) { + return sameDeadlines(candidate.timeouts, timeouts) + && candidate.connection.reusable() == Reuse::Yes; + }; + auto found = std::ranges::find_if(idle.rbegin(), idle.rend(), reusable); + auto taken = std::optional {}; + if (found != idle.rend()) + { + taken = std::move(found->connection); + idle.erase(std::next(found).base()); + } + else if (connections.lent + idle.size() >= pool->maxConnectionsPerOrigin) + { + if (idle.empty()) + { + if (connections.lent == 0) + pool->origins.erase(key); + return std::unexpected( + detail::refusal(HttpErrorCode::ConnectionLimitReached, + std::format("all {} connections to the origin are in use", + pool->maxConnectionsPerOrigin))); + } + idle.front().connection.close(); // under other deadlines: makes room + idle.pop_front(); + } + if (!taken.has_value() && pool->openCount() >= pool->maxConnectionsTotal && !pool->evictOldestIdle()) + { + if (connections.lent == 0 && idle.empty()) + pool->origins.erase(key); + return std::unexpected(detail::refusal( + HttpErrorCode::ConnectionLimitReached, + std::format("all {} connections of the client are in use", pool->maxConnectionsTotal))); + } + ++connections.lent; + return Acquired { .lease = Lease { pool, key, timeouts }, .idle = std::move(taken) }; + } + + // --------------------------------------------------------------------------------------------- + // The response body that gives its connection back. + + /// What a @c PooledBodyReader and its reads in flight share. + struct LentConnection + { + std::unique_ptr inner; + /// Until it goes back or is closed. + std::optional connection; + Lease lease; + /// Taken at the body's end, before the connection went back: a reuse starts another body. + std::optional> trailers; + + /// At the body's end: hands the connection to @c Lease::giveBack, which pools it if it may + /// carry another exchange and closes it otherwise (`Connection: close`, an until-close body), + /// so a body that is over holds no place under the cap. + void settle() + { + if (!connection.has_value()) + return; + auto handed = std::move(*connection); + connection.reset(); + lease.giveBack(std::move(handed)); + } + + /// Closes the connection and gives up its place. + void closeConnection() noexcept + { + if (connection.has_value()) + { + connection->close(); + connection.reset(); + } + lease.release(); + } + }; + + /// The response body the client hands out: the connection's own reader, which gives the + /// connection back to the pool at the body's end, or closes it if the body ends otherwise. + class PooledBodyReader final: public IBodyReader + { + public: + PooledBodyReader(std::unique_ptr inner, Connection connection, Lease lease): + _state { std::make_shared(LentConnection { .inner = std::move(inner), + .connection = std::move(connection), + .lease = std::move(lease), + .trailers = {} }) } + { + // A bodiless response is over with its head: nothing would read it to its end. + if (_state->connection->reusable() == Reuse::Yes) + { + _state->trailers = Fields {}; + _state->settle(); + } + } + + ~PooledBodyReader() override { _state->closeConnection(); } + + PooledBodyReader(PooledBodyReader const&) = delete; + PooledBodyReader& operator=(PooledBodyReader const&) = delete; + PooledBodyReader(PooledBodyReader&&) = delete; + PooledBodyReader& operator=(PooledBodyReader&&) = delete; + + [[nodiscard]] async::Task> read(std::size_t maxBytes) override + { + return readFrom(_state, maxBytes); + } + + [[nodiscard]] async::Task> trailers() override { return trailersOf(_state); } + + private: + static async::Task> readFrom(std::shared_ptr state, + std::size_t maxBytes) + { + auto chunk = co_await state->inner->read(maxBytes); + if (!chunk.has_value()) + state->closeConnection(); + else if (chunk->end == BodyEnd::Reached && state->connection.has_value()) + { + state->trailers = co_await state->inner->trailers(); + state->settle(); + } + co_return chunk; + } + + static async::Task> trailersOf(std::shared_ptr state) + { + if (state->trailers.has_value()) + co_return std::move(*std::exchange(state->trailers, HttpResult { Fields {} })); + co_return co_await state->inner->trailers(); + } + + std::shared_ptr _state; + }; + +} // namespace + +HttpClient::HttpClient(net::EventLoop& loop, + net::IConnector& connector, + net::ITlsContext* tls, + HttpClientOptions options): + _loop { &loop }, + _connector { &connector }, + _tls { tls }, + _options { options }, + _pool { std::make_shared( + detail::Pool { .clock = &loop.clock(), + .maxIdlePerOrigin = options.maxIdlePerOrigin, + .maxConnectionsPerOrigin = options.maxConnectionsPerOrigin, + .maxConnectionsTotal = options.maxConnectionsTotal, + .idleTimeout = options.idleTimeout, + .origins = {} }) } +{ +} + +HttpClient::~HttpClient() = default; +HttpClient::HttpClient(HttpClient&&) noexcept = default; +HttpClient& HttpClient::operator=(HttpClient&&) noexcept = default; + +async::Task> HttpClient::send(OutgoingRequest request) +{ + Require(_pool != nullptr); // not a moved-from client + // 1. Everything that needs no connection, refused before one is taken. + auto head = headFor(request.origin, std::move(request.head)); + if (!head.has_value()) + co_return std::unexpected(std::move(head.error())); + if (request.origin.scheme == Scheme::Https && _tls == nullptr) + co_return std::unexpected( + detail::refusal(HttpErrorCode::ConfigurationError, "an https request to a client without TLS")); + auto const timeouts = request.timeouts.value_or(_options.timeouts); + auto const dialler = + Dialler { .loop = _loop, .connector = _connector, .tls = _tls, .limits = _options.limits }; + + // 2. and 3. A pooled connection, or a fresh one under the origin's cap. + auto acquired = acquire(_pool, poolKeyOf(request.origin), wireTimeoutsOf(timeouts)); + if (!acquired.has_value()) + co_return std::unexpected(std::move(acquired.error())); + auto connection = std::move(acquired->idle); + auto const provenance = connection.has_value() ? Provenance::Pooled : Provenance::Dialled; + if (!connection.has_value()) + { + auto dialled = co_await dial(dialler, request.origin, timeouts); + if (!dialled.has_value()) + co_return std::unexpected(std::move(dialled.error())); + connection.emplace(std::move(*dialled)); + } + + // 4. The exchange, sent again once on a fresh connection if a pooled one was stale. + auto const replay = replayOf(*head, request.body.get()); + auto again = replay == Replay::Allowed && provenance == Provenance::Pooled ? std::optional { *head } + : std::nullopt; + auto exchanged = co_await exchange(_loop, &*connection, std::move(*head), request.body.get()); + if (again.has_value() && isStale(exchanged)) + { + connection->close(); + auto dialled = co_await dial(dialler, request.origin, timeouts); + if (!dialled.has_value()) + co_return std::unexpected(std::move(dialled.error())); + connection.emplace(std::move(*dialled)); + // The body handed over nothing, but its source was asked for it: an empty one of the same + // framing stands in for it. + auto empty = request.body != nullptr ? std::make_unique(std::string {}) : nullptr; + exchanged = co_await exchange(_loop, &*connection, std::move(*again), empty.get()); + } + if (!exchanged.answer.has_value()) + co_return std::unexpected(std::move(exchanged.answer.error())); + auto response = std::move(*exchanged.answer); + response.body = std::make_unique( + std::move(response.body), std::move(*connection), std::move(acquired->lease)); + co_return response; +} + +std::size_t HttpClient::idleConnections() const noexcept +{ + Require(_pool != nullptr); // not a moved-from client + return _pool->idleCount(); +} + +} // namespace core::http diff --git a/src/core/http/HttpClient.hpp b/src/core/http/HttpClient.hpp new file mode 100644 index 00000000..13fc38e5 --- /dev/null +++ b/src/core/http/HttpClient.hpp @@ -0,0 +1,260 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// `HttpClient` -- HTTP/1.1 requests over kept-alive connections: the dial through an injected +/// @c net::IConnector, TLS through an injected @c net::ITlsContext, the exchange through a +/// @c Connection, a bounded pool of idle connections per origin, and every failure on the way +/// classified as an @c HttpErrorCode. + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace core::http +{ + +namespace detail +{ + struct Pool; +} // namespace detail + +/// Whether a request is sent in the clear or over TLS. +enum class Scheme : std::uint8_t +{ + Http, ///< Plain TCP. + Https, ///< TLS, through the client's @c net::ITlsContext. +}; + +/// @param scheme A scheme. +/// @return Its default port: 80, or 443 for @c Scheme::Https. +[[nodiscard]] constexpr std::uint16_t defaultPort(Scheme scheme) noexcept +{ + return scheme == Scheme::Https ? std::uint16_t { 443 } : std::uint16_t { 80 }; +} + +/// Where a request goes: the scheme, the host and the port, which together name one origin. +struct Origin +{ + Scheme scheme = Scheme::Http; ///< In the clear or over TLS. + /// A DNS name, an IPv4 literal, or an IPv6 literal with or without the brackets a URL authority + /// puts around it: the dial gets it without them, the Host field with. A host with a `:` is + /// taken for an IPv6 literal and must be one, so `host:port` is refused; the port goes in + /// @c port. **An IPv6 zone (`fe80::1%eth0`) is refused** (@c HttpErrorCode::RequestUriInvalid): a + /// zone is meaningful only on the host that names it, and RFC 6874 section 4 keeps it out of + /// what is sent, so a caller strips it and dials through a connector that knows the interface. + std::string host; + /// The TCP port, or none for the scheme's default (80, or 443 for @c Scheme::Https). The Host + /// field names it unless it is that default. + std::optional port; + + /// @return @c port, or the scheme's default when it is none. + [[nodiscard]] std::uint16_t effectivePort() const noexcept { return port.value_or(defaultPort(scheme)); } + + auto operator<=>(Origin const&) const = default; +}; + +/// The deadlines of one request, on the client loop's clock. +/// +/// **Each defaults to 600 seconds**, as `wasi:http`'s do in wasmtime, so a client built with no +/// options still bounds every wait. **A zero duration means no deadline** (R31): the client bounds +/// that wait by nothing, rather than by a deadline that fires at once. +struct HttpTimeouts +{ + /// What each deadline is unless set: wasmtime's `wasi:http` default. + static constexpr auto DefaultTimeout = std::chrono::milliseconds { std::chrono::seconds { 600 } }; + + /// The dial, name resolution included (@c net::DialOptions::connectTimeout), and then the TLS + /// handshake, each on its own: @c HttpErrorCode::ConnectionTimeout. A dial that runs out of it + /// while still resolving the name is a ConnectionTimeout too, never @c HttpErrorCode::DnsTimeout: + /// @c net::IConnector reports both as @c net::NetErrorCode::Timeout and tells them apart only in + /// words. **Bounding the handshake is this client's own rule** -- wasmtime leaves the TLS connect + /// unbounded -- so an https request may take up to twice this before its first request byte. + /// Zero leaves the dial to the platform's default, which may be minutes, and the handshake + /// unbounded. + std::chrono::milliseconds connect { DefaultTimeout }; + /// From the start of the exchange -- the request head's write and the response head's read start + /// together, once the connection is up -- to the response's first byte: + /// @c HttpErrorCode::ResponseTimeout. **The upload counts toward it**, as `wasi:http`'s + /// first-byte timeout does in wasmtime, so a body slower than this fails the request, and a server + /// that never reads the body is bounded by it. Restarted for each interim (1xx) response. + std::chrono::milliseconds firstByte { DefaultTimeout }; + /// Between any two reads after the first, the response body's included: + /// @c HttpErrorCode::ConnectionReadTimeout. + std::chrono::milliseconds betweenBytes { DefaultTimeout }; +}; + +/// How an @c HttpClient is configured, fixed at construction. +struct HttpClientOptions +{ + /// The most idle connections kept per origin for reuse; a connection that comes back past it is + /// closed. Zero keeps none. + std::size_t maxIdlePerOrigin = 4; + /// The most connections open to one origin at once, idle ones included. A request that finds + /// every one of them lent out is @c HttpErrorCode::ConnectionLimitReached, at once and without a + /// dial; one that finds an idle connection it cannot use closes that to make room. + std::size_t maxConnectionsPerOrigin = 16; + /// The most connections open at once to all origins together, idle ones included: the bound on + /// the file descriptors the client holds, however many ports or names it is sent to. A request + /// past it closes the idle connection that came back first, of any origin, to make room; with + /// none idle it is @c HttpErrorCode::ConnectionLimitReached, at once and without a dial. It does + /// not wait for a connection to come free: WASI's outgoing handler has no queue, and a refusal the + /// caller sees beats a wait the caller cannot bound. + std::size_t maxConnectionsTotal = 256; + /// How long an idle connection is kept, on the loop's clock. One past it is never reused, and is + /// closed by the next request to any origin (there is no timer of its own). **Zero means no + /// deadline** (R31): idle connections are then bounded by @c maxIdlePerOrigin alone. + std::chrono::milliseconds idleTimeout { 30'000 }; + /// The bounds every response is held to (@c Connection). + HttpLimits limits {}; + /// The deadlines of a request that names none of its own. + HttpTimeouts timeouts {}; +}; + +/// One request to send. +struct OutgoingRequest +{ + Origin origin; ///< Where it goes. + /// The method, the target, the version and the caller's fields. The client writes `Host` from + /// @c origin, and @c Connection the framing fields from @c body; a caller's `Host` or framing + /// field (@c isFramingField) is refused before the dial. + RequestHead head; + std::unique_ptr + body; ///< The body, or null for none; its shape picks the framing (@c framingFor). + std::optional timeouts; ///< This request's deadlines, or none for the client's. +}; + +/// The answer to a request: the final response's head, and its body to read. +struct IncomingResponse +{ + ResponseHead head; ///< The final (non-1xx) response's head. + /// The body, framed by the head. It holds the connection until the body's end: read to + /// @c BodyEnd::Reached on a connection that stays @c Reuse::Yes, the connection goes back to the + /// client's pool (a bodiless response's at once); dropped before that, failed, or outliving the + /// client, it closes the connection. Its trailers stay readable after the connection has gone + /// back. Loop-affine, like the client: read and drop it on the client's loop. + std::unique_ptr body; +}; + +/// Sends HTTP/1.1 requests over connections it keeps alive between them, one request at a time on +/// each (no pipelining). +/// +/// A request runs in four steps, and each step's failures have a code of their own: +/// +/// 1. **Checked before the dial**: an empty or malformed host is @c HttpErrorCode::RequestUriInvalid; +/// a caller's `Host` or framing field is @c HttpErrorCode::ProtocolError; @c Scheme::Https without +/// a TLS context is @c HttpErrorCode::ConfigurationError. Nothing is dialled for any of them. +/// 2. **A connection**: an idle one to the same origin (scheme, host case-insensitively, effective +/// port) opened under the same read deadlines, the most recently used first; else, within +/// @c HttpClientOptions::maxConnectionsPerOrigin (@c HttpErrorCode::ConnectionLimitReached past +/// it, and past @c HttpClientOptions::maxConnectionsTotal over all origins with no idle connection +/// to close for room), a dial through the connector, bounded by @c HttpTimeouts::connect. A name that does +/// not resolve, temporarily or for good, is @c HttpErrorCode::DnsError; a refusal +/// @c HttpErrorCode::ConnectionRefused; an unreachable host @c HttpErrorCode::DestinationUnavailable; +/// the deadline @c HttpErrorCode::ConnectionTimeout. +/// 3. **TLS**, for @c Scheme::Https: @c net::ITlsContext::wrapClient binds the connection to the +/// origin's host, then the handshake runs at once, bounded by @c HttpTimeouts::connect again, before +/// any request byte. A context that cannot verify a per-connection name -- every context from the +/// legacy @c makeTlsClientContext(caPem, expectedHostName, …), trust-on-first-use included (R23) -- +/// is @c HttpErrorCode::ConfigurationError, never a connection that is not verified for the host. A +/// refused handshake is the @c net::TlsFailure's @c TlsCertificateError, @c TlsProtocolError or +/// @c TlsAlertReceived, with the failure attached (@c HttpError::tls). +/// 4. **The exchange**: the request head and body are written while the response head is read +/// (@c async::whenAll), the response timeout running from the start. Interim (1xx) +/// responses are skipped, up to 32 of them, and a 33rd is @c HttpErrorCode::ProtocolError; a 101 +/// is too, since no request asks to upgrade. A failed read closes the connection and stops the write, so a +/// write parked on the socket or on a body source that honours its flow's stop token ends at once, and +/// answers the read's failure. A failed write answers its own failure, closing first, unless the peer cut +/// the connection (@c HttpErrorCode::ConnectionTerminated): then the read goes on, so a server that +/// refuses an upload and closes is still heard (a 413). Any failure on a connection whose TLS +/// session reports a @c net::TlsFailure is that failure's code. +/// +/// **A stale pooled connection is retried once.** A server may close a kept-alive connection while +/// it sits idle, and the client learns of it only by using it. When a connection from the pool fails +/// before the first response head arrived (no interim response either) with a transport failure -- +/// @c HttpErrorCode::ConnectionTerminated for the server's FIN or a reset, or +/// @c HttpErrorCode::InternalError for the OS error a write after that FIN draws (EPIPE, +/// WSAECONNABORTED), reported by the write or by the read that follows it, which the kernel and the +/// timing choose between -- the request is sent again on +/// a freshly dialled connection, but only when that cannot repeat an effect: its method is +/// idempotent (RFC 9110 section 9.2.2: GET, HEAD, OPTIONS, TRACE, PUT, DELETE) and it hands over no +/// body, its source null or of known length zero without trailers. Every other failure, and any +/// failure of a connection dialled for the request (the retry's included), is the answer. A reset +/// that cuts a pooled connection inside the first head counts as before it; RFC 9110 lets an +/// idempotent request be retried after any failure before its response is read. +/// +/// The request completes once its body is written and the final head is read. Loop-affine: +/// construct it, call @c send and await the result, and read and drop every response body on the +/// loop's thread. Destroying the client closes its idle connections; a response body still held +/// keeps its own connection and closes it at its end. +class CORE_HTTP_API HttpClient +{ + public: + /// @param loop The loop every connection is pinned to, and whose clock the deadlines are measured + /// on (not owned; outlives this, every request and every response body). + /// @param connector How connections are dialled (not owned; outlives this). Its sockets must be + /// pinned to @p loop. + /// @param tls The client context for @c Scheme::Https (not owned; outlives this), or null for a + /// client that sends in the clear only. + /// @param options The configuration. + HttpClient(net::EventLoop& loop, + net::IConnector& connector, + net::ITlsContext* tls, + HttpClientOptions options = {}); + ~HttpClient(); + HttpClient(HttpClient const&) = delete; + HttpClient& operator=(HttpClient const&) = delete; + /// Moves the client, its pool included. **A moved-from client may only be destroyed or assigned + /// to**: @c send and @c idleConnections on it are a contract violation (`Require`). **Neither + /// client may be moved while a @c send of it is running**: the running request holds the client + /// it was started on. Response bodies already handed out are unaffected; they hold the pool, not + /// the client. + HttpClient(HttpClient&&) noexcept; + /// @copydoc HttpClient(HttpClient&&) + HttpClient& operator=(HttpClient&&) noexcept; + + /// Sends @p request and reads the final response's head. + /// + /// **It completes only once the whole request body is written**, the final head read or not. + /// Three consequences follow, until the head is delivered before the upload ends (a carry to + /// P14): + /// - An early final response (a 413 to an upload) is not returned while the server stops + /// reading the rest: the send waits for the write, bounded only by @c HttpTimeouts::firstByte + /// if no response byte came, and otherwise by the caller's stop token. + /// - A read failure stops a write parked on a body source only if the source honours its flow's + /// stop token; one that ignores it delays the answer until it hands over its next chunk. + /// - Full duplex deadlocks: a body source that waits on the response body never gets it, since + /// the response is returned only after the body source has finished. + /// @param request The request, owned by the call. + /// @return The response, its body still to read, or the failure, classified as the class says. + /// @throws async::OperationCancelled if the awaiting flow's stop token is stopped while it runs. + [[nodiscard]] async::Task> send(OutgoingRequest request); + + /// @return How many idle connections the client holds for reuse, every origin's, not counting + /// one past @c HttpClientOptions::idleTimeout. + [[nodiscard]] std::size_t idleConnections() const noexcept; + + private: + net::EventLoop* _loop; + net::IConnector* _connector; + net::ITlsContext* _tls; + HttpClientOptions _options; + /// The idle connections and the count lent out, per origin; shared so that a response body can + /// give its connection back, and hold it only weakly. + std::shared_ptr _pool; +}; + +} // namespace core::http diff --git a/src/core/http/HttpClient_test.cpp b/src/core/http/HttpClient_test.cpp new file mode 100644 index 00000000..9bdaf9ab --- /dev/null +++ b/src/core/http/HttpClient_test.cpp @@ -0,0 +1,1806 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// `HttpClient` over `testing::ScriptedConnector`'s in-memory pairs on a hand-driven loop: what is +// refused before the dial, how a dial, a TLS wrap and a handshake fail, the request as written, the +// response as read, and how each half of the exchange ends the other. Every flow runs on a `TestLoop` +// over a `ManualClock`, so nothing here waits on anything but the loop the case drives, and a flow +// that never finishes leaves its answer empty instead of hanging the case. +#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 + +using core::http::BufferBodySource; +using core::http::HttpClient; +using core::http::HttpClientOptions; +using core::http::HttpErrorCode; +using core::http::HttpResult; +using core::http::HttpTimeouts; +using core::http::IncomingResponse; +using core::http::OutgoingRequest; +using core::http::test::AfterReply; +using core::http::test::answerHeadOnly; +using core::http::test::get; +using core::http::test::HandshakeOutcome; +using core::http::test::into; +using core::http::test::LegacyTlsContext; +using core::http::test::readAll; +using core::http::test::ReadBody; +using core::http::test::ReadOutcome; +using core::http::test::readUntilClosed; +using core::http::test::ScriptedServer; +using core::http::test::ScriptedTlsContext; +using core::http::test::scriptOf; +using core::http::test::ServedRequest; +using core::http::test::SlowBodySource; +using core::http::test::startSend; +using core::http::test::TlsScript; +using core::http::test::writeOnly; +using core::http::testing::ScriptedConnector; +using core::net::makeNetError; +using core::net::NetErrorCode; +using core::net::TlsFailure; +using core::net::TlsFailureKind; +using core::net::testing::TestLoop; +using core::platform::ManualClock; + +using namespace std::chrono_literals; + +namespace +{ + +using Answer = std::optional>; + +/// A loop driven by hand over a clock moved by hand, and a connector whose pairs hold at most +/// @c window bytes in each direction (zero: no bound). +struct Rig +{ + explicit Rig(std::size_t window = 0): connector { window } {} + + ManualClock clock {}; + TestLoop loop { clock }; + ScriptedConnector connector; +}; + +/// @return The server end of the oldest dial, as a scripted server; a missing dial fails the case. +std::unique_ptr acceptServer(Rig& rig) +{ + auto socket = rig.connector.acceptNext(); + REQUIRE(socket != nullptr); + return std::make_unique(rig.loop, std::move(socket)); +} + +/// @return @p request with @p fields appended; a field the factories refuse fails the case. +OutgoingRequest withFields(OutgoingRequest request, + std::vector> const& fields) +{ + for (auto const& [name, value]: fields) + REQUIRE(request.head.fields.append(name, value).has_value()); + return request; +} + +/// @return The error @p answer failed with; an answer that is missing or succeeded fails the case. +core::http::HttpError const& failureOf(Answer const& answer) +{ + REQUIRE(answer.has_value()); + REQUIRE_FALSE(answer->has_value()); + return answer->error(); +} + +/// Reads @p answer's response body to its end, on @p rig's loop. +ReadBody bodyOf(Rig& rig, Answer& answer) +{ + REQUIRE(answer.has_value()); + REQUIRE(answer->has_value()); + auto body = std::optional {}; + rig.loop.spawn(into(readAll((*answer)->body.get(), 1000), &body)); + std::ignore = rig.loop.drain(); + REQUIRE(body.has_value()); + return std::move(*body); +} + +/// The values of the field @p name in what the server read. +std::vector fieldValues(ServedRequest const& served, std::string_view name) +{ + REQUIRE(served.head.has_value()); + auto values = std::vector {}; + for (auto const value: served.head->fields.get(name)) + values.emplace_back(value); + return values; +} + +/// @return The client options with @p timeouts, the rest as the defaults say. +HttpClientOptions optionsWith(HttpTimeouts timeouts) +{ + auto options = HttpClientOptions {}; + options.timeouts = timeouts; + return options; +} + +constexpr auto OkReply = std::string_view { "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok" }; + +} // namespace + +TEST_CASE("HttpClient.aGetRoundTrips", "[http][client]") +{ + auto rig = Rig {}; + auto client = HttpClient { rig.loop, rig.connector, nullptr }; + auto answer = Answer {}; + startSend(rig.loop, client, get("http://example.test:8080/where?q=1"), &answer); + std::ignore = rig.loop.drain(); + REQUIRE(rig.connector.connects() == 1); + CHECK(rig.connector.dials()[0].host == "example.test"); + CHECK(rig.connector.dials()[0].port == 8080); + + auto server = acceptServer(rig); + auto served = std::optional {}; + rig.loop.spawn(into(server->answer(std::string { OkReply }, AfterReply::StaysOpen), &served)); + std::ignore = rig.loop.drain(); + REQUIRE(served.has_value()); + REQUIRE(served->head.has_value()); + CHECK(served->head->method.text() == "GET"); + CHECK(served->head->target.text() == "/where?q=1"); + REQUIRE_FALSE(served->head->fields.entries().empty()); + CHECK(served->head->fields.entries().front().name == "Host"); // first, as RFC 9112 section 3.2 asks + REQUIRE(answer.has_value()); + REQUIRE(answer->has_value()); + CHECK((*answer)->head.status == 200); + CHECK(bodyOf(rig, answer).text == "ok"); + CHECK(client.idleConnections() == 1); // read to its end, so pooled +} + +TEST_CASE("HttpClient.dialFailuresMapThroughTheTable", "[http][client]") +{ + struct Row + { + NetErrorCode net; + HttpErrorCode http; + }; + constexpr auto Rows = std::array { + Row { NetErrorCode::NameNotFound, HttpErrorCode::DnsError }, + Row { NetErrorCode::ResolverTemporaryFailure, HttpErrorCode::DnsError }, + Row { NetErrorCode::AddressError, HttpErrorCode::DnsError }, + Row { NetErrorCode::ConnRefused, HttpErrorCode::ConnectionRefused }, + Row { NetErrorCode::HostUnreach, HttpErrorCode::DestinationUnavailable }, + Row { NetErrorCode::Timeout, HttpErrorCode::ConnectionTimeout }, + Row { NetErrorCode::ConnReset, HttpErrorCode::ConnectionTerminated }, + Row { NetErrorCode::Eof, HttpErrorCode::ConnectionTerminated }, + Row { NetErrorCode::PermissionDenied, HttpErrorCode::InternalError }, // no row: the default + }; + for (auto const& row: Rows) + { + DYNAMIC_SECTION(core::net::toString(row.net)) + { + auto rig = Rig {}; + auto client = HttpClient { rig.loop, rig.connector, nullptr }; + rig.connector.refuseNext(makeNetError(row.net, 0, "scripted")); + auto answer = Answer {}; + startSend(rig.loop, client, get("http://example.test/"), &answer); + std::ignore = rig.loop.drain(); + auto const& error = failureOf(answer); + CHECK(error.code == row.http); + CHECK(error.detail.contains("scripted")); + CHECK(rig.connector.acceptNext() == nullptr); + } + } +} + +TEST_CASE("HttpClient.aSilentServerIsAResponseTimeout", "[http][client]") +{ + auto rig = Rig {}; + auto client = + HttpClient { rig.loop, + rig.connector, + nullptr, + optionsWith(HttpTimeouts { .connect = 0ms, .firstByte = 100ms, .betweenBytes = 0ms }) }; + auto answer = Answer {}; + startSend(rig.loop, client, get("http://example.test/"), &answer); + std::ignore = rig.loop.drain(); + auto server = acceptServer(rig); + auto served = std::optional {}; + rig.loop.spawn(into(server->answer({}, AfterReply::StaysOpen), &served)); + std::ignore = rig.loop.drain(); + REQUIRE(served.has_value()); + rig.clock.advance(99ms); + std::ignore = rig.loop.drain(); + REQUIRE_FALSE(answer.has_value()); + rig.clock.advance(1ms); + std::ignore = rig.loop.drain(); + CHECK(failureOf(answer).code == HttpErrorCode::ResponseTimeout); +} + +TEST_CASE("HttpClient.aRequestsOwnTimeoutsReplaceTheClients", "[http][client]") +{ + auto rig = Rig {}; + auto client = + HttpClient { rig.loop, + rig.connector, + nullptr, + optionsWith(HttpTimeouts { .connect = 5s, .firstByte = 0ms, .betweenBytes = 0ms }) }; + SECTION("the client's") + { + auto answer = Answer {}; + startSend(rig.loop, client, get("http://example.test/"), &answer); + std::ignore = rig.loop.drain(); + REQUIRE(rig.connector.connects() == 1); + CHECK(rig.connector.dials()[0].options.connectTimeout == 5s); + // End the exchange here, while its answer is in scope: the dropped server end ends it. + rig.connector.acceptNext().reset(); + std::ignore = rig.loop.drain(); + CHECK(failureOf(answer).code == HttpErrorCode::ConnectionTerminated); + } + SECTION("the request's") + { + auto request = get("http://example.test/"); + request.timeouts = HttpTimeouts { .connect = 7s, .firstByte = 100ms, .betweenBytes = 0ms }; + auto answer = Answer {}; + startSend(rig.loop, client, std::move(request), &answer); + std::ignore = rig.loop.drain(); + REQUIRE(rig.connector.connects() == 1); + CHECK(rig.connector.dials()[0].options.connectTimeout == 7s); + auto server = acceptServer(rig); + auto served = std::optional {}; + rig.loop.spawn(into(server->answer({}, AfterReply::StaysOpen), &served)); + rig.clock.advance(100ms); + std::ignore = rig.loop.drain(); + CHECK(failureOf(answer).code == HttpErrorCode::ResponseTimeout); + } +} + +TEST_CASE("HttpClient.zeroTimeoutsAreNone", "[http][client]") +{ + // R31: zero bounds nothing. The dial is left to the platform; a silent server is waited for. + auto rig = Rig {}; + auto client = + HttpClient { rig.loop, + rig.connector, + nullptr, + optionsWith(HttpTimeouts { .connect = 0ms, .firstByte = 0ms, .betweenBytes = 0ms }) }; + auto answer = Answer {}; + startSend(rig.loop, client, get("http://example.test/"), &answer); + std::ignore = rig.loop.drain(); + REQUIRE(rig.connector.connects() == 1); + CHECK(rig.connector.dials()[0].options.connectTimeout == 0ms); + auto server = acceptServer(rig); + auto served = std::optional {}; + rig.loop.spawn(into(server->answer({}, AfterReply::StaysOpen), &served)); + std::ignore = rig.loop.drain(); + rig.clock.advance(24h); + std::ignore = rig.loop.drain(); + REQUIRE_FALSE(answer.has_value()); + rig.loop.spawn(writeOnly(&server->connection().socket(), std::string { OkReply })); + std::ignore = rig.loop.drain(); + REQUIRE(answer.has_value()); + CHECK(answer->has_value()); +} + +TEST_CASE("HttpClient.theDefaultTimeoutsAre600Seconds", "[http][client]") +{ + // wasmtime's wasi:http defaults: a client built with no options still bounds every wait. + auto const defaults = HttpTimeouts {}; + CHECK(defaults.connect == 600s); + CHECK(defaults.firstByte == 600s); + CHECK(defaults.betweenBytes == 600s); + + auto rig = Rig {}; + auto client = HttpClient { rig.loop, rig.connector, nullptr }; + auto answer = Answer {}; + startSend(rig.loop, client, get("http://example.test/"), &answer); + std::ignore = rig.loop.drain(); + REQUIRE(rig.connector.connects() == 1); + CHECK(rig.connector.dials()[0].options.connectTimeout == 600s); + auto server = acceptServer(rig); + auto served = std::optional {}; + rig.loop.spawn(into(server->answer({}, AfterReply::StaysOpen), &served)); + std::ignore = rig.loop.drain(); + rig.clock.advance(599s); + std::ignore = rig.loop.drain(); + REQUIRE_FALSE(answer.has_value()); + rig.clock.advance(1s); + std::ignore = rig.loop.drain(); + CHECK(failureOf(answer).code == HttpErrorCode::ResponseTimeout); +} + +TEST_CASE("HttpClient.httpsWithoutATlsContextIsAConfigurationError", "[http][client]") +{ + auto rig = Rig {}; + auto client = HttpClient { rig.loop, rig.connector, nullptr }; + auto answer = Answer {}; + startSend(rig.loop, client, get("https://example.test/"), &answer); + std::ignore = rig.loop.drain(); + CHECK(failureOf(answer).code == HttpErrorCode::ConfigurationError); + CHECK(rig.connector.connects() == 0); +} + +TEST_CASE("HttpClient.httpsOverALegacyContextIsAConfigurationError", "[http][client]") +{ + // C3/R23: a context that does not override wrapClient cannot bind the name, so the default + // refuses it, and the client never falls back to a connection unverified for the host. + auto rig = Rig {}; + auto tls = LegacyTlsContext {}; + auto client = HttpClient { rig.loop, rig.connector, &tls }; + auto answer = Answer {}; + startSend(rig.loop, client, get("https://example.test/"), &answer); + std::ignore = rig.loop.drain(); + CHECK(failureOf(answer).code == HttpErrorCode::ConfigurationError); + CHECK(rig.connector.connects() == 1); + CHECK(tls.wraps() == 0); + auto server = rig.connector.acceptNext(); + REQUIRE(server != nullptr); + auto received = std::optional {}; + rig.loop.spawn(into(readUntilClosed(server.get()), &received)); + std::ignore = rig.loop.drain(); + REQUIRE(received.has_value()); // the dialled socket was dropped, unwritten + CHECK(received->empty()); +} + +TEST_CASE("HttpClient.wrapRefusalsMapThroughTheTable", "[http][client]") +{ + struct Row + { + NetErrorCode net; + HttpErrorCode http; + }; + constexpr auto Rows = std::array { + Row { NetErrorCode::Unsupported, HttpErrorCode::ConfigurationError }, + Row { NetErrorCode::AddressError, HttpErrorCode::RequestUriInvalid }, + Row { NetErrorCode::ResourceExhausted, HttpErrorCode::InternalError }, // no row: the default + }; + for (auto const& row: Rows) + { + DYNAMIC_SECTION(core::net::toString(row.net)) + { + auto rig = Rig {}; + auto script = TlsScript {}; + script.wrapError = makeNetError(row.net); + auto tls = ScriptedTlsContext { rig.loop, script }; + auto client = HttpClient { rig.loop, rig.connector, &tls }; + auto answer = Answer {}; + startSend(rig.loop, client, get("https://example.test/"), &answer); + std::ignore = rig.loop.drain(); + CHECK(failureOf(answer).code == row.http); + CHECK(tls.record().wraps == 0); + } + } +} + +TEST_CASE("HttpClient.aRefusedHandshakeIsItsTlsFailure", "[http][client]") +{ + // Reported from handshakeIfNeeded right after wrapClient, with the failure attached, and before + // any request byte: never as a write error. + struct Row + { + TlsFailureKind kind; + HttpErrorCode http; + }; + constexpr auto Rows = std::array { + Row { TlsFailureKind::Certificate, HttpErrorCode::TlsCertificateError }, + Row { TlsFailureKind::Protocol, HttpErrorCode::TlsProtocolError }, + Row { TlsFailureKind::AlertReceived, HttpErrorCode::TlsAlertReceived }, + }; + for (auto const& row: Rows) + { + DYNAMIC_SECTION("kind " << static_cast(row.kind)) + { + auto rig = Rig {}; + auto const failure = + TlsFailure { .kind = row.kind, .alert = std::uint8_t { 42 }, .message = "scripted refusal" }; + auto script = scriptOf(HandshakeOutcome::RefusedByTls); + script.failure = failure; + auto tls = ScriptedTlsContext { rig.loop, script }; + auto client = HttpClient { rig.loop, rig.connector, &tls }; + auto answer = Answer {}; + startSend(rig.loop, client, get("https://example.test:8443/"), &answer); + std::ignore = rig.loop.drain(); + auto const& error = failureOf(answer); + CHECK(error.code == row.http); + REQUIRE(error.tls.has_value()); + CHECK(error.tls->kind == row.kind); + CHECK(error.tls->alert == std::optional { std::uint8_t { 42 } }); + CHECK(error.tls->message == "scripted refusal"); + CHECK(tls.record().handshakes == 1); + CHECK(tls.record().writes == 0); + REQUIRE(tls.record().serverNames.size() == 1); + CHECK(tls.record().serverNames[0] == "example.test"); // the host, never host:port + } + } +} + +TEST_CASE("HttpClient.tlsIsBoundToTheBareHost", "[http][client]") +{ + // The port is split off for the name TLS checks, and an IPv6 literal goes without its brackets. + auto rig = Rig {}; + auto tls = ScriptedTlsContext { rig.loop, scriptOf(HandshakeOutcome::RefusedByTls) }; + auto client = HttpClient { rig.loop, rig.connector, &tls }; + auto answer = Answer {}; + startSend(rig.loop, client, get("https://[::1]:8443/"), &answer); + std::ignore = rig.loop.drain(); + REQUIRE(answer.has_value()); + REQUIRE(tls.record().serverNames.size() == 1); + CHECK(tls.record().serverNames[0] == "::1"); + REQUIRE(rig.connector.connects() == 1); + CHECK(rig.connector.dials()[0].host == "::1"); + CHECK(rig.connector.dials()[0].port == 8443); +} + +TEST_CASE("HttpClient.aHandshakeTheTransportCutMapsThroughTheTable", "[http][client]") +{ + // No TLS failure behind it: the socket's error says what happened. + auto rig = Rig {}; + auto script = scriptOf(HandshakeOutcome::CutByTransport); + script.transportError = makeNetError(NetErrorCode::ConnReset); + auto tls = ScriptedTlsContext { rig.loop, script }; + auto client = HttpClient { rig.loop, rig.connector, &tls }; + auto answer = Answer {}; + startSend(rig.loop, client, get("https://example.test/"), &answer); + std::ignore = rig.loop.drain(); + auto const& error = failureOf(answer); + CHECK(error.code == HttpErrorCode::ConnectionTerminated); + CHECK_FALSE(error.tls.has_value()); +} + +TEST_CASE("HttpClient.aStalledHandshakeIsAConnectionTimeout", "[http][client]") +{ + auto rig = Rig {}; + auto script = scriptOf(HandshakeOutcome::ParksThenSucceeds); + script.park = 1h; + auto tls = ScriptedTlsContext { rig.loop, script }; + auto client = + HttpClient { rig.loop, + rig.connector, + &tls, + optionsWith(HttpTimeouts { .connect = 100ms, .firstByte = 0ms, .betweenBytes = 0ms }) }; + auto answer = Answer {}; + startSend(rig.loop, client, get("https://example.test/"), &answer); + std::ignore = rig.loop.drain(); + rig.clock.advance(99ms); + std::ignore = rig.loop.drain(); + REQUIRE_FALSE(answer.has_value()); + rig.clock.advance(1ms); + std::ignore = rig.loop.drain(); + CHECK(failureOf(answer).code == HttpErrorCode::ConnectionTimeout); + CHECK(tls.record().writes == 0); +} + +TEST_CASE("HttpClient.aZeroConnectTimeoutLeavesTheHandshakeUnbounded", "[http][client]") +{ + // R31, for the handshake; and the exchange over TLS once it is settled. + auto rig = Rig {}; + auto script = scriptOf(HandshakeOutcome::ParksThenSucceeds); + script.park = 24h; + auto tls = ScriptedTlsContext { rig.loop, script }; + auto client = + HttpClient { rig.loop, + rig.connector, + &tls, + optionsWith(HttpTimeouts { .connect = 0ms, .firstByte = 0ms, .betweenBytes = 0ms }) }; + auto answer = Answer {}; + startSend(rig.loop, client, get("https://example.test/"), &answer); + std::ignore = rig.loop.drain(); + rig.clock.advance(23h); + std::ignore = rig.loop.drain(); + REQUIRE_FALSE(answer.has_value()); + CHECK(tls.record().writes == 0); + rig.clock.advance(1h); + std::ignore = rig.loop.drain(); + auto server = acceptServer(rig); + auto served = std::optional {}; + rig.loop.spawn(into(server->answer(std::string { OkReply }, AfterReply::StaysOpen), &served)); + std::ignore = rig.loop.drain(); + REQUIRE(served.has_value()); + CHECK(fieldValues(*served, "Host") + == std::vector { "example.test" }); // 443 is https's default + CHECK(tls.record().writesBeforeHandshake == 0); + CHECK(bodyOf(rig, answer).text == "ok"); +} + +TEST_CASE("HttpClient.aTlsFailureMidExchangeIsItsTlsFailure", "[http][client]") +{ + // The record layer refuses after the handshake: the socket's error is a SystemError, but the + // session says why, and that is the answer. + auto rig = Rig {}; + auto const failure = TlsFailure { .kind = TlsFailureKind::AlertReceived, + .alert = std::uint8_t { 20 }, + .message = "bad_record_mac" }; + auto script = scriptOf(HandshakeOutcome::Succeeds); + script.reads = ReadOutcome::RefusedByTls; + script.failure = failure; + auto tls = ScriptedTlsContext { rig.loop, script }; + auto client = HttpClient { rig.loop, rig.connector, &tls }; + auto answer = Answer {}; + startSend(rig.loop, client, get("https://example.test/"), &answer); + std::ignore = rig.loop.drain(); + auto const& error = failureOf(answer); + CHECK(error.code == HttpErrorCode::TlsAlertReceived); + REQUIRE(error.tls.has_value()); + CHECK(error.tls->alert == std::optional { std::uint8_t { 20 } }); +} + +TEST_CASE("HttpClient.interimResponsesAreSkipped", "[http][client]") +{ + auto rig = Rig {}; + auto client = HttpClient { rig.loop, rig.connector, nullptr }; + auto answer = Answer {}; + startSend(rig.loop, client, get("http://example.test/"), &answer); + std::ignore = rig.loop.drain(); + auto server = acceptServer(rig); + auto served = std::optional {}; + rig.loop.spawn(into(server->answer("HTTP/1.1 100 Continue\r\n\r\n" + "HTTP/1.1 103 Early Hints\r\nLink: \r\n\r\n" + "HTTP/1.1 201 Created\r\nContent-Length: 4\r\n\r\ndone", + AfterReply::StaysOpen), + &served)); + std::ignore = rig.loop.drain(); + REQUIRE(answer.has_value()); + REQUIRE(answer->has_value()); + CHECK((*answer)->head.status == 201); + CHECK(bodyOf(rig, answer).text == "done"); +} + +TEST_CASE("HttpClient.moreThan32InterimResponsesAreAProtocolError", "[http][client]") +{ + // Each interim head costs a read and nothing else: without a cap, a server could keep a request + // reading 1xx heads for as long as it liked, past every byte bound. + auto const interim = GENERATE(32, 33); + CAPTURE(interim); + auto rig = Rig {}; + auto client = HttpClient { rig.loop, rig.connector, nullptr }; + auto answer = Answer {}; + startSend(rig.loop, client, get("http://example.test/"), &answer); + std::ignore = rig.loop.drain(); + auto server = acceptServer(rig); + auto reply = std::string {}; + for ([[maybe_unused]] auto const index: std::views::iota(0, interim)) + reply += "HTTP/1.1 103 Early Hints\r\n\r\n"; + reply += "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok"; + auto served = std::optional {}; + rig.loop.spawn(into(server->answer(std::move(reply), AfterReply::StaysOpen), &served)); + std::ignore = rig.loop.drain(); + if (interim == 32) + { + REQUIRE(answer.has_value()); + REQUIRE(answer->has_value()); + CHECK((*answer)->head.status == 200); + } + else + CHECK(failureOf(answer).code == HttpErrorCode::ProtocolError); +} + +TEST_CASE("HttpClient.a101IsAProtocolError", "[http][client]") +{ + // No request asks to upgrade (Upgrade is a framing field the client refuses), so a 101 is not an + // interim answer to skip: the stream after it is another protocol's. + auto rig = Rig {}; + auto client = HttpClient { rig.loop, rig.connector, nullptr }; + auto answer = Answer {}; + startSend(rig.loop, client, get("http://example.test/"), &answer); + std::ignore = rig.loop.drain(); + auto server = acceptServer(rig); + auto served = std::optional {}; + rig.loop.spawn(into( + server->answer("HTTP/1.1 101 Switching Protocols\r\nUpgrade: x\r\n\r\n" + std::string { OkReply }, + AfterReply::StaysOpen), + &served)); + std::ignore = rig.loop.drain(); + CHECK(failureOf(answer).code == HttpErrorCode::ProtocolError); +} + +TEST_CASE("HttpClient.hostIsWrittenFromTheOrigin", "[http][client]") +{ + struct Row + { + std::string_view url; + std::string_view host; ///< The Host field written. + std::string_view dialHost; ///< What the connector was asked for. + }; + constexpr auto Rows = std::array { + Row { "http://example.test/", "example.test", "example.test" }, + Row { "http://example.test:80/", "example.test", "example.test" }, + Row { "http://example.test:8080/", "example.test:8080", "example.test" }, + Row { "http://192.0.2.1:81/", "192.0.2.1:81", "192.0.2.1" }, + Row { "http://[2001:db8::1]/", "[2001:db8::1]", "2001:db8::1" }, + Row { "http://[2001:db8::1]:8080/", "[2001:db8::1]:8080", "2001:db8::1" }, + }; + for (auto const& row: Rows) + { + DYNAMIC_SECTION(row.url) + { + auto rig = Rig {}; + auto client = HttpClient { rig.loop, rig.connector, nullptr }; + auto answer = Answer {}; + startSend(rig.loop, client, get(row.url), &answer); + std::ignore = rig.loop.drain(); + REQUIRE(rig.connector.connects() == 1); + CHECK(rig.connector.dials()[0].host == row.dialHost); + auto server = acceptServer(rig); + auto served = std::optional {}; + rig.loop.spawn(into(server->answer(std::string { OkReply }, AfterReply::StaysOpen), &served)); + std::ignore = rig.loop.drain(); + REQUIRE(served.has_value()); + CHECK(fieldValues(*served, "Host") == std::vector { std::string { row.host } }); + REQUIRE(answer.has_value()); + CHECK(answer->has_value()); + } + } + SECTION("an unbracketed IPv6 host is bracketed") + { + auto rig = Rig {}; + auto client = HttpClient { rig.loop, rig.connector, nullptr }; + auto request = get("http://example.test/"); + request.origin.host = "2001:db8::1"; + auto answer = Answer {}; + startSend(rig.loop, client, std::move(request), &answer); + std::ignore = rig.loop.drain(); + auto server = acceptServer(rig); + auto served = std::optional {}; + rig.loop.spawn(into(server->answer(std::string { OkReply }, AfterReply::StaysOpen), &served)); + std::ignore = rig.loop.drain(); + REQUIRE(served.has_value()); + CHECK(fieldValues(*served, "Host") == std::vector { "[2001:db8::1]" }); + } +} + +TEST_CASE("HttpClient.aCallersHostOrFramingFieldIsRefusedBeforeTheDial", "[http][client]") +{ + constexpr auto Names = std::array { + "Transfer-Encoding", "Content-Length", "Connection", "Upgrade", "TE", "Host", "host", + }; + for (auto const name: Names) + { + DYNAMIC_SECTION(name) + { + auto rig = Rig {}; + auto client = HttpClient { rig.loop, rig.connector, nullptr }; + auto answer = Answer {}; + startSend(rig.loop, + client, + withFields(get("http://example.test/"), { { std::string { name }, "chunked" } }), + &answer); + std::ignore = rig.loop.drain(); + auto const& error = failureOf(answer); + CHECK(error.code == HttpErrorCode::ProtocolError); + CHECK(error.fieldName == std::optional { std::string { name } }); + CHECK(rig.connector.connects() == 0); + } + } +} + +TEST_CASE("HttpClient.aMalformedHostIsRefusedBeforeTheDial", "[http][client]") +{ + constexpr auto Hosts = std::array { + "", "[]", "a b", "x/y", "a@b", "fe80::1%eth0", "fe80::1%251", "example.test:8080", "cafe:8080", + }; + for (auto const host: Hosts) + { + DYNAMIC_SECTION("'" << host << "'") + { + auto rig = Rig {}; + auto client = HttpClient { rig.loop, rig.connector, nullptr }; + auto request = get("http://example.test/"); + request.origin.host = std::string { host }; + auto answer = Answer {}; + startSend(rig.loop, client, std::move(request), &answer); + std::ignore = rig.loop.drain(); + CHECK(failureOf(answer).code == HttpErrorCode::RequestUriInvalid); + CHECK(rig.connector.connects() == 0); + } + } +} + +TEST_CASE("HttpClient.anUploadCountsTowardTheResponseTimeout", "[http][client]") +{ + // The first-byte timeout follows wasmtime's (P13 Task 16 ruling): it runs from the start of the + // exchange, the upload included. A body slower than it fails the request, and the write parked on + // the body source stops with the read, so the answer comes at the deadline, not after the body. + auto rig = Rig {}; + auto client = + HttpClient { rig.loop, + rig.connector, + nullptr, + optionsWith(HttpTimeouts { .connect = 0ms, .firstByte = 100ms, .betweenBytes = 0ms }) }; + auto request = get("http://example.test/upload", "PUT"); + request.body = std::make_unique( + rig.loop, std::vector { "aaaa", "bbbb", "cccc" }, 300ms); + auto answer = Answer {}; + startSend(rig.loop, client, std::move(request), &answer); + std::ignore = rig.loop.drain(); + auto server = acceptServer(rig); + auto served = std::optional {}; + rig.loop.spawn(into(server->answer({}, AfterReply::StaysOpen), &served)); + std::ignore = rig.loop.drain(); + rig.clock.advance(99ms); + std::ignore = rig.loop.drain(); + REQUIRE_FALSE(answer.has_value()); + rig.clock.advance(1ms); + std::ignore = rig.loop.drain(); + CHECK(failureOf(answer).code == HttpErrorCode::ResponseTimeout); +} + +TEST_CASE("HttpClient.aServerThatNeverReadsIsBoundedByTheResponseTimeout", "[http][client]") +{ + // The upload stalls on a 16-byte window the server never drains; the response timeout ends the + // request, and its close ends the stalled write. + auto rig = Rig { 16 }; + auto client = + HttpClient { rig.loop, + rig.connector, + nullptr, + optionsWith(HttpTimeouts { .connect = 0ms, .firstByte = 100ms, .betweenBytes = 0ms }) }; + auto request = get("http://example.test/upload", "PUT"); + request.body = std::make_unique(std::string(1000, 'x')); + auto answer = Answer {}; + startSend(rig.loop, client, std::move(request), &answer); + std::ignore = rig.loop.drain(); + auto server = rig.connector.acceptNext(); + REQUIRE(server != nullptr); + rig.clock.advance(99ms); + std::ignore = rig.loop.drain(); + REQUIRE_FALSE(answer.has_value()); + rig.clock.advance(1ms); + std::ignore = rig.loop.drain(); + CHECK(failureOf(answer).code == HttpErrorCode::ResponseTimeout); +} + +TEST_CASE("HttpClient.aReadFailureStopsAWriteParkedOnItsSource", "[http][client]") +{ + // The body source waits an hour for its next chunk and honours its flow's stop token; the server + // answers garbage. The read's failure is the answer at once, not in an hour. + auto rig = Rig {}; + auto client = HttpClient { rig.loop, rig.connector, nullptr }; + auto request = get("http://example.test/upload", "PUT"); + request.body = + std::make_unique(rig.loop, std::vector { "aaaa", "bbbb" }, 1h); + auto answer = Answer {}; + startSend(rig.loop, client, std::move(request), &answer); + std::ignore = rig.loop.drain(); + auto server = rig.connector.acceptNext(); + REQUIRE(server != nullptr); + rig.loop.spawn(writeOnly(server.get(), "this is no status line\r\n\r\n")); + std::ignore = rig.loop.drain(); + CHECK(failureOf(answer).code == HttpErrorCode::ProtocolError); +} + +TEST_CASE("HttpClient.anOriginWithoutAPortUsesTheSchemesDefault", "[http][client]") +{ + struct Row + { + core::http::Scheme scheme; + std::uint16_t port; + }; + constexpr auto Rows = + std::array { Row { core::http::Scheme::Http, 80 }, Row { core::http::Scheme::Https, 443 } }; + for (auto const& row: Rows) + { + DYNAMIC_SECTION("port " << row.port) + { + auto origin = core::http::Origin {}; + origin.scheme = row.scheme; + CHECK(origin.effectivePort() == row.port); + auto rig = Rig {}; + auto tls = ScriptedTlsContext { rig.loop, scriptOf(HandshakeOutcome::Succeeds) }; + auto client = HttpClient { rig.loop, rig.connector, &tls }; + auto request = get("http://example.test/"); + request.origin.scheme = row.scheme; + REQUIRE_FALSE(request.origin.port.has_value()); + auto answer = Answer {}; + startSend(rig.loop, client, std::move(request), &answer); + std::ignore = rig.loop.drain(); + REQUIRE(rig.connector.connects() == 1); + CHECK(rig.connector.dials()[0].port == row.port); + auto server = acceptServer(rig); + auto served = std::optional {}; + rig.loop.spawn(into(server->answer(std::string { OkReply }, AfterReply::StaysOpen), &served)); + std::ignore = rig.loop.drain(); + REQUIRE(served.has_value()); + CHECK(fieldValues(*served, "Host") == std::vector { "example.test" }); + } + } +} + +TEST_CASE("HttpClient.aFailedUploadAnswersItsOwnFailure", "[http][client]") +{ + // The body source fails: the write's failure is the answer, and it closes the connection, so the + // response read -- unbounded here -- ends with it instead of waiting on a server that waits too. + auto rig = Rig {}; + auto client = HttpClient { rig.loop, rig.connector, nullptr }; + auto request = get("http://example.test/upload", "PUT"); + request.body = + std::make_unique(rig.loop, std::vector { "aaaa", "bbbb" }, 10ms, 1); + auto answer = Answer {}; + startSend(rig.loop, client, std::move(request), &answer); + std::ignore = rig.loop.drain(); + auto server = acceptServer(rig); + auto served = std::optional {}; + rig.loop.spawn(into(server->answer({}, AfterReply::StaysOpen), &served)); + rig.clock.advance(10ms); + std::ignore = rig.loop.drain(); + rig.clock.advance(10ms); + std::ignore = rig.loop.drain(); + CHECK(failureOf(answer).code == HttpErrorCode::InternalError); +} + +TEST_CASE("HttpClient.aFailedReadEndsTheUpload", "[http][client]") +{ + // The server answers garbage and reads nothing, so the upload stalls on a 16-byte window: the + // read's failure closes the connection, which ends the stalled write, and is the answer. + auto rig = Rig { 16 }; + auto client = HttpClient { rig.loop, rig.connector, nullptr }; + auto request = get("http://example.test/upload", "PUT"); + request.body = std::make_unique(std::string(1000, 'x')); + auto answer = Answer {}; + startSend(rig.loop, client, std::move(request), &answer); + std::ignore = rig.loop.drain(); + auto server = rig.connector.acceptNext(); + REQUIRE(server != nullptr); + rig.loop.spawn(writeOnly(server.get(), "this is no status line\r\n\r\n")); + std::ignore = rig.loop.drain(); + CHECK(failureOf(answer).code == HttpErrorCode::ProtocolError); +} + +TEST_CASE("HttpClient.anUploadThePeerCutStillHearsItsAnswer", "[http][client]") +{ + // A server that refuses an upload answers and closes without reading it; the write fails because + // the peer is gone, and the response it left is still read. + auto rig = Rig { 16 }; + auto client = HttpClient { rig.loop, rig.connector, nullptr }; + auto request = get("http://example.test/upload", "PUT"); + request.body = std::make_unique(std::string(1000, 'x')); + auto answer = Answer {}; + startSend(rig.loop, client, std::move(request), &answer); + std::ignore = rig.loop.drain(); + auto server = rig.connector.acceptNext(); + REQUIRE(server != nullptr); + rig.loop.spawn(core::http::test::writeAndClose( + server.get(), "HTTP/1.1 413 Content Too Large\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")); + std::ignore = rig.loop.drain(); + REQUIRE(answer.has_value()); + REQUIRE(answer->has_value()); + CHECK((*answer)->head.status == 413); +} + +TEST_CASE("HttpClient.aResponseFramingRefusalIsTheAnswer", "[http][client]") +{ + auto rig = Rig {}; + auto client = HttpClient { rig.loop, rig.connector, nullptr }; + auto answer = Answer {}; + startSend(rig.loop, client, get("http://example.test/"), &answer); + std::ignore = rig.loop.drain(); + auto server = acceptServer(rig); + auto served = std::optional {}; + rig.loop.spawn(into(server->answer("HTTP/1.1 200 OK\r\nContent-Length: 1\r\nContent-Length: 2\r\n\r\nab", + AfterReply::StaysOpen), + &served)); + std::ignore = rig.loop.drain(); + CHECK(failureOf(answer).code == HttpErrorCode::ProtocolError); +} + +TEST_CASE("HttpClient.aHeadRequestsResponseHasNoBody", "[http][client]") +{ + // The response is framed by the request's method: a HEAD's announces a length it does not send. + auto rig = Rig {}; + auto client = HttpClient { rig.loop, rig.connector, nullptr }; + auto answer = Answer {}; + startSend(rig.loop, client, get("http://example.test/", "HEAD"), &answer); + std::ignore = rig.loop.drain(); + auto server = acceptServer(rig); + auto served = std::optional {}; + rig.loop.spawn(into( + server->answer("HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n", AfterReply::StaysOpen), &served)); + std::ignore = rig.loop.drain(); + auto const body = bodyOf(rig, answer); + CHECK(body.text.empty()); + CHECK_FALSE(body.error.has_value()); +} + +// ------------------------------------------------------------------------------------------------- +// The keep-alive pool: what goes back, what does not, how long it stays, how many there may be, and +// which failures of a pooled connection are sent again. + +namespace +{ + +/// One request as a server end saw it, and the client's answer to it. +struct Exchanged +{ + Answer answer; + std::optional served; ///< A connection's first request, read by a @c ScriptedServer. + std::optional startLine; ///< A later one's, read raw (@c answerHeadOnly). +}; + +/// Sends @p request and lets @p server answer it with @p reply, staying open. A null @p server +/// accepts the request's dial and reads the request through a @c ScriptedServer; a server already set +/// must be the connection the request reuses, and reads the (bodiless) request's head raw. +/// @param out Where the answer and what the server read go; must outlive the case's last drain. +void exchangeOn(Rig& rig, + HttpClient& client, + OutgoingRequest request, + std::unique_ptr& server, + std::string_view reply, + Exchanged* out) +{ + startSend(rig.loop, client, std::move(request), &out->answer); + std::ignore = rig.loop.drain(); + if (server == nullptr) + { + server = acceptServer(rig); + rig.loop.spawn(into(server->answer(std::string { reply }, AfterReply::StaysOpen), &out->served)); + } + else + rig.loop.spawn( + into(answerHeadOnly(&server->connection().socket(), std::string { reply }), &out->startLine)); + std::ignore = rig.loop.drain(); +} + +/// @return The target the server read; a request it did not read fails the case. +std::string targetOf(Exchanged const& exchanged) +{ + if (exchanged.startLine.has_value()) + { + auto const& line = *exchanged.startLine; + auto const from = line.find(' '); + REQUIRE(from != std::string::npos); + return line.substr(from + 1, line.find(' ', from + 1) - from - 1); + } + REQUIRE(exchanged.served.has_value()); + REQUIRE(exchanged.served->head.has_value()); + return std::string { exchanged.served->head->target.text() }; +} + +/// @return Whether @p socket's peer has closed it: a read to its end, on @p rig's loop, finished. A +/// read still parked is ended by closing @p socket, so it never outlives the answer it fills. +bool peerClosed(Rig& rig, core::net::ISocket& socket) +{ + auto rest = std::optional {}; + rig.loop.spawn(into(readUntilClosed(&socket), &rest)); + std::ignore = rig.loop.drain(); + auto const closed = rest.has_value(); + if (!closed) + { + socket.close(); + std::ignore = rig.loop.drain(); + } + return closed; +} + +/// @return The client options with @p change applied to the defaults. +template +HttpClientOptions optionsWhere(Change change) +{ + auto options = HttpClientOptions {}; + change(options); + return options; +} + +} // namespace + +TEST_CASE("HttpClient.aFullyReadResponseReturnsItsConnection", "[http][client][pool]") +{ + auto rig = Rig {}; + auto client = HttpClient { rig.loop, rig.connector, nullptr }; + auto server = std::unique_ptr {}; + auto first = Exchanged {}; + exchangeOn(rig, client, get("http://example.test/one"), server, OkReply, &first); + CHECK(targetOf(first) == "/one"); + CHECK(client.idleConnections() == 0); // the body is still unread + CHECK(bodyOf(rig, first.answer).text == "ok"); + CHECK(client.idleConnections() == 1); + + auto second = Exchanged {}; + exchangeOn(rig, client, get("http://example.test/two"), server, OkReply, &second); + CHECK(rig.connector.connects() == 1); + CHECK(targetOf(second) == "/two"); + CHECK(client.idleConnections() == 0); // lent out again + CHECK(bodyOf(rig, second.answer).text == "ok"); + CHECK(client.idleConnections() == 1); +} + +TEST_CASE("HttpClient.anOriginWithoutAPortSharesTheDefaultPortsConnections", "[http][client][pool]") +{ + auto rig = Rig {}; + auto client = HttpClient { rig.loop, rig.connector, nullptr }; + auto server = std::unique_ptr {}; + auto first = Exchanged {}; + exchangeOn(rig, client, get("http://Example.TEST/one"), server, OkReply, &first); + CHECK(bodyOf(rig, first.answer).text == "ok"); + auto second = Exchanged {}; + exchangeOn(rig, client, get("http://example.test:80/two"), server, OkReply, &second); + CHECK(rig.connector.connects() == 1); + CHECK(targetOf(second) == "/two"); + CHECK(bodyOf(rig, second.answer).text == "ok"); +} + +TEST_CASE("HttpClient.aPooledResponseKeepsItsTrailers", "[http][client][pool]") +{ + // The connection goes back at the body's end and the next request reuses it; the first response's + // trailers are still its own. + auto rig = Rig {}; + auto client = HttpClient { rig.loop, rig.connector, nullptr }; + auto server = std::unique_ptr {}; + auto first = Exchanged {}; + exchangeOn(rig, + client, + get("http://example.test/one"), + server, + "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n2\r\nok\r\n0\r\nX-Sum: 7\r\n\r\n", + &first); + CHECK(bodyOf(rig, first.answer).text == "ok"); + CHECK(client.idleConnections() == 1); + auto second = Exchanged {}; + exchangeOn(rig, client, get("http://example.test/two"), server, OkReply, &second); + CHECK(rig.connector.connects() == 1); + CHECK(bodyOf(rig, second.answer).text == "ok"); + + auto trailers = std::optional> {}; + rig.loop.spawn(into((*first.answer)->body->trailers(), &trailers)); + std::ignore = rig.loop.drain(); + REQUIRE(trailers.has_value()); + REQUIRE(trailers->has_value()); + auto const sum = (*trailers)->get("X-Sum"); + REQUIRE(std::ranges::distance(sum) == 1); + CHECK(*sum.begin() == "7"); +} + +TEST_CASE("HttpClient.anAbandonedBodyClosesItsConnection", "[http][client][pool]") +{ + auto rig = Rig {}; + auto client = HttpClient { rig.loop, rig.connector, nullptr }; + auto server = std::unique_ptr {}; + auto first = Exchanged {}; + exchangeOn(rig, + client, + get("http://example.test/one"), + server, + "HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nabc", + &first); + REQUIRE(first.answer.has_value()); + REQUIRE(first.answer->has_value()); + (*first.answer)->body.reset(); + CHECK(client.idleConnections() == 0); + CHECK(peerClosed(rig, server->connection().socket())); + + auto second = Answer {}; + startSend(rig.loop, client, get("http://example.test/two"), &second); + std::ignore = rig.loop.drain(); + CHECK(rig.connector.connects() == 2); + auto secondServer = acceptServer(rig); + secondServer->connection().close(); // ends the parked send while `second` is in scope + std::ignore = rig.loop.drain(); + CHECK(second.has_value()); +} + +TEST_CASE("HttpClient.aBodyDroppedUnderAParkedReadClosesItsConnection", "[http][client][pool]") +{ + // The read in flight keeps the connection's state alive past the reader; the drop still closes + // the connection, which ends that read instead of leaving it parked on an open socket. + auto rig = Rig {}; + auto client = HttpClient { rig.loop, rig.connector, nullptr }; + auto server = std::unique_ptr {}; + auto first = Exchanged {}; + exchangeOn(rig, + client, + get("http://example.test/one"), + server, + "HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n", + &first); + REQUIRE(first.answer.has_value()); + REQUIRE(first.answer->has_value()); + auto chunk = std::optional> {}; + rig.loop.spawn(into((*first.answer)->body->read(100), &chunk)); + std::ignore = rig.loop.drain(); + REQUIRE_FALSE(chunk.has_value()); + (*first.answer)->body.reset(); + std::ignore = rig.loop.drain(); + CHECK(chunk.has_value()); + CHECK(client.idleConnections() == 0); + CHECK(peerClosed(rig, server->connection().socket())); +} + +TEST_CASE("HttpClient.aBodilessResponseReturnsItsConnectionAtOnce", "[http][client][pool]") +{ + // A HEAD's response has no body to read, so nothing would ever reach its end: the connection goes + // back with the head. + auto rig = Rig {}; + auto client = HttpClient { rig.loop, rig.connector, nullptr }; + auto server = std::unique_ptr {}; + auto first = Exchanged {}; + exchangeOn(rig, + client, + get("http://example.test/one", "HEAD"), + server, + "HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n", + &first); + REQUIRE(first.answer.has_value()); + REQUIRE(first.answer->has_value()); + CHECK(client.idleConnections() == 1); + auto second = Exchanged {}; + exchangeOn(rig, client, get("http://example.test/two"), server, OkReply, &second); + CHECK(rig.connector.connects() == 1); + CHECK(bodyOf(rig, second.answer).text == "ok"); + // The first response's body reader still answers that its body is over. + CHECK(bodyOf(rig, first.answer).text.empty()); +} + +TEST_CASE("HttpClient.aConnectionWithUnreadBytesIsNotPooled", "[http][client][pool]") +{ + // A HEAD's answer framed by Content-Length carries no body, so the ten bytes the server sends after + // it are no part of any response: a pooled connection would hand them to the next request as its + // answer. The connection is closed instead and the next request dials afresh. + auto rig = Rig {}; + auto client = HttpClient { rig.loop, rig.connector, nullptr }; + auto server = std::unique_ptr {}; + auto first = Exchanged {}; + exchangeOn(rig, + client, + get("http://example.test/one", "HEAD"), + server, + "HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n0123456789", + &first); + REQUIRE(first.answer.has_value()); + REQUIRE(first.answer->has_value()); + CHECK(client.idleConnections() == 0); + auto fresh = std::unique_ptr {}; + auto second = Exchanged {}; + exchangeOn(rig, client, get("http://example.test/two"), fresh, OkReply, &second); + CHECK(rig.connector.connects() == 2); + CHECK(bodyOf(rig, second.answer).text == "ok"); +} + +TEST_CASE("HttpClient.aConnectionTheResponseClosesIsNotPooled", "[http][client][pool]") +{ + auto rig = Rig {}; + auto client = HttpClient { rig.loop, rig.connector, nullptr }; + auto server = std::unique_ptr {}; + auto first = Exchanged {}; + exchangeOn(rig, + client, + get("http://example.test/one"), + server, + "HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok", + &first); + CHECK(bodyOf(rig, first.answer).text == "ok"); + CHECK(client.idleConnections() == 0); + CHECK(peerClosed(rig, server->connection().socket())); +} + +TEST_CASE("HttpClient.theIdleCapClosesTheSurplus", "[http][client][pool]") +{ + auto const cap = GENERATE(std::size_t { 0 }, std::size_t { 1 }); + auto rig = Rig {}; + auto client = HttpClient { rig.loop, rig.connector, nullptr, optionsWhere([cap](HttpClientOptions& o) { + o.maxIdlePerOrigin = cap; + }) }; + auto answers = std::array {}; + startSend(rig.loop, client, get("http://example.test/a"), answers.data()); + startSend(rig.loop, client, get("http://example.test/b"), &answers[1]); + std::ignore = rig.loop.drain(); + REQUIRE(rig.connector.connects() == 2); + auto servers = std::array { acceptServer(rig), acceptServer(rig) }; + auto served = std::array, 2> {}; + for (auto const index: { std::size_t { 0 }, std::size_t { 1 } }) + rig.loop.spawn(into(servers.at(index)->answer(std::string { OkReply }, AfterReply::StaysOpen), + &served.at(index))); + std::ignore = rig.loop.drain(); + CHECK(bodyOf(rig, answers[0]).text == "ok"); + CHECK(bodyOf(rig, answers[1]).text == "ok"); + CHECK(client.idleConnections() == cap); + // The surplus is closed, not merely forgotten: the second connection back is the one past the cap. + CHECK(peerClosed(rig, servers[1]->connection().socket())); +} + +TEST_CASE("HttpClient.anIdleConnectionExpiresOnTheClientsClock", "[http][client][pool]") +{ + auto rig = Rig {}; + auto client = HttpClient { rig.loop, rig.connector, nullptr, optionsWhere([](HttpClientOptions& o) { + o.idleTimeout = 1000ms; + }) }; + auto server = std::unique_ptr {}; + auto first = Exchanged {}; + exchangeOn(rig, client, get("http://example.test/one"), server, OkReply, &first); + CHECK(bodyOf(rig, first.answer).text == "ok"); + rig.clock.advance(999ms); + CHECK(client.idleConnections() == 1); + SECTION("reused before its deadline") + { + auto second = Exchanged {}; + exchangeOn(rig, client, get("http://example.test/two"), server, OkReply, &second); + CHECK(rig.connector.connects() == 1); + CHECK(targetOf(second) == "/two"); + } + SECTION("closed at its deadline") + { + rig.clock.advance(1ms); + CHECK(client.idleConnections() == 0); + auto second = Answer {}; + startSend(rig.loop, client, get("http://example.test/two"), &second); + std::ignore = rig.loop.drain(); + CHECK(rig.connector.connects() == 2); + CHECK(peerClosed(rig, server->connection().socket())); // swept by the send + auto secondServer = acceptServer(rig); + secondServer->connection().close(); + std::ignore = rig.loop.drain(); + CHECK(second.has_value()); + } +} + +TEST_CASE("HttpClient.aConnectionIsReusedOnlyUnderItsOwnDeadlines", "[http][client][pool]") +{ + // A connection keeps the read deadlines it was opened with, so a request with others of its own + // gets a connection of its own; at the connection cap the idle one makes room. + auto const cap = GENERATE(std::size_t { 1 }, std::size_t { 16 }); + auto rig = Rig {}; + auto client = HttpClient { rig.loop, rig.connector, nullptr, optionsWhere([cap](HttpClientOptions& o) { + o.maxConnectionsPerOrigin = cap; + }) }; + auto server = std::unique_ptr {}; + auto first = Exchanged {}; + exchangeOn(rig, client, get("http://example.test/one"), server, OkReply, &first); + CHECK(bodyOf(rig, first.answer).text == "ok"); + REQUIRE(client.idleConnections() == 1); + + auto request = get("http://example.test/two"); + request.timeouts = HttpTimeouts { .connect = 0ms, .firstByte = 100ms, .betweenBytes = 0ms }; + auto second = Answer {}; + startSend(rig.loop, client, std::move(request), &second); + std::ignore = rig.loop.drain(); + CHECK(rig.connector.connects() == 2); + CHECK(client.idleConnections() == (cap == 1 ? 0U : 1U)); + if (cap == 1) + CHECK(peerClosed(rig, server->connection().socket())); // closed to make room, not forgotten + rig.clock.advance(100ms); + std::ignore = rig.loop.drain(); + CHECK(failureOf(second).code == HttpErrorCode::ResponseTimeout); +} + +TEST_CASE("HttpClient.theConnectionCapRefusesOneMore", "[http][client][pool]") +{ + auto rig = Rig {}; + auto client = HttpClient { rig.loop, rig.connector, nullptr, optionsWhere([](HttpClientOptions& o) { + o.maxConnectionsPerOrigin = 2; + }) }; + auto answers = std::array {}; + startSend(rig.loop, client, get("http://example.test/a"), answers.data()); + startSend(rig.loop, client, get("http://example.test/b"), &answers[1]); + startSend(rig.loop, client, get("http://example.test/c"), &answers[2]); + std::ignore = rig.loop.drain(); + CHECK(rig.connector.connects() == 2); + CHECK(failureOf(answers[2]).code == HttpErrorCode::ConnectionLimitReached); + + // The cap is per origin. + startSend(rig.loop, client, get("http://example.test:8080/d"), &answers[3]); + std::ignore = rig.loop.drain(); + CHECK(rig.connector.connects() == 3); + + // A request that failed gives its place back. + auto failed = rig.connector.acceptNext(); + REQUIRE(failed != nullptr); + failed->close(); + std::ignore = rig.loop.drain(); + CHECK(failureOf(answers[0]).code == HttpErrorCode::ConnectionTerminated); + startSend(rig.loop, client, get("http://example.test/e"), &answers[4]); + std::ignore = rig.loop.drain(); + CHECK(rig.connector.connects() == 4); + + // End every parked send while `answers` is in scope. + while (auto rest = rig.connector.acceptNext()) + rest->close(); + std::ignore = rig.loop.drain(); + for (auto const& answer: answers) + CHECK(answer.has_value()); +} + +TEST_CASE("HttpClient.aRefusedDialGivesItsPlaceBack", "[http][client][pool]") +{ + auto rig = Rig {}; + auto client = HttpClient { rig.loop, rig.connector, nullptr, optionsWhere([](HttpClientOptions& o) { + o.maxConnectionsPerOrigin = 1; + }) }; + rig.connector.refuseNext(makeNetError(NetErrorCode::ConnRefused, 0, "scripted")); + auto first = Answer {}; + startSend(rig.loop, client, get("http://example.test/a"), &first); + std::ignore = rig.loop.drain(); + CHECK(failureOf(first).code == HttpErrorCode::ConnectionRefused); + auto server = std::unique_ptr {}; + auto second = Exchanged {}; + exchangeOn(rig, client, get("http://example.test/b"), server, OkReply, &second); + CHECK(rig.connector.connects() == 2); + CHECK(bodyOf(rig, second.answer).text == "ok"); +} + +TEST_CASE("HttpClient.theClientDestroyedMidBodyLetsTheReadFinish", "[http][client][pool]") +{ + // The body reader holds its connection, and the pool only weakly: with the client gone the read + // still finishes, and the connection is closed at its end instead of going back. + auto rig = Rig {}; + auto client = std::make_unique(rig.loop, rig.connector, nullptr); + auto server = std::unique_ptr {}; + auto first = Exchanged {}; + exchangeOn(rig, + *client, + get("http://example.test/one"), + server, + "HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\nab", + &first); + REQUIRE(first.answer.has_value()); + REQUIRE(first.answer->has_value()); + client.reset(); + auto body = std::optional {}; + rig.loop.spawn(into(readAll((*first.answer)->body.get(), 1000), &body)); + std::ignore = rig.loop.drain(); + REQUIRE_FALSE(body.has_value()); + rig.loop.spawn(writeOnly(&server->connection().socket(), "cd")); + std::ignore = rig.loop.drain(); + REQUIRE(body.has_value()); + CHECK(body->text == "abcd"); + CHECK_FALSE(body->error.has_value()); + CHECK(peerClosed(rig, server->connection().socket())); +} + +namespace +{ + +/// What a stale-connection row sends as its body. +enum class RowBody : std::uint8_t +{ + None, ///< No source at all. + EmptyOnce, ///< A source of known length zero that hands its one chunk over once. + EmptyWithTrailers, ///< A source of known length zero with trailers: chunked, so not empty. + Data, ///< Four bytes. +}; + +/// A body of known length zero whose @c next may be called once, as @c IBodySource says: a second +/// call fails the body, so a retry that asked the spent source again would show. +class OneShotEmptySource final: public core::http::IBodySource +{ + public: + [[nodiscard]] std::optional knownLength() const noexcept override { return 0; } + [[nodiscard]] core::http::TrailerIntent trailerIntent() const noexcept override + { + return core::http::TrailerIntent::None; + } + [[nodiscard]] core::async::Task> next() override + { + return chunk(++_calls); + } + [[nodiscard]] core::async::Task> trailers() override { return none(); } + + private: + static core::async::Task> chunk(std::size_t call) + { + if (call > 1) + { + auto error = core::http::HttpError {}; + error.code = HttpErrorCode::InternalError; + error.detail = "asked twice"; + co_return std::unexpected(std::move(error)); + } + co_return core::http::BodyChunk { .bytes = {}, .end = core::http::BodyEnd::Reached }; + } + + static core::async::Task> none() { co_return core::http::Fields {}; } + + std::size_t _calls = 0; +}; + +/// A request to retry, and how the server ends the pooled connection it is sent on. +struct StaleRow +{ + std::string_view name; + std::string_view method; + RowBody body; +}; + +/// How a server ends a kept-alive connection while it sits in the client's pool. +enum class ServerEnds : std::uint8_t +{ + Closes, ///< In full: the client's write draws a reset, which its read reports as an OS error. + HalfCloses, ///< Its write side only: the client's write goes through and its read sees the end. +}; + +/// Wraps @c net::ISocket::shutdownWrite as a task. +core::async::Task halfClose(core::net::ISocket* socket) +{ + std::ignore = co_await socket->shutdownWrite(); +} + +/// Ends @p server's side of its connection as @p ends says. +void endServer(Rig& rig, ScriptedServer& server, ServerEnds ends) +{ + if (ends == ServerEnds::Closes) + server.connection().close(); + else + rig.loop.spawn(halfClose(&server.connection().socket())); + std::ignore = rig.loop.drain(); +} + +/// Reads a request off @p socket, writes @p wire and closes: a server that starts an answer and dies. +core::async::Task answerThenClose(core::net::ISocket* socket, std::string wire) +{ + std::ignore = co_await answerHeadOnly(socket, std::move(wire)); + socket->close(); +} + +/// Leaves @p server's pooled connection to the client after one exchange read to its end. +void poolOne(Rig& rig, HttpClient& client, std::unique_ptr& server, Exchanged* first) +{ + exchangeOn(rig, client, get("http://example.test/one"), server, OkReply, first); + REQUIRE(bodyOf(rig, first->answer).text == "ok"); + REQUIRE(client.idleConnections() == 1); +} + +/// @return A request for `/two` by @p row. +OutgoingRequest requestOf(StaleRow const& row) +{ + auto request = get("http://example.test/two", row.method); + switch (row.body) + { + case RowBody::None: break; + case RowBody::EmptyOnce: request.body = std::make_unique(); break; + case RowBody::EmptyWithTrailers: { + auto trailers = core::http::Fields {}; + REQUIRE(trailers.append("X-Sum", "0").has_value()); + request.body = std::make_unique(std::string {}, std::move(trailers)); + break; + } + case RowBody::Data: request.body = std::make_unique(std::string { "data" }); break; + } + return request; +} + +} // namespace + +TEST_CASE("HttpClient.aStaleReusedConnectionIsRetriedOnceForASafeRequest", "[http][client][pool]") +{ + // The server closed the kept-alive connection while it sat in the pool. A request whose method is + // idempotent and whose body is empty is sent again, once, on a fresh connection. + constexpr auto Rows = std::array { + StaleRow { .name = "GET", .method = "GET", .body = RowBody::None }, + StaleRow { .name = "HEAD", .method = "HEAD", .body = RowBody::None }, + StaleRow { .name = "DELETE", .method = "DELETE", .body = RowBody::None }, + StaleRow { .name = "PUT, empty", .method = "PUT", .body = RowBody::EmptyOnce }, + }; + auto const ends = GENERATE(ServerEnds::Closes, ServerEnds::HalfCloses); + for (auto const& row: Rows) + { + DYNAMIC_SECTION(row.name << (ends == ServerEnds::Closes ? ", closed" : ", half-closed")) + { + auto rig = Rig {}; + auto client = HttpClient { rig.loop, rig.connector, nullptr }; + auto server = std::unique_ptr {}; + auto first = Exchanged {}; + poolOne(rig, client, server, &first); + endServer(rig, *server, ends); + + auto fresh = std::unique_ptr {}; + auto second = Exchanged {}; + exchangeOn(rig, + client, + requestOf(row), + fresh, + row.method == "HEAD" ? "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n" : OkReply, + &second); + CHECK(rig.connector.connects() == 2); + CHECK(targetOf(second) == "/two"); + REQUIRE(second.answer.has_value()); + REQUIRE(second.answer->has_value()); + CHECK((*second.answer)->head.status == 200); + if (row.body == RowBody::EmptyOnce) + CHECK(fieldValues(*second.served, "Content-Length") == std::vector { "0" }); + } + } +} + +TEST_CASE("HttpClient.aStaleReusedConnectionIsNotRetriedForAnUnsafeRequest", "[http][client][pool]") +{ + // A method that is not idempotent, or a body that was handed over and cannot be handed over again, + // fails with the stale connection's error, and nothing is dialled. The body is the only + // difference from the retried rows, so the PUT and GET rows hold the body rule alone. + constexpr auto Rows = std::array { + StaleRow { .name = "POST", .method = "POST", .body = RowBody::None }, + StaleRow { .name = "PATCH", .method = "PATCH", .body = RowBody::None }, + StaleRow { .name = "PUT with a body", .method = "PUT", .body = RowBody::Data }, + StaleRow { .name = "GET with a body", .method = "GET", .body = RowBody::Data }, + StaleRow { .name = "PUT, empty with trailers", .method = "PUT", .body = RowBody::EmptyWithTrailers }, + }; + auto const ends = GENERATE(ServerEnds::Closes, ServerEnds::HalfCloses); + for (auto const& row: Rows) + { + DYNAMIC_SECTION(row.name << (ends == ServerEnds::Closes ? ", closed" : ", half-closed")) + { + auto rig = Rig {}; + auto client = HttpClient { rig.loop, rig.connector, nullptr }; + auto server = std::unique_ptr {}; + auto first = Exchanged {}; + poolOne(rig, client, server, &first); + endServer(rig, *server, ends); + auto second = Answer {}; + startSend(rig.loop, client, requestOf(row), &second); + std::ignore = rig.loop.drain(); + CHECK(failureOf(second).code + == (ends == ServerEnds::Closes ? HttpErrorCode::InternalError + : HttpErrorCode::ConnectionTerminated)); + CHECK(rig.connector.connects() == 1); + // A half-closed server still reads: end its side while `second` is in scope. + server->connection().close(); + std::ignore = rig.loop.drain(); + } + } +} + +TEST_CASE("HttpClient.aReusedConnectionThatAnsweredIsNotRetried", "[http][client][pool]") +{ + // A connection that closes cleanly after part of the first head, or after an interim head, is not + // stale: the server has seen the request. (A reset inside the first head is retried, as the class + // documents; HttpClient.aResetInsideTheFirstHeadIsRetried pins that.) + struct Row + { + std::string_view name; + std::string_view wire; + HttpErrorCode code; + }; + constexpr auto Rows = std::array { + Row { .name = "inside the head", .wire = "HTTP/1.1 2", .code = HttpErrorCode::ResponseIncomplete }, + Row { .name = "after an interim response", + .wire = "HTTP/1.1 100 Continue\r\n\r\n", + .code = HttpErrorCode::ConnectionTerminated }, + }; + for (auto const& row: Rows) + { + DYNAMIC_SECTION(row.name) + { + auto rig = Rig {}; + auto client = HttpClient { rig.loop, rig.connector, nullptr }; + auto server = std::unique_ptr {}; + auto first = Exchanged {}; + poolOne(rig, client, server, &first); + auto second = Answer {}; + startSend(rig.loop, client, get("http://example.test/two"), &second); + std::ignore = rig.loop.drain(); + rig.loop.spawn(answerThenClose(&server->connection().socket(), std::string { row.wire })); + std::ignore = rig.loop.drain(); + CHECK(failureOf(second).code == row.code); + CHECK(rig.connector.connects() == 1); + } + } +} + +TEST_CASE("HttpClient.aFreshConnectionsFailureIsFinal", "[http][client][pool]") +{ + // The retry is the stale connection's only: a request that fails on a connection dialled for it, + // the retry's own included, is answered with that failure. + auto rig = Rig {}; + auto client = HttpClient { rig.loop, rig.connector, nullptr }; + SECTION("a first request") + { + auto answer = Answer {}; + startSend(rig.loop, client, get("http://example.test/one"), &answer); + std::ignore = rig.loop.drain(); + auto server = rig.connector.acceptNext(); + REQUIRE(server != nullptr); + server->close(); + std::ignore = rig.loop.drain(); + CHECK(failureOf(answer).code == HttpErrorCode::ConnectionTerminated); + CHECK(rig.connector.connects() == 1); + } + SECTION("the retry") + { + auto server = std::unique_ptr {}; + auto first = Exchanged {}; + poolOne(rig, client, server, &first); + endServer(rig, *server, ServerEnds::Closes); + auto second = Answer {}; + startSend(rig.loop, client, get("http://example.test/two"), &second); + std::ignore = rig.loop.drain(); + REQUIRE(rig.connector.connects() == 2); + auto fresh = rig.connector.acceptNext(); + REQUIRE(fresh != nullptr); + fresh->close(); + std::ignore = rig.loop.drain(); + CHECK(failureOf(second).code == HttpErrorCode::ConnectionTerminated); + CHECK(rig.connector.connects() == 2); + // A third dial would be parked on a server end nobody closes: end it while `second` is in scope. + while (auto rest = rig.connector.acceptNext()) + rest->close(); + std::ignore = rig.loop.drain(); + } +} + +TEST_CASE("HttpClient.aFailedBodyGivesItsPlaceBack", "[http][client][pool]") +{ + // A body that fails is over: its connection is closed at the failure, not when the reader is + // dropped, so it holds no place under the cap. + auto rig = Rig {}; + auto client = HttpClient { rig.loop, rig.connector, nullptr, optionsWhere([](HttpClientOptions& o) { + o.maxConnectionsPerOrigin = 1; + }) }; + auto first = Answer {}; + startSend(rig.loop, client, get("http://example.test/one"), &first); + std::ignore = rig.loop.drain(); + auto server = acceptServer(rig); + auto served = std::optional {}; + rig.loop.spawn( + into(server->answer("HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\nab", AfterReply::Closes), &served)); + std::ignore = rig.loop.drain(); + auto const body = bodyOf(rig, first); + REQUIRE(body.error.has_value()); + CHECK(body.error->code == HttpErrorCode::ResponseIncomplete); + + auto second = Answer {}; + startSend(rig.loop, client, get("http://example.test/two"), &second); + std::ignore = rig.loop.drain(); + CHECK(rig.connector.connects() == 2); + while (auto rest = rig.connector.acceptNext()) + rest->close(); + std::ignore = rig.loop.drain(); + CHECK(second.has_value()); +} + +TEST_CASE("HttpClient.aResetInsideTheFirstHeadIsRetried", "[http][client][pool]") +{ + // The documented approximation: a reset reaches the client as ConnectionTerminated whether or not + // part of the head came before it, so a pooled connection reset inside its first head is stale + // like one reset before it. The request is idempotent and bodiless, so the retry is safe. + auto rig = Rig {}; + auto client = HttpClient { rig.loop, rig.connector, nullptr }; + auto server = std::unique_ptr {}; + auto first = Exchanged {}; + poolOne(rig, client, server, &first); + auto second = Answer {}; + startSend(rig.loop, client, get("http://example.test/two"), &second); + std::ignore = rig.loop.drain(); + // Part of a head, read by the client, then a close over the request the server never read: a reset. + rig.loop.spawn(writeOnly(&server->connection().socket(), "HTTP/1.1 2")); + std::ignore = rig.loop.drain(); + REQUIRE_FALSE(second.has_value()); + server->connection().close(); + std::ignore = rig.loop.drain(); + CHECK(rig.connector.connects() == 2); + auto fresh = acceptServer(rig); + auto served = std::optional {}; + rig.loop.spawn(into(fresh->answer(std::string { OkReply }, AfterReply::StaysOpen), &served)); + std::ignore = rig.loop.drain(); + REQUIRE(second.has_value()); + REQUIRE(second->has_value()); + CHECK((*second)->head.status == 200); +} + +TEST_CASE("HttpClient.anExpiredIdleConnectionHoldsNoRoomUnderTheIdleCap", "[http][client][pool]") +{ + // With room for one idle connection, a connection coming back finds that place taken by one past + // its deadline: that one is closed and the newcomer kept, rather than the other way round. + auto rig = Rig {}; + auto client = HttpClient { rig.loop, rig.connector, nullptr, optionsWhere([](HttpClientOptions& o) { + o.maxIdlePerOrigin = 1; + o.idleTimeout = 1000ms; + }) }; + auto answers = std::array {}; + startSend(rig.loop, client, get("http://example.test/a"), answers.data()); + startSend(rig.loop, client, get("http://example.test/b"), &answers[1]); + std::ignore = rig.loop.drain(); + REQUIRE(rig.connector.connects() == 2); + auto servers = std::array { acceptServer(rig), acceptServer(rig) }; + auto served = std::array, 2> {}; + for (auto const index: { std::size_t { 0 }, std::size_t { 1 } }) + rig.loop.spawn(into(servers.at(index)->answer(std::string { OkReply }, AfterReply::StaysOpen), + &served.at(index))); + std::ignore = rig.loop.drain(); + CHECK(bodyOf(rig, answers[0]).text == "ok"); + REQUIRE(client.idleConnections() == 1); + rig.clock.advance(1000ms); + CHECK(client.idleConnections() == 0); + CHECK(bodyOf(rig, answers[1]).text == "ok"); + CHECK(client.idleConnections() == 1); + CHECK(peerClosed(rig, servers[0]->connection().socket())); + CHECK_FALSE(peerClosed(rig, servers[1]->connection().socket())); +} + +TEST_CASE("HttpClient.theTotalCapEvictsTheOldestIdleConnectionOfAnyOrigin", "[http][client][pool]") +{ + auto rig = Rig {}; + auto client = HttpClient { rig.loop, rig.connector, nullptr, optionsWhere([](HttpClientOptions& o) { + o.maxConnectionsTotal = 2; + }) }; + auto first = std::unique_ptr {}; + auto a = Exchanged {}; + exchangeOn(rig, client, get("http://a.test/"), first, OkReply, &a); + CHECK(bodyOf(rig, a.answer).text == "ok"); + rig.clock.advance(1ms); + auto second = std::unique_ptr {}; + auto b = Exchanged {}; + exchangeOn(rig, client, get("http://b.test/"), second, OkReply, &b); + CHECK(bodyOf(rig, b.answer).text == "ok"); + REQUIRE(client.idleConnections() == 2); + + auto third = std::unique_ptr {}; + auto c = Exchanged {}; + exchangeOn(rig, client, get("http://c.test/"), third, OkReply, &c); + CHECK(rig.connector.connects() == 3); + CHECK(targetOf(c) == "/"); + CHECK(client.idleConnections() == 1); + CHECK(peerClosed(rig, first->connection().socket())); // the oldest idle made room + CHECK_FALSE(peerClosed(rig, second->connection().socket())); // the newer one stays +} + +TEST_CASE("HttpClient.theTotalCapRefusesWhenNoConnectionIsIdle", "[http][client][pool]") +{ + auto rig = Rig {}; + auto client = HttpClient { rig.loop, rig.connector, nullptr, optionsWhere([](HttpClientOptions& o) { + o.maxConnectionsTotal = 2; + }) }; + auto answers = std::array {}; + startSend(rig.loop, client, get("http://a.test/"), answers.data()); + startSend(rig.loop, client, get("http://b.test/"), &answers[1]); + startSend(rig.loop, client, get("http://c.test/"), &answers[2]); + std::ignore = rig.loop.drain(); + CHECK(rig.connector.connects() == 2); + CHECK(failureOf(answers[2]).code == HttpErrorCode::ConnectionLimitReached); + // A connection given up frees room under the total too. + auto gone = rig.connector.acceptNext(); + REQUIRE(gone != nullptr); + gone->close(); + std::ignore = rig.loop.drain(); + startSend(rig.loop, client, get("http://c.test/"), &answers[3]); + std::ignore = rig.loop.drain(); + CHECK(rig.connector.connects() == 3); + while (auto rest = rig.connector.acceptNext()) + rest->close(); + std::ignore = rig.loop.drain(); + for (auto const& answer: answers) + CHECK(answer.has_value()); +} + +TEST_CASE("HttpClient.aStalePooledHttpsConnectionIsRetriedOverAFreshHandshake", "[http][client][pool]") +{ + // Over the scripted TLS context (R29: the http binaries link no net_tls): the retry dials, wraps + // for the same host and handshakes again; the pool never hands an https connection to http. + auto rig = Rig {}; + auto tls = ScriptedTlsContext { rig.loop, scriptOf(HandshakeOutcome::Succeeds) }; + auto client = HttpClient { rig.loop, rig.connector, &tls }; + auto server = std::unique_ptr {}; + auto first = Exchanged {}; + exchangeOn(rig, client, get("https://example.test/one"), server, OkReply, &first); + CHECK(bodyOf(rig, first.answer).text == "ok"); + REQUIRE(client.idleConnections() == 1); + REQUIRE(tls.record().handshakes == 1); + endServer(rig, *server, ServerEnds::Closes); + + auto fresh = std::unique_ptr {}; + auto second = Exchanged {}; + exchangeOn(rig, client, get("https://example.test/two"), fresh, OkReply, &second); + CHECK(rig.connector.connects() == 2); + CHECK(tls.record().wraps == 2); + CHECK(tls.record().handshakes == 2); + CHECK(tls.record().serverNames == std::vector { "example.test", "example.test" }); + CHECK(targetOf(second) == "/two"); + CHECK(bodyOf(rig, second.answer).text == "ok"); + + // The same host in the clear is another origin: it dials rather than reuse the TLS connection. + auto plain = std::unique_ptr {}; + auto third = Exchanged {}; + exchangeOn(rig, client, get("http://example.test/three"), plain, OkReply, &third); + CHECK(rig.connector.connects() == 3); + CHECK(tls.record().wraps == 2); +} diff --git a/src/core/http/HttpTestSupport.hpp b/src/core/http/HttpTestSupport.hpp index 69a56713..42c5593e 100644 --- a/src/core/http/HttpTestSupport.hpp +++ b/src/core/http/HttpTestSupport.hpp @@ -3,15 +3,32 @@ /// @file /// Test-only helpers the `core::http` cases share: raw wire text written to a socket, a body read -/// to its end, and a flow run on a hand-driven loop until it has an answer. Test-only: in no -/// `FILE_SET`, so never installed. +/// to its end, a flow run on a hand-driven loop until it has an answer, a server end a case scripts, +/// and a TLS context whose handshake and failures a case scripts (R29: no `core::net_tls`, so the +/// binaries build without `CORE_CPP_WITH_TLS`). Test-only: in no `FILE_SET`, so never installed. #include #include +#include +#include +#include #include +#include #include +#include +#include +#include +#include +#include + +#include +#include +#include #include +#include +#include +#include #include #include #include @@ -76,6 +93,27 @@ inline async::Task readUntilClosed(net::ISocket* socket) } } +/// Reads one bodiless request head off @p socket as raw bytes and answers it with @p reply: a server +/// end that takes a second request on a connection a @c ScriptedServer, whose @c Connection holds its +/// raw reply for unwritten, has already served. +/// @param socket The server end; must outlive the returned task. +/// @param reply The raw response bytes. +/// @return The request's start line, or empty if the peer closed or failed first. +inline async::Task answerHeadOnly(net::ISocket* socket, std::string reply) +{ + auto text = std::string {}; + auto chunk = std::vector(512); + while (!text.contains("\r\n\r\n")) + { + auto const got = co_await socket->read(std::span { chunk }); + if (!got.has_value() || *got == 0) + co_return std::string {}; + text += textOf(std::span { chunk }.first(*got)); + } + static_cast(co_await socket->write(bytesOf(reply))); + co_return text.substr(0, text.find("\r\n")); +} + /// A body read to its end, chunk by chunk. struct ReadBody { @@ -117,4 +155,422 @@ async::Task into(async::Task task, std::optional* out) *out = co_await std::move(task); } +// ------------------------------------------------------------------------------------------------- +// The server end of a scripted exchange. + +/// What a server end read of one request: the head and the body. +struct ServedRequest +{ + std::optional head; ///< The head, if it was read. + ReadBody body; ///< The body, as far as it was read. + std::optional error; ///< What ended the read early, if anything did. +}; + +/// Whether a scripted server closes its end after its reply. +enum class AfterReply : std::uint8_t +{ + StaysOpen, + Closes, +}; + +/// The server end of one connection a case scripts: it reads a request through a @c Connection in +/// the request role, and answers with raw bytes, so a case can send what no well-behaved server would. +class ScriptedServer +{ + public: + /// @param loop The loop the connection runs on. + /// @param socket The server end, from @c testing::ScriptedConnector::acceptNext; must not be null. + ScriptedServer(net::EventLoop& loop, std::unique_ptr socket): + _connection { loop, std::move(socket), MessageRole::Request, HttpLimits {}, WireTimeouts {} } + { + } + + /// @return The connection, for its socket. + [[nodiscard]] Connection& connection() noexcept { return _connection; } + + /// Reads one request, its head and its body to the end, then writes @p reply as it is. + /// @param reply The raw response bytes; none writes nothing. + /// @param after Whether to close once they are written. + /// @return What was read. + [[nodiscard]] async::Task answer(std::string reply, AfterReply after) + { + return answerOn(&_connection, std::move(reply), after); + } + + private: + static async::Task answerOn(Connection* connection, std::string reply, AfterReply after) + { + auto out = ServedRequest {}; + auto head = co_await connection->readRequestHead(); + if (!head.has_value()) + { + out.error = std::move(head.error()); + co_return out; + } + auto framing = requestFraming(head->version, head->fields); + if (!framing.has_value()) + { + out.error = std::move(framing.error()); + co_return out; + } + out.head = std::move(*head); + auto reader = connection->bodyReader(*framing); + out.body = co_await readAll(reader.get(), 4096); + if (!reply.empty()) + static_cast(co_await connection->socket().write(bytesOf(reply))); + if (after == AfterReply::Closes) + connection->close(); + co_return out; + } + + Connection _connection; +}; + +/// A request for @p url, `http://host[:port]/target` or `https://…`, IPv6 hosts in brackets; without +/// a port the origin names none, so the scheme's default applies. +/// @param url The URL; anything else fails the case. +/// @param method The method. +/// @return The request, without a body. +[[nodiscard]] inline OutgoingRequest get(std::string_view url, std::string_view method = "GET") +{ + auto request = OutgoingRequest {}; + auto rest = url; + if (rest.starts_with("https://")) + { + request.origin.scheme = Scheme::Https; + rest.remove_prefix(8); + } + else + { + REQUIRE(rest.starts_with("http://")); + rest.remove_prefix(7); + } + auto const slash = rest.find('/'); + auto authority = rest.substr(0, slash); + auto const target = slash == std::string_view::npos ? std::string_view { "/" } : rest.substr(slash); + auto const portAt = authority.rfind(':'); + if (portAt != std::string_view::npos && authority.find(']', portAt) == std::string_view::npos) + { + auto const digits = authority.substr(portAt + 1); + auto port = std::uint16_t { 0 }; + auto const parsed = std::from_chars(digits.data(), digits.data() + digits.size(), port); + REQUIRE(parsed.ec == std::errc {}); + request.origin.port = port; + authority = authority.substr(0, portAt); + } + request.origin.host = std::string { authority }; + auto parsedMethod = Method::parse(method); + REQUIRE(parsedMethod.has_value()); + request.head.method = std::move(*parsedMethod); + auto parsedTarget = RequestTarget::parse(target); + REQUIRE(parsedTarget.has_value()); + request.head.target = std::move(*parsedTarget); + return request; +} + +/// Starts @p client sending @p request on @p loop; its answer lands in @p out. +/// @param loop The client's loop. +/// @param client The client; must outlive the flow. +/// @param request The request. +/// @param out Where the answer goes; must outlive the flow. +inline void startSend(net::EventLoop& loop, + HttpClient& client, + OutgoingRequest request, + std::optional>* out) +{ + loop.spawn(into(client.send(std::move(request)), out)); +} + +/// The next chunk after @p gap on @p loop's clock, or a failure of code @p fail instead. +inline async::Task> chunkAfter(net::EventLoop* loop, + std::chrono::milliseconds gap, + std::string text, + BodyEnd end, + std::optional fail) +{ + co_await loop->delay(gap); + if (fail.has_value()) + { + auto error = HttpError {}; + error.code = *fail; + co_return std::unexpected(std::move(error)); + } + auto const bytes = bytesOf(text); + co_return BodyChunk { .bytes = std::vector(bytes.begin(), bytes.end()), .end = end }; +} + +/// @return No trailers. +inline async::Task> noTrailers() +{ + co_return Fields {}; +} + +/// A body of a known length whose chunks arrive @c gap apart on the loop's clock: an upload slower +/// than a response timeout. With @c failAt set, that chunk fails (@c HttpErrorCode::InternalError) +/// instead of arriving. +class SlowBodySource final: public IBodySource +{ + public: + /// @param loop Whose clock the gaps are measured on. + /// @param chunks The body, chunk by chunk; must not be empty. + /// @param gap The wait before each chunk. + /// @param failAt The index of the chunk that fails, if one does. + SlowBodySource(net::EventLoop& loop, + std::vector chunks, + std::chrono::milliseconds gap, + std::optional failAt = std::nullopt): + _loop { &loop }, _chunks { std::move(chunks) }, _gap { gap }, _failAt { failAt } + { + } + + [[nodiscard]] std::optional knownLength() const noexcept override + { + auto total = std::uint64_t { 0 }; + for (auto const& chunk: _chunks) + total += chunk.size(); + return total; + } + + [[nodiscard]] TrailerIntent trailerIntent() const noexcept override { return TrailerIntent::None; } + + [[nodiscard]] async::Task> next() override + { + auto const index = _next++; + auto const end = _next == _chunks.size() ? BodyEnd::Reached : BodyEnd::More; + auto const fail = _failAt == index ? std::optional { HttpErrorCode::InternalError } : std::nullopt; + return chunkAfter(_loop, _gap, _chunks.at(index), end, fail); + } + + [[nodiscard]] async::Task> trailers() override { return noTrailers(); } + + private: + net::EventLoop* _loop; + std::vector _chunks; + std::chrono::milliseconds _gap; + std::optional _failAt; + std::size_t _next = 0; +}; + +// ------------------------------------------------------------------------------------------------- +// TLS, scripted (R29). + +/// How a @c ScriptedTlsSocket's handshake ends. +enum class HandshakeOutcome : std::uint8_t +{ + Succeeds, ///< At once. + RefusedByTls, ///< With @c TlsScript::failure reported by the session, and an error. + CutByTransport, ///< With @c TlsScript::transportError and no TLS failure, as a reset would. + ParksThenSucceeds, ///< After @c TlsScript::park on the loop's clock, honouring a stop. +}; + +/// What a @c ScriptedTlsSocket's reads do once the handshake has succeeded. +enum class ReadOutcome : std::uint8_t +{ + Forwards, ///< They read the transport. + RefusedByTls, ///< The first fails, the session reporting @c TlsScript::failure, as an alert would. +}; + +/// What a @c ScriptedTlsContext's connections do. +struct TlsScript +{ + std::optional wrapError; ///< What @c wrapClient answers instead of a socket, if set. + HandshakeOutcome handshake = HandshakeOutcome::Succeeds; ///< How the handshake ends. + ReadOutcome reads = ReadOutcome::Forwards; ///< What the reads after it do. + net::TlsFailure failure; ///< What a refusal reports. + net::NetError transportError = + net::makeNetError(net::NetErrorCode::ConnReset); ///< A cut handshake's error. + std::chrono::milliseconds park { 0 }; ///< How long a parked handshake waits. +}; + +/// @return The script whose handshake ends as @p handshake, everything else as the defaults say. +[[nodiscard]] inline TlsScript scriptOf(HandshakeOutcome handshake) +{ + auto script = TlsScript {}; + script.handshake = handshake; + return script; +} + +/// What a scripted context's connections saw, kept by the context so it outlives them. +struct TlsRecord +{ + std::vector serverNames; ///< The @c net::TlsPeer::serverName of every wrapClient. + std::size_t wraps = 0; ///< How many sockets were wrapped. + std::size_t handshakes = 0; ///< How many handshakes were asked for. + std::size_t writes = 0; ///< How many writes reached the TLS sockets. + std::size_t writesBeforeHandshake = 0; ///< How many of them came before a handshake had succeeded. +}; + +/// The session of a @c ScriptedTlsSocket: it reports a failure once one has been scripted to happen. +class ScriptedTlsSession final: public net::ITlsSession +{ + public: + ScriptedTlsSession() = default; + + [[nodiscard]] std::expected, std::string> channelBinding() const override + { + return std::unexpected(std::string { "scripted" }); + } + [[nodiscard]] std::optional> peerCertificateDigest() const override + { + return std::nullopt; + } + [[nodiscard]] std::optional negotiatedVersion() const override { return std::nullopt; } + [[nodiscard]] std::optional failure() const override { return _failure; } + + /// Makes @c failure report @p failure from now on. + void fail(net::TlsFailure failure) { _failure = std::move(failure); } + + private: + std::optional _failure; +}; + +/// A "TLS" socket that encrypts nothing: it forwards to the transport it owns, and its handshake and +/// reads end as its @c TlsScript says. +class ScriptedTlsSocket final: public net::ISocket +{ + public: + ScriptedTlsSocket(std::unique_ptr inner, + net::EventLoop& loop, + TlsScript script, + TlsRecord& record): + _inner { std::move(inner) }, _loop { &loop }, _script { std::move(script) }, _record { &record } + { + } + + [[nodiscard]] net::IoAwaitable read(std::span buffer) override + { + if (_script.reads == ReadOutcome::RefusedByTls) + { + _session.fail(_script.failure); + return net::IoAwaitable { std::unexpected( + net::makeNetError(net::NetErrorCode::SystemError, 0, "scripted TLS record refused")) }; + } + return _inner->read(buffer); + } + + [[nodiscard]] net::IoAwaitable write(std::span buffer) override + { + countWrite(); + return _inner->write(buffer); + } + + [[nodiscard]] net::IoAwaitable writeVectored(std::span const> segments, + std::shared_ptr keepAlive = {}) override + { + countWrite(); + return _inner->writeVectored(segments, std::move(keepAlive)); + } + + [[nodiscard]] net::ResultAwaitable handshakeIfNeeded() override + { + ++_record->handshakes; + switch (_script.handshake) + { + case HandshakeOutcome::Succeeds: + _isEstablished = Established::Yes; + return net::ResultAwaitable { net::ResultAwaitable::Result {} }; + case HandshakeOutcome::RefusedByTls: + _session.fail(_script.failure); + return net::ResultAwaitable { net::ResultAwaitable::Result { std::unexpected( + net::makeNetError(net::NetErrorCode::SystemError, 0, "scripted handshake refused")) } }; + case HandshakeOutcome::CutByTransport: + return net::ResultAwaitable { net::ResultAwaitable::Result { + std::unexpected(_script.transportError) } }; + case HandshakeOutcome::ParksThenSucceeds: + return net::ResultAwaitable { parkThenSucceed(this) }; + } + return net::ResultAwaitable { net::ResultAwaitable::Result {} }; + } + + void cancelRead() noexcept override { _inner->cancelRead(); } + [[nodiscard]] net::ITlsSession const* tlsSession() const noexcept override { return &_session; } + void close() noexcept override { _inner->close(); } + [[nodiscard]] bool isClosed() const noexcept override { return _inner->isClosed(); } + + private: + /// Whether a handshake has succeeded yet. + enum class Established : std::uint8_t + { + No, + Yes, + }; + + static async::Task> parkThenSucceed(ScriptedTlsSocket* self) + { + co_await self->_loop->delay(self->_script.park); + self->_isEstablished = Established::Yes; + co_return std::expected {}; + } + + void countWrite() noexcept + { + ++_record->writes; + if (_isEstablished == Established::No) + ++_record->writesBeforeHandshake; + } + + std::unique_ptr _inner; + net::EventLoop* _loop; + TlsScript _script; + TlsRecord* _record; + ScriptedTlsSession _session; + Established _isEstablished = Established::No; +}; + +/// A client context that binds the name it is given, and whose connections do what @c TlsScript says. +class ScriptedTlsContext final: public net::ITlsContext +{ + public: + /// @param loop Where a parked handshake waits. + /// @param script What every connection does. + ScriptedTlsContext(net::EventLoop& loop, TlsScript script): _loop { &loop }, _script { std::move(script) } + { + } + + [[nodiscard]] std::unique_ptr wrap(std::unique_ptr inner, + async::IExecutor& /*executor*/) override + { + ++_record.wraps; + return std::make_unique(std::move(inner), *_loop, _script, _record); + } + + [[nodiscard]] std::expected, net::NetError> wrapClient( + std::unique_ptr inner, async::IExecutor& executor, net::TlsPeer const& peer) override + { + _record.serverNames.push_back(peer.serverName); + if (_script.wrapError.has_value()) + return std::unexpected(*_script.wrapError); + return wrap(std::move(inner), executor); + } + + /// @return What its connections saw. + [[nodiscard]] TlsRecord const& record() const noexcept { return _record; } + + private: + net::EventLoop* _loop; + TlsScript _script; + TlsRecord _record; +}; + +/// A client context written before @c net::ITlsContext::wrapClient existed: it overrides @c wrap only, +/// so the default @c wrapClient refuses any server name (R23), as every legacy context's does. +class LegacyTlsContext final: public net::ITlsContext +{ + public: + LegacyTlsContext() = default; + + [[nodiscard]] std::unique_ptr wrap(std::unique_ptr inner, + async::IExecutor& /*executor*/) override + { + ++_wraps; + return inner; + } + + /// @return How many sockets were wrapped. + [[nodiscard]] std::size_t wraps() const noexcept { return _wraps; } + + private: + std::size_t _wraps = 0; +}; + } // namespace core::http::test diff --git a/src/core/http/testing/ScriptedConnector.cpp b/src/core/http/testing/ScriptedConnector.cpp new file mode 100644 index 00000000..897a3dbf --- /dev/null +++ b/src/core/http/testing/ScriptedConnector.cpp @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: Apache-2.0 +#include + +#include + +#include + +namespace core::http::testing +{ + +ScriptedConnector::ScriptedConnector(std::size_t maxBytesInFlight): _maxBytesInFlight { maxBytesInFlight } +{ +} + +ScriptedConnector::~ScriptedConnector() = default; + +async::Task ScriptedConnector::connect(std::string host, + std::uint16_t port, + net::DialOptions options) +{ + _dials.push_back(ScriptedDial { .host = std::move(host), .port = port, .options = options }); + if (!_refusals.empty()) + { + auto error = std::move(_refusals.front()); + _refusals.pop_front(); + co_return std::unexpected(std::move(error)); + } + auto pair = net::testing::InMemorySocketPair::create(_maxBytesInFlight); + _accepted.push_back(std::move(pair.server)); + co_return std::unique_ptr { std::move(pair.client) }; +} + +void ScriptedConnector::refuseNext(net::NetError error) +{ + _refusals.push_back(std::move(error)); +} + +std::unique_ptr ScriptedConnector::acceptNext() +{ + if (_accepted.empty()) + return nullptr; + auto socket = std::move(_accepted.front()); + _accepted.pop_front(); + return socket; +} + +std::size_t ScriptedConnector::connects() const noexcept +{ + return _dials.size(); +} + +std::span ScriptedConnector::dials() const noexcept +{ + return _dials; +} + +} // namespace core::http::testing diff --git a/src/core/http/testing/ScriptedConnector.hpp b/src/core/http/testing/ScriptedConnector.hpp new file mode 100644 index 00000000..69d43f43 --- /dev/null +++ b/src/core/http/testing/ScriptedConnector.hpp @@ -0,0 +1,77 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// `ScriptedConnector` -- an @c net::IConnector that dials nothing: each connection is a fresh +/// in-memory socket pair, whose client end the dial answers and whose server end a test accepts. + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace core::http::testing +{ + +/// One dial a @c ScriptedConnector was asked for, refused ones included. +struct ScriptedDial +{ + std::string host; ///< The host, as the dial named it. + std::uint16_t port = 0; ///< The port. + net::DialOptions options; ///< The budget and the options it asked for. +}; + +/// A connector whose connections are in-memory pairs (@c net::testing::InMemorySocketPair). +/// +/// A dial answers the client end at once, without suspending, and queues the server end for +/// @c acceptNext; a dial after @c refuseNext answers that error instead and queues nothing. It never +/// suspends, so a dial's deadline and its stop token have nothing to cut short. Loop-affine like the +/// sockets it hands out: one thread, the loop's. +class CORE_HTTP_API ScriptedConnector final: public net::IConnector +{ + public: + /// @param maxBytesInFlight What each direction of every pair holds before a writer waits; zero + /// for no bound (@c net::testing::InMemorySocketPair::create). + explicit ScriptedConnector(std::size_t maxBytesInFlight = 0); + ~ScriptedConnector() override; + ScriptedConnector(ScriptedConnector const&) = delete; + ScriptedConnector& operator=(ScriptedConnector const&) = delete; + ScriptedConnector(ScriptedConnector&&) = delete; + ScriptedConnector& operator=(ScriptedConnector&&) = delete; + + /// @copydoc net::IConnector::connect + [[nodiscard]] async::Task connect(std::string host, + std::uint16_t port, + net::DialOptions options) override; + + /// Answers the next dial with @p error. Queued: each call refuses one more dial. + /// @param error What that dial answers. + void refuseNext(net::NetError error); + + /// @return The server end of the oldest connection not yet accepted, or null when every one has + /// been. + [[nodiscard]] std::unique_ptr acceptNext(); + + /// @return How many dials were asked for, refused ones included. + [[nodiscard]] std::size_t connects() const noexcept; + + /// @return Every dial asked for, in order, refused ones included. + [[nodiscard]] std::span dials() const noexcept; + + private: + std::size_t _maxBytesInFlight; + std::deque _refusals; + std::deque> _accepted; + std::vector _dials; +}; + +} // namespace core::http::testing From 820d6544cc21082313d84356f38a4af11f749c44 Mon Sep 17 00:00:00 2001 From: Christian Parpart Date: Fri, 27 Nov 2026 05:12:12 +0100 Subject: [PATCH 14/19] feat(http): keep-alive HTTP/1.1 server with chunked bodies and trailers serveHttp accepts as net::serve does and serves each connection in a flow of its own, up to maxConnections. serveHttpConnection serves request after request over a Connection in the request role. Pipelined requests are answered in order, one at a time. Refusals are answered through errorStatusTable. The handler's own failure or exception is a 500 and a close. A body the handler left unread is drained up to maxDrainBytes once its reader is destroyed. Expect: 100-continue is sent on the first body read. Head, idle, between-bytes, whole-body and write deadlines bound a slow client, and are on by default. Also in this commit: - a severed exchange, whole-message deadlines, the shared accept loop - start the head deadline at the request's first byte - flood past what Windows holds in flight on loopback - Windows' loopback takes an unread flood whole - a status outside 100-999 is refused before the wire - the vendored consumer links core::http Signed-off-by: Christian Parpart --- .agent/reference/provenance.md | 4 + src/core/http/CMakeLists.txt | 14 +- src/core/http/Connection.cpp | 76 +- src/core/http/Connection.hpp | 10 + src/core/http/ConnectionLoopback_test.cpp | 13 +- src/core/http/Connection_test.cpp | 139 +++ src/core/http/HttpServer.cpp | 695 ++++++++++++ src/core/http/HttpServer.hpp | 213 ++++ src/core/http/HttpServerLoopback_test.cpp | 418 +++++++ src/core/http/HttpServer_test.cpp | 1232 +++++++++++++++++++++ src/core/http/HttpTestSupport.hpp | 430 ++++++- src/core/http/Message.hpp | 10 +- src/core/http/SmugglingCorpus.hpp | 33 + src/core/http/posix/HttpTestSupport.cpp | 5 + src/core/http/windows/HttpTestSupport.cpp | 5 + tests/consumer-vendored/CMakeLists.txt | 2 +- tests/consumer-vendored/main.cpp | 13 +- 17 files changed, 3285 insertions(+), 27 deletions(-) create mode 100644 src/core/http/HttpServer.cpp create mode 100644 src/core/http/HttpServer.hpp create mode 100644 src/core/http/HttpServerLoopback_test.cpp create mode 100644 src/core/http/HttpServer_test.cpp diff --git a/.agent/reference/provenance.md b/.agent/reference/provenance.md index 5400edc1..531982de 100644 --- a/.agent/reference/provenance.md +++ b/.agent/reference/provenance.md @@ -243,6 +243,10 @@ others in notes. | `src/core/http/HttpClient.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the dial, wrap and TLS-failure row tables; the exchange as two halves under `whenAll` | | `src/core/http/HttpClient.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): `HttpClient`, `Origin`, `HttpTimeouts` (zero is none), `OutgoingRequest`, `IncomingResponse` | | `src/core/http/HttpClient_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the client over `testing::ScriptedConnector` on a `TestLoop`, TLS scripted | +| `src/core/http/HttpServer.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the refusal-to-status table, the per-request exchange (drain, `100 Continue`, whole-head and whole-body deadlines), and an accept loop after `net::serve`'s | +| `src/core/http/HttpServer.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): `serveHttp`, `serveHttpConnection`, `IHttpHandler`, `HttpServerOptions`, `errorStatusTable` | +| `src/core/http/HttpServerLoopback_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the server over real sockets: an `HttpClient` round trip and the slow-client deadlines on every backend | +| `src/core/http/HttpServer_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the server over in-memory pairs on a `TestLoop`, the smuggling corpus with exact statuses | | `src/core/http/HttpTestSupport.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): test-only helpers the http cases share: a scripted server end, a slow body source, and a scripted TLS context (R29) | | `src/core/http/Message.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | | `src/core/http/Message.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): one `HttpErrorCode` per WASI 0.3 `wasi:http` `error-code` case, the validating field, method, target and reason factories | diff --git a/src/core/http/CMakeLists.txt b/src/core/http/CMakeLists.txt index 8ad2ef93..be32a809 100644 --- a/src/core/http/CMakeLists.txt +++ b/src/core/http/CMakeLists.txt @@ -6,14 +6,16 @@ # (Framing_test.cpp, over the shared SmugglingCorpus.hpp). Connection puts it on an ISocket: heads # and streamed bodies with trailers, read through one buffer of maxReadChunk bytes. HttpClient sends # a request over a connection of its own: the dial through an injected IConnector, TLS through an -# injected ITlsContext, and every failure on the way classified. testing/ScriptedConnector is the -# connector a consumer's test dials in memory with. +# injected ITlsContext, and every failure on the way classified. serveHttp is the keep-alive server +# over the same Connection, one flow per accepted socket, its refusals answered through one status +# table. testing/ScriptedConnector is the connector a consumer's test dials in memory with. core_cpp_add_module(http KIND STATIC HEADERS Body.hpp Connection.hpp Framing.hpp HttpClient.hpp + HttpServer.hpp Message.hpp testing/ScriptedConnector.hpp SOURCES @@ -21,6 +23,7 @@ core_cpp_add_module(http KIND STATIC Connection.cpp Framing.cpp HttpClient.cpp + HttpServer.cpp Message.cpp testing/ScriptedConnector.cpp PUBLIC_LIBS core::base core::net) @@ -35,16 +38,19 @@ core_cpp_add_test(http Connection_test.cpp Framing_test.cpp HttpClient_test.cpp + HttpServer_test.cpp HttpTestSupport.hpp Message_test.cpp SmugglingCorpus.hpp) -# Connection over a real socket pair on every backend this platform builds: the deadlines and the -# cancellations the in-memory double cannot drive. Its own binary for the label; a deadline defect +# Connection and the server over real sockets on every backend this platform builds: the deadlines +# and the cancellations the in-memory double cannot drive, and one HttpClient round trip against +# serveHttp on the default backend. Its own binary for the label; a deadline defect # hangs rather than fails, so every case runs under a watchdog, and TIMEOUT is the backstop. core_cpp_add_test(http NAME http_loopback SOURCES ConnectionLoopback_test.cpp + HttpServerLoopback_test.cpp HttpTestSupport.hpp SOURCES_POSIX posix/HttpTestSupport.cpp diff --git a/src/core/http/Connection.cpp b/src/core/http/Connection.cpp index 82a30ce9..80469e08 100644 --- a/src/core/http/Connection.cpp +++ b/src/core/http/Connection.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include @@ -395,6 +396,8 @@ namespace detail Fields trailers; /// The failure that ended the current body, repeated to every later read of it. std::optional bodyError; + /// When the current body's whole-body bound (@c WireTimeouts::body) runs out, if it has one. + std::optional bodyDeadline; ConnectionState(net::EventLoop* ownerLoop, std::unique_ptr ownedSocket, @@ -488,7 +491,8 @@ namespace /// @return The byte count, zero for the peer's EOF, or the failure (which breaks the stream). async::Task> fill(std::shared_ptr state, std::chrono::milliseconds timeout, - HttpErrorCode timeoutCode) + HttpErrorCode timeoutCode, + RefusalReason timeoutReason = RefusalReason::Unclassified) { if (state->readWire == Wire::Busy || state->readStream == Stream::Broken) co_return std::unexpected(state->fail(detail::refusal( @@ -513,8 +517,12 @@ namespace state->readWire = Wire::Idle; timer.reset(); if (!result.has_value() && deadline.expiry == Expiry::Fired) - co_return std::unexpected(state->fail( - detail::refusal(timeoutCode, std::format("no byte arrived within {} ms", timeout.count())))); + co_return std::unexpected( + state->fail(detail::refusal(timeoutCode, + std::format("no byte arrived within {} ms", timeout.count()), + std::nullopt, + std::nullopt, + timeoutReason))); if (!result.has_value()) co_return std::unexpected(state->fail(fromNet(result.error(), Direction::Read))); state->end = *result; @@ -546,10 +554,15 @@ namespace auto const& row = rowFor(state->role); auto parser = HeadParser { state->role, state->limits }; auto progress = HeadProgress::Nothing; + // The whole head's bound starts at its first byte: the wait for that byte is firstByte's + // budget alone, so a client that idles is not charged for it twice. + auto headDeadline = std::optional {}; while (true) { if (auto const bytes = state->buffered(); !bytes.empty()) { + if (progress == HeadProgress::Nothing && state->timeouts.head > 0ms) + headDeadline = state->loop->clock().now() + state->timeouts.head; progress = HeadProgress::Started; auto fed = parser.feed(bytes); if (!fed.has_value()) @@ -567,9 +580,26 @@ namespace continue; } auto const first = progress == HeadProgress::Nothing; - auto got = co_await fill(state, - first ? state->timeouts.firstByte : state->timeouts.betweenBytes, - first ? row.firstByteTimeout : HttpErrorCode::ConnectionReadTimeout); + auto const nothing = first ? RefusalReason::NothingArrived : RefusalReason::Unclassified; + auto wait = first ? state->timeouts.firstByte : state->timeouts.betweenBytes; + auto code = first ? row.firstByteTimeout : HttpErrorCode::ConnectionReadTimeout; + if (headDeadline.has_value()) + { + // The whole head's bound, asked before every read rather than armed once: a read + // whose bytes beat its cancel leaves no timer behind to bound the next one. + auto const now = state->loop->clock().now(); + if (now >= *headDeadline) + co_return std::unexpected(state->fail(detail::refusal( + HttpErrorCode::ConnectionReadTimeout, + std::format("the head took longer than {} ms", state->timeouts.head.count())))); + auto const left = std::chrono::ceil(*headDeadline - now); + if (wait <= 0ms || left < wait) + { + wait = left; + code = HttpErrorCode::ConnectionReadTimeout; + } + } + auto got = co_await fill(state, wait, code, nothing); if (!got.has_value()) co_return std::unexpected(std::move(got.error())); if (*got == 0) @@ -612,10 +642,29 @@ namespace return chunk; } + /// The deadline of the next body read: @c WireTimeouts::betweenBytes, capped by what is left of + /// the whole body's bound; or the refusal once that bound has run out. + [[nodiscard]] HttpResult bodyWait(ConnectionState const& state) + { + auto const wait = state.timeouts.betweenBytes; + if (!state.bodyDeadline.has_value()) + return wait; + auto const now = state.loop->clock().now(); + if (now >= *state.bodyDeadline) + return std::unexpected( + detail::refusal(HttpErrorCode::ConnectionReadTimeout, + std::format("the body took longer than {} ms", state.timeouts.body.count()))); + auto const left = std::chrono::ceil(*state.bodyDeadline - now); + return wait <= 0ms || left < wait ? left : wait; + } + /// Reads more of a body into the empty buffer; an EOF is the role's incomplete-message code. async::Task> fillBody(std::shared_ptr state) { - auto got = co_await fill(state, state->timeouts.betweenBytes, HttpErrorCode::ConnectionReadTimeout); + auto const wait = bodyWait(*state); + if (!wait.has_value()) + co_return std::unexpected(state->failBody(wait.error())); + auto got = co_await fill(state, *wait, HttpErrorCode::ConnectionReadTimeout); if (!got.has_value()) co_return std::unexpected(state->failBody(std::move(got.error()))); if (*got == 0) @@ -644,8 +693,10 @@ namespace { if (state->buffered().empty()) { - auto got = - co_await fill(state, state->timeouts.betweenBytes, HttpErrorCode::ConnectionReadTimeout); + auto const wait = bodyWait(*state); + if (!wait.has_value()) + co_return std::unexpected(state->failBody(wait.error())); + auto got = co_await fill(state, *wait, HttpErrorCode::ConnectionReadTimeout); if (!got.has_value()) co_return std::unexpected(state->failBody(std::move(got.error()))); if (*got == 0) @@ -803,6 +854,10 @@ namespace auto head = std::move(startLine); // Refused before the first wire byte: the connection is left as it was, so the caller may // send a corrected head (a handler's 500 after its own bad one). Nothing above changes state. + // A status line carries three digits: anything else would be a malformed line on the wire. + if (written == Written::Response && (status < 100 || status > 999)) + co_return std::unexpected(detail::refusal(HttpErrorCode::ProtocolError, + std::format("status {} is not three digits", status))); if (auto appended = appendCallerFields(head, fields); !appended.has_value()) co_return std::unexpected(std::move(appended.error())); auto const reply = written == Written::Response ? state->replyBody : ReplyBody::AsFramed; @@ -971,6 +1026,9 @@ std::unique_ptr Connection::bodyReader(Framing framing) else state.decoder.reset(); state.untilCloseBytes = 0; + state.bodyDeadline.reset(); + if (state.timeouts.body > 0ms) + state.bodyDeadline = state.loop->clock().now() + state.timeouts.body; if ((framing.persistence == Persistence::Close || framing.kind == BodyFraming::UntilClose) && state.persist == Persist::KeepAlive) state.persist = Persist::LastExchange; diff --git a/src/core/http/Connection.hpp b/src/core/http/Connection.hpp index fba1438f..c69d24bc 100644 --- a/src/core/http/Connection.hpp +++ b/src/core/http/Connection.hpp @@ -59,6 +59,16 @@ struct WireTimeouts /// Each write, a head's or a body chunk's, to its last byte (@c HttpErrorCode::ConnectionWriteTimeout). /// A peer that stops reading stalls a write at most this long. std::chrono::milliseconds write { 0 }; + /// A head as a whole, from its first byte to its last (@c HttpErrorCode::ConnectionReadTimeout): the + /// wait for that first byte is @c firstByte's alone, a separate budget. It is checked before every + /// read of the head after the first byte and caps each read's own deadline, so neither a trickle + /// of bytes each inside @c betweenBytes nor a read that beat its cancel by a byte (a completion + /// transport's, where the data wins) stretches a head past it. + std::chrono::milliseconds head { 0 }; + /// A body as a whole, from its reader's first adoption after the head to its last byte + /// (@c HttpErrorCode::ConnectionReadTimeout), checked before every read of it as @c head is. Time + /// the caller spends between reads counts: a read after the bound is refused at once. + std::chrono::milliseconds body { 0 }; }; /// One HTTP/1.1 connection, either end. diff --git a/src/core/http/ConnectionLoopback_test.cpp b/src/core/http/ConnectionLoopback_test.cpp index 2ac283ba..3090bb0a 100644 --- a/src/core/http/ConnectionLoopback_test.cpp +++ b/src/core/http/ConnectionLoopback_test.cpp @@ -79,15 +79,16 @@ constexpr auto SmallBuffer = std::uint64_t { 4096 }; /// peer that does not read stalls a writer. constexpr auto Flood = std::size_t { 4 } * 1024 * 1024; -/// Asserts that a write against a peer that never reads stalled. Wine's IOCP sockets take the whole -/// flood whatever the buffer sizes, so there the case could not run and says so; on a native -/// kernel a write that finished is the defect this case exists to find. +/// Asserts that a write against a peer that never reads stalled. Windows' loopback, natively and +/// under wine, takes the whole flood whatever the buffer sizes, so there the case could not run and +/// says so; on a kernel whose loopback stalls a write that finished is the defect this case exists +/// to find. /// @param finished Whether the write ran to its end. void expectStalled(bool finished) { - if (finished && core::http::test::runsUnderWine()) - SKIP("wine's IOCP sockets buffer the whole flood however small SO_SNDBUF/SO_RCVBUF are, so " - "no write stalls there"); + if (finished && core::http::test::loopbackFlood() == core::http::test::LoopbackFlood::Absorbed) + SKIP("Windows' loopback, natively and under wine, takes the whole flood however small " + "SO_SNDBUF/SO_RCVBUF are, so no write stalls there"); REQUIRE_FALSE(finished); } diff --git a/src/core/http/Connection_test.cpp b/src/core/http/Connection_test.cpp index 0d987564..586681c3 100644 --- a/src/core/http/Connection_test.cpp +++ b/src/core/http/Connection_test.cpp @@ -22,6 +22,7 @@ #include #include +#include #include #include @@ -1147,6 +1148,108 @@ TEST_CASE("Connection.aSilentPeerTimesOut", "[http][connection]") } } +namespace +{ + +/// Writes @p prefix, then @p text one byte every @p gap on @p loop's clock, each write awaited. +Task trickleAfter(core::net::EventLoop* loop, + ISocket* socket, + std::string prefix, + std::string text, + std::chrono::milliseconds gap) +{ + if (!prefix.empty() && !(co_await socket->write(core::http::test::bytesOf(prefix))).has_value()) + co_return; + for (auto const octet: text) + { + auto const one = std::string(1, octet); + if (!(co_await socket->write(core::http::test::bytesOf(one))).has_value()) + co_return; + co_await loop->delay(gap); + } +} + +/// A transport whose reads always beat their cancel: `cancelRead` reaches nothing, as a completion +/// transport's does when its receive has already finished (the data wins). +class UncancellableSocket final: public SocketDecorator +{ + public: + explicit UncancellableSocket(ISocket& inner) noexcept: SocketDecorator { inner } {} + + void cancelRead() noexcept override {} +}; + +} // namespace + +TEST_CASE("Connection.aHeadOrABodyAsAWholeIsBounded", "[http][connection]") +{ + // Every byte arrives inside betweenBytes; only the whole-message bound can end the trickle. Where + // the cancel reaches nothing, the bound still holds at the first read after it: one byte late. + enum class Cancel : std::uint8_t + { + Reaches, + Ignored, + }; + struct Row + { + std::string_view name; + WireTimeouts timeouts; + std::string_view prefix; + Cancel cancel; + std::chrono::milliseconds answeredAt; + }; + constexpr auto Head = std::string_view {}; + constexpr auto Body = std::string_view { "POST / HTTP/1.1\r\nHost: h\r\nContent-Length: 40\r\n\r\n" }; + constexpr auto Rows = std::array { + Row { "a head", WireTimeouts { .betweenBytes = 100ms, .head = 300ms }, Head, Cancel::Reaches, 300ms }, + Row { "a head whose read beats its cancel", + WireTimeouts { .betweenBytes = 100ms, .head = 300ms }, + Head, + Cancel::Ignored, + 360ms }, + Row { "a body", WireTimeouts { .betweenBytes = 100ms, .body = 300ms }, Body, Cancel::Reaches, 300ms }, + Row { "a body whose read beats its cancel", + WireTimeouts { .betweenBytes = 100ms, .body = 300ms }, + Body, + Cancel::Ignored, + 360ms }, + }; + for (auto const& row: Rows) + { + DYNAMIC_SECTION(row.name) + { + auto wire = Wire {}; + auto socket = + row.cancel == Cancel::Ignored + ? std::unique_ptr { std::make_unique(*wire.pair.server) } + : std::unique_ptr { std::move(wire.pair.server) }; + auto connection = Connection { + wire.loop, std::move(socket), MessageRole::Request, HttpLimits {}, row.timeouts + }; + auto const trickle = row.prefix.empty() + ? std::string { "GET / HTTP/1.1\r\nHost: h\r\nX-Slow: aaaaaaaaaa" } + : std::string(20, 'x'); + wire.loop.spawn( + trickleAfter(&wire.loop, wire.pair.client.get(), std::string { row.prefix }, trickle, 90ms)); + auto served = std::optional {}; + wire.loop.spawn(into(serveOne(&connection, 100), &served)); + std::ignore = wire.loop.drain(); + auto elapsed = 0ms; + while (!served.has_value() && elapsed < 2000ms) + { + wire.clock.advance(10ms); + elapsed += 10ms; + std::ignore = wire.loop.drain(); + } + REQUIRE(served.has_value()); + auto const code = + served->body.error.has_value() ? std::optional { served->body.error->code } : served->error; + CHECK(code == HttpErrorCode::ConnectionReadTimeout); + CHECK(elapsed == row.answeredAt); + } + } +} + TEST_CASE("Connection.aZeroTimeoutIsNone", "[http][connection]") { // R31: a zero duration means no deadline, not one that fires at once. @@ -2174,3 +2277,39 @@ TEST_CASE("Connection.aHeadRefusedForItsFramingCanBeCorrected", "[http][connecti REQUIRE(peer.has_value()); CHECK(*peer == "HTTP/1.1 204 \r\n\r\n"); } + +TEST_CASE("Connection.aStatusOutside100To999IsRefusedBeforeTheWire", "[http][connection]") +{ + // A status line carries three digits: 99 and 1000 would put a malformed line on the wire. Refused + // before the first byte, so a corrected head still follows. + auto const status = + GENERATE(std::uint16_t { 0 }, std::uint16_t { 99 }, std::uint16_t { 1000 }, std::uint16_t { 65535 }); + CAPTURE(status); + auto wire = Wire {}; + auto server = Connection { + wire.loop, std::move(wire.pair.server), MessageRole::Request, HttpLimits {}, NoTimeouts + }; + wire.loop.spawn(writeOnly(wire.pair.client.get(), "GET / HTTP/1.1\r\nHost: h\r\n\r\n")); + auto served = std::optional {}; + wire.loop.spawn(into(serveOne(&server, 100), &served)); + std::ignore = wire.loop.drain(); + REQUIRE(served.has_value()); + + auto peer = std::optional {}; + wire.loop.spawn(into(readUntilClosed(wire.pair.client.get()), &peer)); + auto refused = std::optional> {}; + wire.loop.spawn(into(server.writeResponseHead(responseHead(status, {}), Framing {}), &refused)); + std::ignore = wire.loop.drain(); + REQUIRE(refused.has_value()); + REQUIRE_FALSE(refused->has_value()); + CHECK(refused->error().code == HttpErrorCode::ProtocolError); + auto corrected = std::optional> {}; + wire.loop.spawn(into(server.writeResponseHead(responseHead(204, {}), Framing {}), &corrected)); + std::ignore = wire.loop.drain(); + REQUIRE(corrected.has_value()); + CHECK(corrected->has_value()); + server.close(); + std::ignore = wire.loop.drain(); + REQUIRE(peer.has_value()); + CHECK(*peer == "HTTP/1.1 204 \r\n\r\n"); +} diff --git a/src/core/http/HttpServer.cpp b/src/core/http/HttpServer.cpp new file mode 100644 index 00000000..7ffb78ac --- /dev/null +++ b/src/core/http/HttpServer.cpp @@ -0,0 +1,695 @@ +// SPDX-License-Identifier: Apache-2.0 +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace core::http +{ + +namespace +{ + + using namespace std::chrono_literals; + + /// The statuses refusals are answered with (RFC 9110 section 15, RFC 9112). A request's every + /// syntax and framing refusal is a 400 but the two RFC 9110 names apart, which the reason column + /// carries; a size is 413, 414 or 431 by what was too large; a read deadline is 408. + constexpr auto ErrorStatusRows = std::array { + ErrorStatusRow { HttpErrorCode::ProtocolError, RefusalReason::Unclassified, 400 }, + ErrorStatusRow { HttpErrorCode::ProtocolError, RefusalReason::UnsupportedVersion, 505 }, + ErrorStatusRow { HttpErrorCode::ProtocolError, RefusalReason::UnimplementedCoding, 501 }, + ErrorStatusRow { HttpErrorCode::RequestMethodInvalid, RefusalReason::Unclassified, 400 }, + ErrorStatusRow { HttpErrorCode::RequestUriInvalid, RefusalReason::Unclassified, 400 }, + ErrorStatusRow { HttpErrorCode::RequestUriTooLong, RefusalReason::Unclassified, 414 }, + ErrorStatusRow { HttpErrorCode::RequestHeaderSectionSize, RefusalReason::Unclassified, 431 }, + ErrorStatusRow { HttpErrorCode::RequestHeaderSize, RefusalReason::Unclassified, 431 }, + ErrorStatusRow { HttpErrorCode::RequestTrailerSectionSize, RefusalReason::Unclassified, 431 }, + ErrorStatusRow { HttpErrorCode::RequestTrailerSize, RefusalReason::Unclassified, 431 }, + ErrorStatusRow { HttpErrorCode::RequestBodySize, RefusalReason::Unclassified, 413 }, + ErrorStatusRow { HttpErrorCode::RequestLengthRequired, RefusalReason::Unclassified, 411 }, + ErrorStatusRow { HttpErrorCode::ConnectionReadTimeout, RefusalReason::Unclassified, 408 }, + ErrorStatusRow { HttpErrorCode::InternalError, RefusalReason::Unclassified, 500 }, + }; + + /// A refusal a server closes on without an answer, whatever its code's row says. + struct UnansweredRow + { + HttpErrorCode code; + RefusalReason reason; + }; + + /// An idle connection: no byte of a request arrived before its deadline (RFC 9112 section 9.5). + constexpr auto UnansweredRows = std::array { + UnansweredRow { HttpErrorCode::ConnectionReadTimeout, RefusalReason::NothingArrived }, + }; + + /// A status and its reason phrase. + struct StatusPhrase + { + std::uint16_t status; + std::string_view phrase; + }; + + /// The phrases of the statuses the server writes itself (RFC 9110 section 15). + constexpr auto StatusPhrases = std::array { + StatusPhrase { 100, "Continue" }, + StatusPhrase { 400, "Bad Request" }, + StatusPhrase { 408, "Request Timeout" }, + StatusPhrase { 411, "Length Required" }, + StatusPhrase { 413, "Content Too Large" }, + StatusPhrase { 414, "URI Too Long" }, + StatusPhrase { 431, "Request Header Fields Too Large" }, + StatusPhrase { 500, "Internal Server Error" }, + StatusPhrase { 501, "Not Implemented" }, + StatusPhrase { 505, "HTTP Version Not Supported" }, + }; + + /// The row a handler's own failure is answered with. + [[nodiscard]] ErrorStatusRow internalErrorRow() noexcept + { + return *std::ranges::find(ErrorStatusRows, HttpErrorCode::InternalError, &ErrorStatusRow::code); + } + + /// A head of @p status with its phrase. + [[nodiscard]] ResponseHead statusHead(std::uint16_t status) + { + auto head = ResponseHead {}; + head.status = status; + head.reason = ReasonPhrase::parse(statusPhrase(status)).value_or(ReasonPhrase {}); + return head; + } + + // --------------------------------------------------------------------------------------------- + // One exchange: what the server and the handler's body reader share about one request. + + /// Where `Expect: 100-continue` is. + enum class Continue : std::uint8_t + { + NotExpected, ///< The request did not ask, or cannot be answered with one (HTTP/1.0, no body). + Expected, ///< Asked for, and not yet sent: the first body read sends it. + Sending, ///< A body read is writing it. + Sent, ///< Written. + Moot, ///< The final response is under way, so none may follow. + }; + + /// Where the request body is. + enum class BodyState : std::uint8_t + { + Unread, ///< Not yet at its end. + Reached, ///< At its end. + Failed, ///< A read of it failed; the read side is over. + }; + + /// What a body read hands the server when it returns: only that it did. + struct ReadReturned + { + }; + + /// The state of one request a handler's body reader shares with the server, which may outlive the + /// server's flow when the handler keeps the reader: the server severs it when the request is over. + struct Exchange + { + Connection* connection; ///< The connection; null once severed, after which every read is refused. + Continue expect; ///< Where `Expect: 100-continue` is. + BodyState body = BodyState::Unread; ///< Where the body is. + std::uint64_t consumed = 0; ///< Body bytes read so far, the handler's and the drain's. + std::optional readFailure; ///< What ended the body, which answers a failed handler. + std::size_t readsInFlight = 0; ///< Body reads started and not yet returned. + async::AsyncQueue returned; ///< Told each time the last read in flight returns. + + Exchange(Connection* owner, net::EventLoop& loop, Continue expects): + connection { owner }, + expect { expects }, + returned { loop, + async::AsyncQueueOptions { .capacity = 1, + .overflow = async::AsyncQueueOverflow::DropOldest } } + { + } + + /// Records @p error as what ended the body, the first time, and hands it back. + [[nodiscard]] HttpError fail(HttpError error) + { + if (body != BodyState::Failed) + { + body = BodyState::Failed; + readFailure = error; + } + return error; + } + + /// No read reaches the connection from now on. + void sever() noexcept { connection = nullptr; } + }; + + /// Counts one body read in flight for as long as it lives, on every way out of it. + class ReadInFlight + { + public: + explicit ReadInFlight(Exchange* exchange) noexcept: _exchange { exchange } + { + ++_exchange->readsInFlight; + } + ~ReadInFlight() + { + if (--_exchange->readsInFlight == 0) + std::ignore = _exchange->returned.push(ReadReturned {}); + } + ReadInFlight(ReadInFlight const&) = delete; + ReadInFlight& operator=(ReadInFlight const&) = delete; + ReadInFlight(ReadInFlight&&) = delete; + ReadInFlight& operator=(ReadInFlight&&) = delete; + + private: + Exchange* _exchange; + }; + + /// The refusal of a read of a request that is over. + [[nodiscard]] HttpError requestOver() + { + return detail::refusal(HttpErrorCode::ConnectionTerminated, + "the request is over: its connection moved on"); + } + + /// The request body as the handler reads it: the connection's reader, with the interim response + /// sent on the first read, each failure recorded for the server, and every read refused once the + /// server has severed the exchange. + class ServerBodyReader final: public IBodyReader + { + public: + ServerBodyReader(std::shared_ptr exchange, std::unique_ptr inner): + _exchange { std::move(exchange) }, _inner { std::move(inner) } + { + } + + ~ServerBodyReader() override = default; + ServerBodyReader(ServerBodyReader const&) = delete; + ServerBodyReader& operator=(ServerBodyReader const&) = delete; + ServerBodyReader(ServerBodyReader&&) = delete; + ServerBodyReader& operator=(ServerBodyReader&&) = delete; + + [[nodiscard]] async::Task> read(std::size_t maxBytes) override + { + return readThrough(_exchange, _inner.get(), maxBytes); + } + + [[nodiscard]] async::Task> trailers() override + { + return trailersThrough(_exchange, _inner.get()); + } + + private: + static async::Task> readThrough(std::shared_ptr exchange, + IBodyReader* inner, + std::size_t maxBytes) + { + if (exchange->connection == nullptr) + co_return std::unexpected(requestOver()); + auto const inFlight = ReadInFlight { exchange.get() }; + if (exchange->expect == Continue::Expected) + { + exchange->expect = Continue::Sending; + auto wrote = co_await exchange->connection->writeResponseHead(statusHead(100), Framing {}); + if (!wrote.has_value()) + { + exchange->expect = Continue::Moot; + co_return std::unexpected(exchange->fail(std::move(wrote.error()))); + } + exchange->expect = Continue::Sent; + if (exchange->connection == nullptr) // severed while the interim response was written + co_return std::unexpected(requestOver()); + } + auto chunk = co_await inner->read(maxBytes); + if (!chunk.has_value()) + co_return std::unexpected(exchange->fail(std::move(chunk.error()))); + exchange->consumed += chunk->bytes.size(); + if (chunk->end == BodyEnd::Reached && exchange->body == BodyState::Unread) + exchange->body = BodyState::Reached; + co_return chunk; + } + + static async::Task> trailersThrough(std::shared_ptr exchange, + IBodyReader* inner) + { + if (exchange->connection == nullptr) + co_return std::unexpected(requestOver()); + auto trailers = co_await inner->trailers(); + if (!trailers.has_value()) + co_return std::unexpected(exchange->fail(std::move(trailers.error()))); + co_return trailers; + } + + std::shared_ptr _exchange; + std::unique_ptr _inner; + }; + + /// A body source with its trailers dropped: a chunked body sent to an HTTP/1.0 client, which reads + /// until close and has no trailer section. + class WithoutTrailers final: public IBodySource + { + public: + explicit WithoutTrailers(IBodySource* inner): _inner { inner } {} + + [[nodiscard]] std::optional knownLength() const noexcept override + { + return _inner->knownLength(); + } + [[nodiscard]] TrailerIntent trailerIntent() const noexcept override { return TrailerIntent::None; } + [[nodiscard]] async::Task> next() override { return _inner->next(); } + [[nodiscard]] async::Task> trailers() override { return none(); } + + private: + static async::Task> none() { co_return Fields {}; } + + IBodySource* _inner; + }; + + // --------------------------------------------------------------------------------------------- + // The exchange, request by request. + + /// Whether a connection carries another request. + enum class Next : std::uint8_t + { + Another, + Close, + }; + + /// Whether a request is the last its connection serves. + enum class LastRequest : std::uint8_t + { + No, + Yes, + }; + + /// How a drain of an unread body ended. + enum class Drained : std::uint8_t + { + Clean, ///< The body reached its end within the bound. + Close, ///< It is longer than the bound, or failed: the connection closes. + }; + + /// Whether @p head asks for `100 Continue` before its body, and may get one. + [[nodiscard]] Continue continueFor(RequestHead const& head, Framing const& framing) + { + auto const expects = std::ranges::any_of(head.fields.get("Expect"), [](std::string_view value) { + return detail::equalsIgnoringCase(value, "100-continue"); + }); + auto const hasBody = + framing.kind != BodyFraming::None && (framing.kind != BodyFraming::Length || framing.length != 0); + return expects && hasBody && head.version == HttpVersion::Http11 ? Continue::Expected + : Continue::NotExpected; + } + + /// Answers with @p row's status and `Connection: close`, if there is a row and the write side can + /// still take it; a write refused or failed is the end of the connection either way. + async::Task answer(Connection* connection, std::optional row) + { + if (!row.has_value()) + co_return; + std::ignore = co_await connection->writeResponseHead( + statusHead(row->status), + Framing { .kind = BodyFraming::None, .length = 0, .persistence = Persistence::Close }); + } + + /// Reads and discards what the handler left of the body, up to @p maxBytes; a known remainder + /// past them is not read at all. + async::Task drain(std::shared_ptr exchange, + Connection* connection, + Framing framing, + std::uint64_t maxBytes, + std::size_t chunkBytes) + { + if (exchange->body != BodyState::Unread) + co_return exchange->body == BodyState::Reached ? Drained::Clean : Drained::Close; + if (framing.kind == BodyFraming::Length && framing.length - exchange->consumed > maxBytes) + co_return Drained::Close; + auto reader = ServerBodyReader { exchange, connection->bodyReader(framing) }; + auto const start = exchange->consumed; + while (true) + { + auto chunk = co_await reader.read(chunkBytes); + if (!chunk.has_value() || exchange->consumed - start > maxBytes) + co_return Drained::Close; + if (chunk->end == BodyEnd::Reached) + co_return Drained::Clean; + } + } + + /// Runs the flow @p start starts; an exception it throws, but for a cancellation of the flow, + /// becomes its @c HttpErrorCode::InternalError, named after @p what. + template + std::invoke_result_t guarded(Start start, char const* what) + { + auto thrown = std::string {}; + try + { + co_return co_await start(); + } + catch (async::OperationCancelled const&) + { + throw; + } + catch (std::exception const& error) + { + thrown = error.what(); + } + catch (...) + { + thrown = "an exception that is no std::exception"; + } + co_return std::unexpected( + detail::refusal(HttpErrorCode::InternalError, std::format("{} threw: {}", what, thrown))); + } + + /// Serves one request of @p connection; @p current receives its exchange, which the caller severs. + async::Task serveOne(net::EventLoop* loop, + Connection* connection, + IHttpHandler* handler, + HttpServerOptions const* options, + std::optional peer, + LastRequest last, + std::shared_ptr* current) + { + auto head = co_await connection->readRequestHead(); + if (!head.has_value()) + { + co_await answer(connection, errorStatusFor(head.error())); + co_return Next::Close; + } + auto const framing = requestFraming(head->version, head->fields); + if (!framing.has_value()) + { + co_await answer(connection, errorStatusFor(framing.error())); + co_return Next::Close; + } + auto inner = connection->bodyReader(*framing); + // Zero bytes read nothing and report where the body is: a declared length past maxBodyBytes + // is refused here, before the handler sees the request. + auto const probe = co_await inner->read(0); + if (!probe.has_value()) + { + co_await answer(connection, errorStatusFor(probe.error())); + co_return Next::Close; + } + auto const version = head->version; + auto exchange = std::make_shared(connection, *loop, continueFor(*head, *framing)); + *current = exchange; + if (probe->end == BodyEnd::Reached) + exchange->body = BodyState::Reached; + + auto result = co_await guarded( + [handler, + request = + IncomingRequest { .head = std::move(*head), + .body = std::make_unique(exchange, std::move(inner)), + .peer = peer }]() mutable { return handler->handle(std::move(request)); }, + "the handler"); + + // A read the handler left running is writing the interim response: no final one can follow. + if (exchange->expect == Continue::Sending) + co_return Next::Close; + auto const continueUnsent = exchange->expect == Continue::Expected; + exchange->expect = Continue::Moot; + if (!result.has_value()) + { + co_await answer(connection, + exchange->readFailure.has_value() ? errorStatusFor(*exchange->readFailure) + : std::optional { internalErrorRow() }); + co_return Next::Close; + } + auto response = std::move(*result); + // A 1xx is no final response, and a status past 999 fits no status line: either is the + // handler's failure, answered 500. + if (response.head.status < 200 || response.head.status > 999) + { + co_await answer(connection, internalErrorRow()); + co_return Next::Close; + } + + // Unread, with the client maybe waiting for the `100 Continue` it never got, the body may or + // may not follow: nothing can tell its bytes from the next request's. + auto persistence = + last == LastRequest::Yes || framing->persistence == Persistence::Close || continueUnsent + ? Persistence::Close + : Persistence::KeepAlive; + // The handler is done with the body: drain it now, so the response can say whether it closes. + if (persistence == Persistence::KeepAlive && !connection->hasLiveBodyReader()) + { + auto const drained = co_await drain( + exchange, connection, *framing, options->maxDrainBytes, options->limits.maxReadChunk); + if (drained == Drained::Close) + persistence = Persistence::Close; + } + + auto replyFraming = framingFor(response.body.get()); + replyFraming.persistence = persistence; + auto* source = response.body.get(); + auto trailerless = std::optional {}; + if (version == HttpVersion::Http10 && replyFraming.kind == BodyFraming::Chunked) + { + replyFraming.kind = BodyFraming::UntilClose; // HTTP/1.0 has no chunked coding + source = &trailerless.emplace(source); + } + if (auto wrote = co_await connection->writeResponseHead(std::move(response.head), replyFraming); + !wrote.has_value()) + { + // Refused before the first wire byte (a framing field of the handler's), the connection is + // as it was and takes the 500; failed after it, the write side refuses this one too. + co_await answer(connection, internalErrorRow()); + co_return Next::Close; + } + // The head is out: a failed or throwing body has nothing but the close to say it failed. + if (auto wrote = co_await guarded( + [connection, source, replyFraming]() { return connection->writeBody(source, replyFraming); }, + "the response body"); + !wrote.has_value()) + co_return Next::Close; + trailerless.reset(); + response.body.reset(); // a source streaming the request body holds its reader + + if (persistence == Persistence::Close || connection->hasLiveBodyReader()) + co_return Next::Close; + auto const drained = co_await drain( + exchange, connection, *framing, options->maxDrainBytes, options->limits.maxReadChunk); + if (drained == Drained::Close) + co_return Next::Close; + co_return connection->reusable() == Reuse::Yes ? Next::Another : Next::Close; + } + + /// Ends @p exchange before its connection is closed: no read reaches the connection after this, + /// and one still parked is retired and has returned, so the close's own reads do not meet it. A + /// read writing the interim response cannot be retired: the connection is closed under it. + async::Task settle(std::shared_ptr exchange, Connection* connection) + { + exchange->sever(); + if (exchange->expect == Continue::Sending) + { + connection->close(); + co_return; + } + if (exchange->readsInFlight == 0) + co_return; + connection->socket().cancelRead(); + while (exchange->readsInFlight > 0) + if (!(co_await exchange->returned.pop()).has_value()) + co_return; + } + + /// Severs the exchange it holds when the connection's flow ends or is destroyed. + class Severing + { + public: + Severing() = default; + ~Severing() + { + if (current != nullptr) + current->sever(); + } + Severing(Severing const&) = delete; + Severing& operator=(Severing const&) = delete; + Severing(Severing&&) = delete; + Severing& operator=(Severing&&) = delete; + + std::shared_ptr current; ///< The exchange of the request being served, or the last. + }; + + // --------------------------------------------------------------------------------------------- + // The accept loop's side: admission, and the report of a refusal. + + /// Reports connections closed at the admission cap: the first, then at most one a second, with + /// how many were closed since, so a flood is visible without a line per connection. + class CapReporter + { + public: + CapReporter(net::EventLoop* loop, net::AcceptLoopReporting const* reporting): + _loop { loop }, _reporting { reporting } + { + } + + /// One connection was closed at the cap. + void refused() + { + ++_unreported; + auto const now = _loop->clock().now(); + if (_last.has_value() && now - *_last < 1s) + return; + _last = now; + net::reportAcceptLoopEvent( + *_reporting, + net::AcceptLoopEvent { + .surface = _reporting->surface, + .line = std::format("{}: {} connection(s) past the admission cap closed unanswered", + _reporting->surface, + std::exchange(_unreported, 0)), + .error = net::makeNetError(net::NetErrorCode::ResourceExhausted, 0, "admission cap"), + .kind = net::AcceptLoopEventKind::Warning }); + } + + private: + net::EventLoop* _loop; + net::AcceptLoopReporting const* _reporting; + std::optional _last; + std::uint64_t _unreported = 0; + }; + + /// A connection's hold on its server's admission policy; the lease ends before the policy goes. + struct Admission + { + std::shared_ptr policy; + std::optional lease; + }; + + async::Task serveAdmitted(net::EventLoop* loop, + std::unique_ptr socket, + IHttpHandler* handler, + HttpServerOptions options, + Admission admission) + { + auto const held = std::move(admission); + co_await serveHttpConnection(loop, std::move(socket), handler, std::move(options)); + } + + /// The flow of a connection not admitted: nothing, once its socket is closed. + async::Task refusedConnection() + { + co_return; + } + +} // namespace + +std::span errorStatusTable() noexcept +{ + return ErrorStatusRows; +} + +std::optional errorStatusFor(HttpError const& error) noexcept +{ + if (std::ranges::any_of(UnansweredRows, [&](UnansweredRow const& row) { + return row.code == error.code && row.reason == error.reason; + })) + return std::nullopt; + auto const matches = [&](RefusalReason reason) { + return std::ranges::find_if(ErrorStatusRows, [&](ErrorStatusRow const& row) { + return row.code == error.code && row.reason == reason; + }); + }; + if (auto const exact = matches(error.reason); exact != ErrorStatusRows.end()) + return *exact; + if (auto const fallback = matches(RefusalReason::Unclassified); fallback != ErrorStatusRows.end()) + return *fallback; + return std::nullopt; +} + +std::string_view statusPhrase(std::uint16_t status) noexcept +{ + auto const found = std::ranges::find(StatusPhrases, status, &StatusPhrase::status); + return found != StatusPhrases.end() ? found->phrase : std::string_view {}; +} + +async::Task serveHttpConnection(net::EventLoop* loop, + std::unique_ptr socket, + IHttpHandler* handler, + HttpServerOptions options) +{ + { + // A transport that negotiates (TLS) finishes before the first request byte; a client that + // never finishes the handshake is held to the head's bound, and one that fails it is dropped. + auto target = net::SocketDeadlineTarget { .socket = socket.get(), .expired = false }; + auto const deadline = net::armSocketDeadline(loop, options.headTimeout, &target); + if (auto const handshaken = co_await socket->handshakeIfNeeded(); !handshaken.has_value()) + co_return; + } + auto const remote = socket->remoteEndpoint(); + auto const peer = remote.has_value() ? std::optional { *remote } : std::nullopt; + auto connection = Connection { *loop, + std::move(socket), + MessageRole::Request, + options.limits, + WireTimeouts { .firstByte = options.idleTimeout, + .betweenBytes = options.bodyBetweenBytes, + .write = options.writeTimeout, + .head = options.headTimeout, + .body = options.bodyTotal } }; + auto severing = Severing {}; + auto served = std::size_t { 0 }; + auto next = Next::Another; + while (next == Next::Another) + { + ++served; + auto const last = options.maxRequestsPerConnection != 0 && served >= options.maxRequestsPerConnection + ? LastRequest::Yes + : LastRequest::No; + if (severing.current != nullptr) + severing.current->sever(); // the last request's reader is gone: it has nothing in flight + next = co_await serveOne(loop, &connection, handler, &options, peer, last, &severing.current); + } + if (severing.current != nullptr) + co_await settle(severing.current, &connection); + std::ignore = co_await net::closeLingering(&connection.socket(), loop, options.linger); +} + +async::Task serveHttp(net::EventLoop* loop, + net::IListener* listener, + IHttpHandler* handler, + HttpServerOptions options) +{ + // `options` and the reporter live in this frame for as long as the accept loop runs, and each + // spawned connection takes a copy of the options of its own. + auto reporter = CapReporter { loop, &options.reporting }; + co_await net::acceptLoop( + loop, + listener, + options.reporting, + net::ConnectionFlow::Spawned, + [loop, handler, serving = &options, capped = &reporter](std::unique_ptr socket) { + auto admission = Admission { .policy = serving->admission, .lease = std::nullopt }; + if (admission.policy != nullptr) + { + admission.lease = admission.policy->tryAdmit(); + if (!admission.lease.has_value()) + { + socket.reset(); // past the cap: closed unanswered + capped->refused(); + return refusedConnection(); + } + } + return serveAdmitted(loop, std::move(socket), handler, *serving, std::move(admission)); + }); +} + +} // namespace core::http diff --git a/src/core/http/HttpServer.hpp b/src/core/http/HttpServer.hpp new file mode 100644 index 00000000..4ea3aa35 --- /dev/null +++ b/src/core/http/HttpServer.hpp @@ -0,0 +1,213 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// The keep-alive HTTP/1.1 server: an accept loop that serves each connection in a flow of its own, +/// and the per-connection exchange of request heads, streamed bodies and responses over a +/// @c Connection in the request role. The handler is an interface, one request in and one response +/// out, so `wasi:http/handler#handle` maps onto it one to one. Refusals map to a status through one +/// table (@c errorStatusTable). + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace core::http +{ + +/// One request as a handler receives it. +struct IncomingRequest +{ + RequestHead head; ///< The request head, as read. + /// The body, streamed from the connection; a body of none reads as one empty @c BodyEnd::Reached + /// chunk. With `Expect: 100-continue` the first @c IBodyReader::read sends the interim + /// `100 Continue`. **The connection's next request waits for this reader to be destroyed**: a + /// reader still alive once the response is written closes the connection, a read of it still + /// parked then is retired first (it answers @c HttpErrorCode::ConnectionTerminated), and every read + /// after that is refused the same way, since the request is over. + std::unique_ptr body; + std::optional peer; ///< The client's address, where the socket knows one. +}; + +/// One response as a handler produces it. +struct OutgoingResponse +{ + /// The final head: a status from 200 to 599, and no framing field (@c isFramingField), which the + /// connection writes itself. A 1xx, or a head the connection refuses, is answered 500 instead. + ResponseHead head; + /// The body, or null for none; its shape picks the framing (@c framingFor). It may stream the + /// request body into the response: the server writes it before it reads anything more. + std::unique_ptr body; +}; + +/// What a server calls once per request. +class IHttpHandler +{ + public: + IHttpHandler() = default; + virtual ~IHttpHandler() = default; + IHttpHandler(IHttpHandler const&) = delete; + IHttpHandler& operator=(IHttpHandler const&) = delete; + IHttpHandler(IHttpHandler&&) = delete; + IHttpHandler& operator=(IHttpHandler&&) = delete; + + /// Answers one request. Called on the server's loop, for one request of a connection at a time. + /// @param request The request; its body is the handler's to read, or to leave. + /// @return The response, or a failure: the server answers a failure, and an exception, with 500 + /// and closes -- unless the failure came from reading the request body, which is then + /// answered with that refusal's status (@c errorStatusTable), or not at all where it has + /// none (the client went away). + [[nodiscard]] virtual async::Task> handle(IncomingRequest request) = 0; +}; + +/// The limits a server holds each request to by default: @c HttpLimits with the body bounded to +/// 64 MiB, since a server's peer is untrusted and an unbounded body is the one limit the pure +/// layer leaves open. +/// @return The limits. +[[nodiscard]] inline HttpLimits defaultServerLimits() +{ + return HttpLimits { .maxBodyBytes = std::uint64_t { 64 } * 1024 * 1024 }; +} + +/// How a server serves its connections, fixed when it starts. +/// +/// **Every wait on a client is bounded by default**, because a client that sends or reads slowly +/// holds a connection, and so a slot of @c maxConnections, for as long as it is let: a head by +/// @c headTimeout, the wait for one by @c idleTimeout, a body by @c bodyBetweenBytes and +/// @c bodyTotal, and every write by @c writeTimeout. Zero turns that bound off. +struct HttpServerOptions +{ + /// The bounds of every request read: head, field and trailer sizes, and the body. + HttpLimits limits = defaultServerLimits(); + /// A request head, from its first byte to its last (@c WireTimeouts::head); past it the answer is + /// 408. The wait for that first byte is @c idleTimeout's, a separate budget: a keep-alive client + /// that idles almost to @c idleTimeout still has all of this for its head. + std::chrono::milliseconds headTimeout { 10'000 }; + /// The wait for a request's first byte, on a new connection and between requests; past it the + /// connection closes without an answer, as an idle one (RFC 9112 section 9.5). + std::chrono::milliseconds idleTimeout { 5'000 }; + /// Between any two reads after a head's first byte, a body's included (a slowloris trickle). + std::chrono::milliseconds bodyBetweenBytes { 10'000 }; + /// A request body as a whole, from the end of its head to its last byte, the server's drain of it + /// included. + std::chrono::milliseconds bodyTotal { 60'000 }; + /// Each write to the client, a head's or a body chunk's; a client that stops reading is closed + /// past it. + std::chrono::milliseconds writeTimeout { 30'000 }; + /// The requests one connection serves; the last is answered with `Connection: close`. + std::size_t maxRequestsPerConnection = 1000; + /// How many connections @c serveHttp serves at once: one it does not admit is closed unanswered, + /// and reported (rate-limited) as an @c net::AcceptLoopEventKind::Warning. 512 by default; null is + /// no cap. **Shared by every copy of these options**, so servers started from one copy share one + /// cap; give each its own policy for a cap each. + std::shared_ptr admission = std::make_shared(512); + /// The most of a request body the server reads and discards so the connection can carry the next + /// request, when the handler left it unread; a longer one closes the connection instead. + std::uint64_t maxDrainBytes = std::uint64_t { 64 } * 1024; + /// How a connection is closed: half-closed, then listened to within these bounds (as + /// @c net::HttpLimits::linger, R30), so an answer is not destroyed by a reset. + net::LingerBounds linger { .total = std::chrono::milliseconds { 250 }, + .maxBytes = std::size_t { 64 } * 1024, + .reads = 4 }; + /// Where the accept loop reports what @c net::AcceptErrorPolicy decided. + net::AcceptLoopReporting reporting {}; +}; + +/// One row of @c errorStatusTable: the status a refusal is answered with. +struct ErrorStatusRow +{ + HttpErrorCode code; ///< The refusal's code. + RefusalReason reason; ///< Its reason; @c RefusalReason::Unclassified is the code's default row. + std::uint16_t status; ///< The status that answers it. +}; + +/// The statuses a server answers a refused request with: 400, 408, 411, 413, 414, 431, 501, 505, +/// and 500 for an internal failure. A code without a row -- the client closing, a write failing -- +/// is not answered: the connection closes. Neither is a read timeout before any byte of a request +/// (@c RefusalReason::NothingArrived), which is an idle connection, not a slow request. +/// @return The rows; a code's rows are looked up by reason first, then as Unclassified. +[[nodiscard]] CORE_HTTP_API std::span errorStatusTable() noexcept; + +/// The row of @c errorStatusTable that answers @p error. +/// @param error A refusal of a request. +/// @return The row for its code and reason, else for its code, else none. +[[nodiscard]] CORE_HTTP_API std::optional errorStatusFor(HttpError const& error) noexcept; + +/// The reason phrase of a status this server writes itself (RFC 9110 section 15): `100 Continue` and +/// every status of @c errorStatusTable. +/// @param status A status code. +/// @return Its phrase, or empty for a status the server never writes. +[[nodiscard]] CORE_HTTP_API std::string_view statusPhrase(std::uint16_t status) noexcept; + +/// Serves connections from @p listener until it is closed, each in a flow of its own on @p loop. +/// +/// The accept loop is @c net::serve's (@c net::acceptLoop): a failed accept is answered by @c +/// net::AcceptErrorPolicy, reported through @c HttpServerOptions::reporting, and only a closed or dead +/// listener (or the flow's own cancellation) ends it. Each accepted socket is handed to @c +/// serveHttpConnection in a flow @c EventLoop::spawn starts, so a slow client holds its own connection and +/// nothing else; one +/// @c HttpServerOptions::admission does not admit is closed at once. +/// +/// **Connections outlive the loop that accepted them**: closing the listener ends the accept loop, +/// not the connections it started, which end with their client, their deadlines, or the loop. +/// @param loop The loop the listener and every connection run on (not owned; outlives every +/// connection). +/// @param listener The bound listener (not owned); alive when the flow is first resumed. Its owner +/// may close and destroy it afterwards, as with @c net::serve. +/// @param handler The handler (not owned; outlives every connection). +/// @param options The configuration. +/// @return A task that completes when the accept loop ends. +[[nodiscard]] CORE_HTTP_API async::Task serveHttp(net::EventLoop* loop, + net::IListener* listener, + IHttpHandler* handler, + HttpServerOptions options = {}); + +/// Serves one connection: request after request, until either end closes it. +/// +/// Per request: the wait for the head's first byte, held to @c HttpServerOptions::idleTimeout; the +/// head from that byte on, held to @c headTimeout; its framing (@c requestFraming); the handler; the +/// response, framed by @c framingFor; then, once the handler's body reader is destroyed, a drain of +/// what it left unread, up to @c maxDrainBytes. A refused head or framing is answered by +/// @c errorStatusTable without calling the handler, and the connection closes. Every close is +/// lingering (@c net::closeLingering). +/// +/// **Pipelined requests are served in order, one at a time**: request N+1 is read only once +/// response N is written in full, as @c Connection's request role requires, so a client that sends +/// several at once gets their answers in order and the handler never sees two of one connection at +/// a time. HTTP/1.1 permits this (RFC 9112 section 9.3.2), and a WASI handler serves one request per +/// connection at a time. +/// +/// **The connection closes, with `Connection: close` where the response can still say so**, after: +/// a request that asked for it, or HTTP/1.0 without keep-alive; the @c maxRequestsPerConnection-th +/// request; a body longer than @c maxDrainBytes left unread; `Expect: 100-continue` answered without +/// the handler reading (the client may or may not send the body); a body reader still alive when the +/// response is written; and any failure. +/// @param loop The loop the socket runs on (not owned; outlives the flow). +/// @param socket The accepted socket, owned from now on; its handshake is awaited first, within +/// @c headTimeout. +/// @param handler The handler (not owned; outlives the flow). +/// @param options The configuration; @c reporting and @c admission are the accept loop's. +/// @return A task that completes once the connection is closed. +[[nodiscard]] CORE_HTTP_API async::Task serveHttpConnection(net::EventLoop* loop, + std::unique_ptr socket, + IHttpHandler* handler, + HttpServerOptions options); + +} // namespace core::http diff --git a/src/core/http/HttpServerLoopback_test.cpp b/src/core/http/HttpServerLoopback_test.cpp new file mode 100644 index 00000000..04a260ce --- /dev/null +++ b/src/core/http/HttpServerLoopback_test.cpp @@ -0,0 +1,418 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The server over real sockets: one request and response between `serveHttp` and `HttpClient` on +// the default backend, and the deadlines that bound a slow client on every backend this platform +// builds -- one that never reads (the write deadline), and ones that send slowly (the head, idle, +// between-bytes and whole-body deadlines). Every case bounds its flow with a watchdog, so a deadline +// that never fires fails the case in seconds instead of hanging it. +#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 + +using core::async::Task; +using core::http::BufferBodySource; +using core::http::HttpResult; +using core::http::HttpServerOptions; +using core::http::IHttpHandler; +using core::http::IncomingRequest; +using core::http::OutgoingResponse; +using core::http::ResponseHead; +using core::http::test::EchoHandler; +using core::http::test::parseResponses; +using core::http::test::textOf; +using core::net::EventLoop; +using core::net::ISocket; +using core::net::testing::BackendMatrix; + +using namespace std::chrono_literals; + +namespace +{ + +/// The watchdog over each case's flow: two orders of magnitude over the deadlines below. +constexpr auto Watchdog = 10s; + +/// Long enough that a loaded runner does not deliver what the case never sent first. +constexpr auto Deadline = 50ms; + +/// The kernel buffers each end of a pair is asked for, so a little data fills them. +constexpr auto SmallBuffer = std::uint64_t { 4096 }; + +/// Many times what two `SmallBuffer`-sized kernel buffers hold, so a client that does not read stalls +/// the server's write. +constexpr auto Flood = std::size_t { 4 } * 1024 * 1024; + +/// Every deadline off, so a case turns on only the one it is about. +HttpServerOptions quietOptions() +{ + auto options = HttpServerOptions {}; + options.headTimeout = 0ms; + options.idleTimeout = 0ms; + options.bodyBetweenBytes = 0ms; + options.bodyTotal = 0ms; + options.writeTimeout = 0ms; + return options; +} + +/// Answers every request with a body of `Flood` bytes. +class FloodHandler final: public IHttpHandler +{ + public: + [[nodiscard]] Task> handle(IncomingRequest request) override + { + static_cast(request); + return answer(); + } + + private: + static Task> answer() + { + co_return OutgoingResponse { .head = ResponseHead {}, + .body = std::make_unique(std::string(Flood, 'f')) }; + } +}; + +/// The two ends of one case: a loop on a backend, and a real connected pair. +struct Ends +{ + std::unique_ptr backend; + std::unique_ptr loop; + std::unique_ptr server; + std::unique_ptr client; +}; + +/// @return The ends, or nothing where @p kind does not build here. +std::optional endsOn(core::net::BackendKind kind) +{ + auto backend = core::net::makeBackend(kind); + if (!backend) + return std::nullopt; + auto loop = std::make_unique(*backend); + auto pair = core::net::testing::makeSocketPair(*loop); + REQUIRE(pair.has_value()); + // Best effort: a transport without the options keeps its defaults, and the flood still exceeds + // them on every native kernel. + std::ignore = pair->first->setOption(core::net::SocketOption::SendBufferSize, SmallBuffer); + std::ignore = pair->second->setOption(core::net::SocketOption::ReceiveBufferSize, SmallBuffer); + return Ends { .backend = std::move(backend), + .loop = std::move(loop), + .server = std::move(pair->first), + .client = std::move(pair->second) }; +} + +/// Writes @p text to @p socket in full. +Task send(ISocket* socket, std::string text) +{ + if (!text.empty()) + static_cast(co_await socket->write(core::http::test::bytesOf(text))); +} + +/// Writes @p text one byte every @p gap, stopping at the first failed write. +Task trickle(EventLoop* loop, ISocket* socket, std::string text, std::chrono::milliseconds gap) +{ + for (auto const octet: text) + { + co_await loop->delay(gap); + auto const one = std::string(1, octet); + if (!(co_await socket->write(core::http::test::bytesOf(one))).has_value()) + co_return; + } +} + +/// Reads @p socket until EOF or an error, within @p limit. +/// @return What the server wrote before it closed, or nothing if it had not closed by @p limit. +Task> readUntilClosedWithin(EventLoop* loop, + ISocket* socket, + std::chrono::milliseconds limit) +{ + auto text = std::string {}; + auto collect = [](ISocket* from, std::string* out) -> Task { + auto buffer = std::vector(4096); + while (true) + { + auto const got = co_await from->read(std::span { buffer }); + if (!got.has_value() || *got == 0) + co_return; + *out += textOf(std::span { buffer }.first(*got)); + } + }; + if (!co_await core::net::withTimeout(loop, collect(socket, &text), limit)) + co_return std::nullopt; + co_return text; +} + +/// Serves @p ends' server end with @p handler while the client sends @p prefix, then @p rest +/// trickled a byte every @p gap; the client's answer lands in @p out. +Task serveSlowSender(Ends* ends, + IHttpHandler* handler, + HttpServerOptions options, + std::string prefix, + std::string rest, + std::chrono::milliseconds gap, + std::optional>* out) +{ + auto served = + core::http::serveHttpConnection(ends->loop.get(), std::move(ends->server), handler, options); + auto client = [](Ends* both, + std::string first, + std::string slow, + std::chrono::milliseconds pause, + std::optional>* answer) -> Task { + co_await send(both->client.get(), std::move(first)); + co_await core::async::whenAll( + trickle(both->loop.get(), both->client.get(), std::move(slow), pause), + core::http::test::into(readUntilClosedWithin(both->loop.get(), both->client.get(), Watchdog / 2), + answer)); + }; + co_await core::async::whenAll(std::move(served), + client(ends, std::move(prefix), std::move(rest), gap, out)); +} + +/// Whether @p kind builds on this platform; a case skips the backends that do not. +bool buildsHere(core::net::BackendKind kind) +{ + return core::net::makeBackend(kind) != nullptr; +} + +/// Runs @p task under the watchdog and REQUIREs it finished. +void runBounded(EventLoop& loop, Task task) +{ + auto const finished = core::net::testing::blockOnWithin(loop, std::move(task), Watchdog); + REQUIRE(finished); +} + +/// The status of the first response in @p wire, or zero for none. +std::uint16_t firstStatus(std::string_view wire) +{ + auto const responses = parseResponses(wire); + return responses.empty() ? std::uint16_t { 0 } : responses.front().head.status; +} + +/// Sends @p request with @p client and reads the body to its end. +Task> fetch(core::http::HttpClient* client, core::http::OutgoingRequest request) +{ + auto response = co_await client->send(std::move(request)); + if (!response.has_value()) + co_return std::unexpected(std::move(response.error())); + auto body = co_await core::http::test::readAll(response->body.get(), 4096); + if (body.error.has_value()) + co_return std::unexpected(std::move(*body.error)); + co_return std::move(body.text); +} + +} // namespace + +TEST_CASE("HttpServerLoopback.aClientRoundTripOnTheDefaultBackend", "[http][server][loopback]") +{ + auto backend = core::net::makeDefaultBackend(); + REQUIRE(backend != nullptr); + auto loop = EventLoop { *backend }; + auto listener = core::net::listen(loop, "127.0.0.1", 0); + if (!listener.has_value()) + SKIP("no loopback listener here: " << listener.error().toString()); + auto connector = core::net::makeConnector(loop, core::net::defaultAsyncResolver()); + auto handler = EchoHandler {}; + auto const port = (*listener)->boundPort(); + auto first = std::optional> {}; + auto second = std::optional> {}; + { + auto client = core::http::HttpClient { loop, *connector, nullptr }; + auto const url = "http://127.0.0.1:" + std::to_string(port); + auto exchangeTwice = [](core::http::HttpClient* http, + std::string base, + core::net::IListener* accepting, + std::optional>* one, + std::optional>* two) -> Task { + *one = co_await fetch(http, core::http::test::get(base + "/one")); + *two = co_await fetch(http, core::http::test::get(base + "/two")); // over the pooled connection + accepting->close(); + }; + loop.spawn(core::http::serveHttp(&loop, listener->get(), &handler)); + runBounded(loop, exchangeTwice(&client, url, listener->get(), &first, &second)); + } + REQUIRE(first.has_value()); + REQUIRE(first->has_value()); + REQUIRE(second.has_value()); + REQUIRE(second->has_value()); + CHECK(handler.calls() == 2); +} + +TEST_CASE("HttpServerLoopback.aClientThatNeverReadsMeetsTheWriteDeadline", "[http][server][loopback]") +{ + for (auto const& backend: BackendMatrix) + { + if (!buildsHere(backend.kind)) + continue; + DYNAMIC_SECTION("backend=" << backend.name) + { + auto ends = endsOn(backend.kind); + REQUIRE(ends.has_value()); + auto options = quietOptions(); + options.writeTimeout = Deadline; + auto handler = FloodHandler {}; + auto request = std::string { "GET / HTTP/1.1\r\nHost: a\r\n\r\n" }; + auto served = [](Ends* both, + IHttpHandler* serving, + HttpServerOptions with, + std::string wire) -> Task { + co_await send(both->client.get(), std::move(wire)); // and then never read + co_await core::http::serveHttpConnection( + both->loop.get(), std::move(both->server), serving, with); + }; + auto const finished = core::net::testing::blockOnWithin( + *ends->loop, served(&*ends, &handler, options, std::move(request)), Watchdog); + if (!finished && core::http::test::loopbackFlood() == core::http::test::LoopbackFlood::Absorbed) + SKIP("Windows' loopback, natively and under wine, takes the whole flood however small " + "SO_SNDBUF/SO_RCVBUF are, so no write stalls there, and the connection waits for its " + "next request"); + CHECK(finished); + } + } +} + +TEST_CASE("HttpServerLoopback.aClientThatSendsSlowlyMeetsTheReadDeadlines", "[http][server][loopback]") +{ + struct Row + { + std::string_view name; + std::string_view prefix; ///< Sent at once. + std::string_view rest; ///< Trickled. + std::chrono::milliseconds gap; + void (*configure)(HttpServerOptions&); + std::uint16_t status; ///< What the client is answered; zero for a close without an answer. + }; + auto const rows = std::array { + Row { "a head that never finishes, by headTimeout", + "GET / HTTP/1.1\r\nHo", + "", + 0ms, + [](HttpServerOptions& options) { options.headTimeout = Deadline; }, + 408 }, + Row { "a head that trickles within bodyBetweenBytes, by headTimeout", + "GET / HTTP/1.1\r\nHost: a\r\nX-Slow: ", + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + 20ms, + [](HttpServerOptions& options) { + options.bodyBetweenBytes = Deadline * 4; + options.headTimeout = Deadline * 2; + }, + 408 }, + Row { "no byte at all, closed silently by idleTimeout", + "", + "", + 0ms, + [](HttpServerOptions& options) { options.idleTimeout = Deadline; }, + 0 }, + Row { "a body that stops, by bodyBetweenBytes", + "POST / HTTP/1.1\r\nHost: a\r\nContent-Length: 5\r\n\r\na", + "", + 0ms, + [](HttpServerOptions& options) { options.bodyBetweenBytes = Deadline; }, + 408 }, + Row { "a body that trickles within bodyBetweenBytes, by bodyTotal", + "POST / HTTP/1.1\r\nHost: a\r\nContent-Length: 50\r\n\r\n", + "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + 20ms, + [](HttpServerOptions& options) { + options.bodyBetweenBytes = Deadline * 4; + options.bodyTotal = Deadline * 2; + }, + 408 }, + }; + for (auto const& backend: BackendMatrix) + { + if (!buildsHere(backend.kind)) + continue; + for (auto const& row: rows) + { + DYNAMIC_SECTION("backend=" << backend.name << " " << row.name) + { + auto ends = endsOn(backend.kind); + REQUIRE(ends.has_value()); + auto options = quietOptions(); + row.configure(options); + auto handler = EchoHandler {}; + auto answer = std::optional> {}; + runBounded(*ends->loop, + serveSlowSender(&*ends, + &handler, + options, + std::string { row.prefix }, + std::string { row.rest }, + row.gap, + &answer)); + REQUIRE(answer.has_value()); + REQUIRE(answer->has_value()); // the server closed + CHECK(firstStatus(**answer) == row.status); + if (row.status == 0) + CHECK((*answer)->empty()); + } + } + } +} + +TEST_CASE("HttpServerLoopback.aBodyReadLeftRunningNeverMeetsTheClose", "[http][server][loopback]") +{ + // The handler answers once its own read has parked on a body the client never finishes; the + // server closes with that read retired first, on every backend, and the close's reads meet none. + for (auto const& backend: BackendMatrix) + { + if (!buildsHere(backend.kind)) + continue; + DYNAMIC_SECTION("backend=" << backend.name) + { + auto left = core::http::test::LeftRunning {}; + auto* loop = static_cast(nullptr); + auto handler = core::http::test::SpawningReader { &loop, &left, Deadline }; + auto ends = endsOn(backend.kind); + REQUIRE(ends.has_value()); + loop = ends->loop.get(); + auto answer = std::optional> {}; + runBounded(*ends->loop, + serveSlowSender(&*ends, + &handler, + quietOptions(), + "POST / HTTP/1.1\r\nHost: a\r\nContent-Length: 10\r\n\r\nabc", + "", + 0ms, + &answer)); + REQUIRE(answer.has_value()); + REQUIRE(answer->has_value()); + CHECK(firstStatus(**answer) == 200); + CHECK(left.text == "abc"); + CHECK(left.failure == core::http::HttpErrorCode::ConnectionTerminated); + CHECK(left.end == core::http::test::FlowEnd::Finished); + } + } +} diff --git a/src/core/http/HttpServer_test.cpp b/src/core/http/HttpServer_test.cpp new file mode 100644 index 00000000..2c2cf1cb --- /dev/null +++ b/src/core/http/HttpServer_test.cpp @@ -0,0 +1,1232 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// `serveHttp` and `serveHttpConnection` over in-memory pairs on a hand-driven loop: keep-alive with +// chunked bodies and trailers, the smuggling corpus answered with each row's exact status, the +// statuses of the refusal table, the drain of an unread body and when it closes instead, the head, +// idle and body deadlines, `Expect: 100-continue`, a handler's failures, and the accept loop's +// connection cap and accept policy. Every flow runs on a `TestLoop` over a `ManualClock`, so a deadline fires +// only when a case moves the clock, and a flow that never finishes leaves its answer empty instead of +// hanging. +#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 + +using core::async::Task; +using core::http::BodyChunk; +using core::http::BufferBodySource; +using core::http::errorStatusFor; +using core::http::errorStatusTable; +using core::http::Fields; +using core::http::HeadParser; +using core::http::HttpError; +using core::http::HttpErrorCode; +using core::http::HttpResult; +using core::http::HttpServerOptions; +using core::http::IBodySource; +using core::http::IHttpHandler; +using core::http::IncomingRequest; +using core::http::MessageRole; +using core::http::OutgoingResponse; +using core::http::Progress; +using core::http::RefusalReason; +using core::http::ResponseHead; +using core::http::TrailerIntent; +using core::http::test::EchoHandler; +using core::http::test::EchoMode; +using core::http::test::exchange; +using core::http::test::fieldOf; +using core::http::test::FlowEnd; +using core::http::test::IgnoringHandler; +using core::http::test::KeepsReader; +using core::http::test::parseResponses; +using core::http::test::ServedConnection; +using core::http::test::smugglingCorpus; +using core::http::test::smugglingLimits; +using core::http::test::SmugglingVerdict; + +using namespace std::chrono_literals; + +namespace +{ + +/// Every deadline off, so a case turns on only the one it is about. +HttpServerOptions quietOptions() +{ + auto options = HttpServerOptions {}; + options.headTimeout = 0ms; + options.idleTimeout = 0ms; + options.bodyBetweenBytes = 0ms; + options.bodyTotal = 0ms; + options.writeTimeout = 0ms; + return options; +} + +/// @return An error of @p code and @p reason, its payload empty. +HttpError errorOf(HttpErrorCode code, RefusalReason reason = RefusalReason::Unclassified) +{ + auto error = HttpError {}; + error.code = code; + error.reason = reason; + return error; +} + +/// Whether the pure layer refuses @p wire at its head or its framing, before any body byte. +bool refusedBeforeTheBody(std::string_view wire) +{ + auto parser = HeadParser { MessageRole::Request, smugglingLimits() }; + auto fed = parser.feed(wire); + if (!fed.has_value()) + return true; + if (fed->progress != Progress::Complete) + return false; + auto const head = parser.takeRequest(); + return !core::http::requestFraming(head.version, head.fields).has_value(); +} + +/// Answers each request after @p delay on the loop's clock, recording the order it was called in. +class SlowHandler final: public IHttpHandler +{ + public: + SlowHandler(core::net::EventLoop** loop, std::chrono::milliseconds delay): + _loop { loop }, _delay { delay } + { + } + + [[nodiscard]] Task> handle(IncomingRequest request) override + { + _targets.emplace_back(request.head.target.text()); + return answer(*_loop, _delay, std::string { request.head.target.text() }); + } + + [[nodiscard]] std::vector const& targets() const noexcept { return _targets; } + + private: + static Task> answer(core::net::EventLoop* loop, + std::chrono::milliseconds delay, + std::string target) + { + co_await loop->delay(delay); + co_return OutgoingResponse { .head = ResponseHead {}, + .body = std::make_unique(target) }; + } + + core::net::EventLoop** _loop; + std::chrono::milliseconds _delay; + std::vector _targets; +}; + +/// Reads the request body only after @p delay, then answers it as an echo. +class LateReader final: public IHttpHandler +{ + public: + LateReader(core::net::EventLoop** loop, std::chrono::milliseconds delay): _loop { loop }, _delay { delay } + { + } + + [[nodiscard]] Task> handle(IncomingRequest request) override + { + return answer(*_loop, _delay, std::move(request)); + } + + private: + static Task> answer(core::net::EventLoop* loop, + std::chrono::milliseconds delay, + IncomingRequest request) + { + co_await loop->delay(delay); + auto body = co_await core::http::test::readAll(request.body.get(), 1024); + if (body.error.has_value()) + co_return std::unexpected(std::move(*body.error)); + co_return OutgoingResponse { .head = ResponseHead {}, + .body = std::make_unique(std::move(body.text)) }; + } + + core::net::EventLoop** _loop; + std::chrono::milliseconds _delay; +}; + +/// How a @c FailingHandler fails. +enum class Failure : std::uint8_t +{ + Error, ///< It returns an error. + Exception, ///< It throws. + FramingField, ///< It answers with a framing field, which the connection refuses before the wire. + Interim, ///< It answers with a 1xx, which is no final response. + WideStatus, ///< It answers with a status of four digits, which no status line can carry. + BodySource, ///< Its body fails after the head is written. + BodyThrows, ///< Its body throws after the head is written. +}; + +/// A body whose first chunk fails. +class FailingSource final: public IBodySource +{ + public: + [[nodiscard]] std::optional knownLength() const noexcept override { return std::nullopt; } + [[nodiscard]] TrailerIntent trailerIntent() const noexcept override { return TrailerIntent::None; } + [[nodiscard]] Task> next() override { return fail(); } + [[nodiscard]] Task> trailers() override { return core::http::test::noTrailers(); } + + private: + static Task> fail() + { + co_return std::unexpected(errorOf(HttpErrorCode::InternalError)); + } +}; + +/// A body whose first chunk throws. +class ThrowingSource final: public IBodySource +{ + public: + [[nodiscard]] std::optional knownLength() const noexcept override { return std::nullopt; } + [[nodiscard]] TrailerIntent trailerIntent() const noexcept override { return TrailerIntent::None; } + [[nodiscard]] Task> next() override { return fail(); } + [[nodiscard]] Task> trailers() override { return core::http::test::noTrailers(); } + + private: + static Task> fail() + { + throw std::runtime_error { "the body threw" }; + co_return BodyChunk {}; // what makes this a coroutine, so the throw is the task's + } +}; + +class FailingHandler final: public IHttpHandler +{ + public: + explicit FailingHandler(Failure failure): _failure { failure } {} + + [[nodiscard]] Task> handle(IncomingRequest request) override + { + static_cast(request); + return answer(_failure); + } + + private: + static Task> answer(Failure failure) + { + auto head = ResponseHead {}; + switch (failure) + { + case Failure::Error: co_return std::unexpected(errorOf(HttpErrorCode::InternalError)); + case Failure::Exception: throw std::runtime_error { "the handler threw" }; + case Failure::FramingField: REQUIRE(head.fields.append("Content-Length", "2").has_value()); break; + case Failure::Interim: + // Bodiless, which the connection would write: only the server can tell it is no answer. + head.status = 103; + co_return OutgoingResponse { .head = std::move(head), .body = nullptr }; + case Failure::WideStatus: + head.status = 1000; + co_return OutgoingResponse { .head = std::move(head), .body = nullptr }; + case Failure::BodySource: + co_return OutgoingResponse { .head = std::move(head), + .body = std::make_unique() }; + case Failure::BodyThrows: + co_return OutgoingResponse { .head = std::move(head), + .body = std::make_unique() }; + } + co_return OutgoingResponse { .head = std::move(head), + .body = std::make_unique("ok") }; + } + + Failure _failure; +}; + +constexpr auto ChunkedUpload = std::string_view { "POST /up HTTP/1.1\r\n" + "Host: a\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n" + "3\r\nabc\r\n" + "2\r\nde\r\n" + "0\r\n" + "X-Sum: 5\r\n" + "\r\n" }; + +constexpr auto LengthUpload = std::string_view { "POST /up HTTP/1.1\r\n" + "Host: a\r\n" + "Content-Length: 10\r\n" + "\r\n" + "0123456789" }; + +constexpr auto ClosingGet = std::string_view { "GET /last HTTP/1.1\r\nHost: a\r\nConnection: close\r\n\r\n" }; + +/// @return `GET ` with a Host. +std::string get(std::string_view target) +{ + return "GET " + std::string { target } + " HTTP/1.1\r\nHost: a\r\n\r\n"; +} + +} // namespace + +TEST_CASE("HttpServer.errorStatusTable", "[http][server]") +{ + // An independent statement of every row, so a row changed, removed or added fails here. + struct Expected + { + HttpErrorCode code = HttpErrorCode::InternalError; + RefusalReason reason = RefusalReason::Unclassified; + std::optional status; + }; + constexpr auto Rows = std::array { + Expected { HttpErrorCode::ProtocolError, RefusalReason::Unclassified, std::uint16_t { 400 } }, + Expected { HttpErrorCode::ProtocolError, RefusalReason::UnsupportedVersion, std::uint16_t { 505 } }, + Expected { HttpErrorCode::ProtocolError, RefusalReason::UnimplementedCoding, std::uint16_t { 501 } }, + Expected { HttpErrorCode::RequestMethodInvalid, RefusalReason::Unclassified, std::uint16_t { 400 } }, + Expected { HttpErrorCode::RequestUriInvalid, RefusalReason::Unclassified, std::uint16_t { 400 } }, + Expected { HttpErrorCode::RequestUriTooLong, RefusalReason::Unclassified, std::uint16_t { 414 } }, + Expected { + HttpErrorCode::RequestHeaderSectionSize, RefusalReason::Unclassified, std::uint16_t { 431 } }, + Expected { HttpErrorCode::RequestHeaderSize, RefusalReason::Unclassified, std::uint16_t { 431 } }, + Expected { + HttpErrorCode::RequestTrailerSectionSize, RefusalReason::Unclassified, std::uint16_t { 431 } }, + Expected { HttpErrorCode::RequestTrailerSize, RefusalReason::Unclassified, std::uint16_t { 431 } }, + Expected { HttpErrorCode::RequestBodySize, RefusalReason::Unclassified, std::uint16_t { 413 } }, + Expected { HttpErrorCode::RequestLengthRequired, RefusalReason::Unclassified, std::uint16_t { 411 } }, + Expected { HttpErrorCode::ConnectionReadTimeout, RefusalReason::Unclassified, std::uint16_t { 408 } }, + Expected { HttpErrorCode::InternalError, RefusalReason::Unclassified, std::uint16_t { 500 } }, + // A reason without a row of its own falls back to its code's. + Expected { + HttpErrorCode::RequestUriTooLong, RefusalReason::UnsupportedVersion, std::uint16_t { 414 } }, + // A code without a row is not answered. + Expected { HttpErrorCode::ConnectionTerminated, RefusalReason::Unclassified, std::nullopt }, + Expected { HttpErrorCode::ConnectionWriteTimeout, RefusalReason::Unclassified, std::nullopt }, + Expected { HttpErrorCode::ResponseIncomplete, RefusalReason::Unclassified, std::nullopt }, + // An idle connection is closed, not answered: no byte of a request arrived. + Expected { HttpErrorCode::ConnectionReadTimeout, RefusalReason::NothingArrived, std::nullopt }, + }; + for (auto const& row: Rows) + { + INFO(core::http::toString(row.code) << " reason " << static_cast(row.reason)); + auto const found = errorStatusFor(errorOf(row.code, row.reason)); + REQUIRE(found.has_value() == row.status.has_value()); + if (found.has_value()) + CHECK(found->status == *row.status); + } + CHECK(errorStatusTable().size() == 14); +} + +TEST_CASE("HttpServer.statusPhrase", "[http][server]") +{ + struct Expected + { + std::uint16_t status = 0; + std::string_view phrase; + }; + constexpr auto Rows = std::array { + Expected { 100, "Continue" }, + Expected { 400, "Bad Request" }, + Expected { 408, "Request Timeout" }, + Expected { 411, "Length Required" }, + Expected { 413, "Content Too Large" }, + Expected { 414, "URI Too Long" }, + Expected { 431, "Request Header Fields Too Large" }, + Expected { 500, "Internal Server Error" }, + Expected { 501, "Not Implemented" }, + Expected { 505, "HTTP Version Not Supported" }, + Expected { 200, "" }, // never written by the server itself + Expected { 404, "" }, + }; + for (auto const& row: Rows) + { + INFO(row.status); + CHECK(core::http::statusPhrase(row.status) == row.phrase); + } + for (auto const& row: errorStatusTable()) + CHECK_FALSE(core::http::statusPhrase(row.status).empty()); +} + +TEST_CASE("HttpServer.keepAliveCarriesAChunkedUploadThenAClose", "[http][server]") +{ + auto handler = EchoHandler {}; + auto const answer = + exchange(handler, quietOptions(), std::string { ChunkedUpload } + std::string { ClosingGet }); + + auto const responses = parseResponses(answer.wire); + REQUIRE(responses.size() == 2); + CHECK(responses[0].head.status == 200); + CHECK(fieldOf(responses[0].head.fields, "X-Echo") == "POST /up"); + CHECK(fieldOf(responses[0].head.fields, "Transfer-Encoding") == "chunked"); // trailers need it + CHECK(responses[0].body == "abcde"); + CHECK(fieldOf(responses[0].trailers, "X-Sum") == "5"); + CHECK(fieldOf(responses[0].head.fields, "Connection").empty()); + CHECK(fieldOf(responses[1].head.fields, "X-Echo") == "GET /last"); + CHECK(fieldOf(responses[1].head.fields, "Connection") == "close"); + CHECK(handler.calls() == 2); + CHECK(answer.server == FlowEnd::Finished); + CHECK(answer.closed == FlowEnd::Finished); +} + +TEST_CASE("HttpServer.theWireEndsAfterAConnectionClose", "[http][server]") +{ + // The client never half-closes: only the server's close can end the wire. + auto handler = EchoHandler {}; + auto served = ServedConnection { handler, quietOptions() }; + served.send(std::string { ClosingGet } + get("/never")); + served.advance(HttpServerOptions {}.linger.total); + CHECK(parseResponses(served.received()).size() == 1); + CHECK(handler.calls() == 1); + CHECK(served.wire() == FlowEnd::Finished); + CHECK(served.server() == FlowEnd::Finished); +} + +TEST_CASE("HttpServer.pipelinedRequestsAreServedInOrderOneAtATime", "[http][server]") +{ + auto* loop = static_cast(nullptr); + auto handler = SlowHandler { &loop, 100ms }; + auto served = ServedConnection { handler, quietOptions() }; + loop = &served.loop(); + + served.send(get("/1") + get("/2") + get("/3")); + CHECK(handler.targets() == std::vector { "/1" }); // /2 waits for /1's answer + CHECK(served.received().empty()); + + served.advance(100ms); + CHECK(handler.targets() == std::vector { "/1", "/2" }); + CHECK(parseResponses(served.received()).size() == 1); + + served.advance(100ms); + served.advance(100ms); + auto const responses = parseResponses(served.received()); + REQUIRE(responses.size() == 3); + CHECK(responses[0].body == "/1"); + CHECK(responses[1].body == "/2"); + CHECK(responses[2].body == "/3"); +} + +TEST_CASE("HttpServer.everyCorpusRequestRowIsAnsweredWithItsStatus", "[http][server][smuggling]") +{ + auto rows = std::size_t { 0 }; + for (auto const& row: smugglingCorpus()) + { + if (row.role != MessageRole::Request) + continue; + ++rows; + DYNAMIC_SECTION(row.name) + { + auto options = quietOptions(); + options.limits = smugglingLimits(); + auto handler = EchoHandler {}; + auto const answer = exchange(handler, options, std::string { row.wire }); + auto const responses = parseResponses(answer.wire); + REQUIRE_FALSE(responses.empty()); + CHECK(responses.front().head.status == row.status); + CHECK(std::ranges::find(handler.targets(), "/smuggled") == handler.targets().end()); + if (row.verdict == SmugglingVerdict::Refused) + { + CHECK(responses.size() == 1); + CHECK(fieldOf(responses.front().head.fields, "Connection") == "close"); + CHECK(answer.closed == FlowEnd::Finished); + CHECK(answer.server == FlowEnd::Finished); + // A request smuggled in behind the refused one never reaches a handler. + auto smuggler = EchoHandler {}; + auto const smuggled = + exchange(smuggler, + options, + std::string { row.wire } + "GET /smuggled HTTP/1.1\r\nHost: a\r\n\r\n"); + CHECK(parseResponses(smuggled.wire).size() == 1); + CHECK(std::ranges::find(smuggler.targets(), "/smuggled") == smuggler.targets().end()); + if (refusedBeforeTheBody(row.wire)) + CHECK(handler.calls() == 0); + else + { + // A refused body reaches the handler only as its failed read. + CHECK(handler.calls() == 1); + CHECK(handler.readFailure() == row.code); + } + } + else + { + CHECK(handler.calls() == 1); + CHECK(responses.front().body == row.body); + } + } + } + CHECK(rows >= 50); +} + +TEST_CASE("HttpServer.anUnreadBodyIsDrainedWithinItsBound", "[http][server]") +{ + SECTION("within maxDrainBytes the connection carries the next request") + { + auto handler = IgnoringHandler {}; + auto const answer = exchange(handler, quietOptions(), std::string { LengthUpload } + get("/next")); + auto const responses = parseResponses(answer.wire); + REQUIRE(responses.size() == 2); + CHECK(fieldOf(responses[0].head.fields, "Connection").empty()); + CHECK(responses[1].body == "ok"); + CHECK(handler.calls() == 2); + } + SECTION("a chunked one too") + { + auto handler = IgnoringHandler {}; + auto const answer = exchange(handler, quietOptions(), std::string { ChunkedUpload } + get("/next")); + CHECK(parseResponses(answer.wire).size() == 2); + CHECK(handler.calls() == 2); + } + SECTION("exactly maxDrainBytes is within it") + { + auto options = quietOptions(); + options.maxDrainBytes = 10; + auto handler = IgnoringHandler {}; + auto const answer = exchange(handler, options, std::string { LengthUpload } + get("/next")); + CHECK(parseResponses(answer.wire).size() == 2); + } + SECTION("a known remainder past maxDrainBytes is not read at all") + { + // The body never comes: a drain that waited for it would answer nothing. + auto options = quietOptions(); + options.maxDrainBytes = 9; + auto handler = IgnoringHandler {}; + auto served = ServedConnection { handler, options }; + served.send("POST /up HTTP/1.1\r\nHost: a\r\nContent-Length: 10\r\n\r\n"); + auto const responses = parseResponses(served.received()); + REQUIRE(responses.size() == 1); + CHECK(fieldOf(responses[0].head.fields, "Connection") == "close"); + } + SECTION("past maxDrainBytes the response says close, and the wire ends") + { + auto options = quietOptions(); + options.maxDrainBytes = 9; + auto handler = IgnoringHandler {}; + auto served = ServedConnection { handler, options }; + served.send(std::string { LengthUpload } + get("/next")); + served.advance(options.linger.total); + auto const responses = parseResponses(served.received()); + REQUIRE(responses.size() == 1); + CHECK(fieldOf(responses[0].head.fields, "Connection") == "close"); + CHECK(handler.calls() == 1); + CHECK(served.wire() == FlowEnd::Finished); + } +} + +TEST_CASE("HttpServer.theDrainWaitsForTheHandlersReader", "[http][server]") +{ + SECTION("a handler streaming the body into its response is never raced by the drain") + { + auto handler = EchoHandler { EchoMode::Streamed }; + auto options = quietOptions(); + options.maxDrainBytes = 0; // any drain would close; none may happen + auto const answer = exchange(handler, options, std::string { LengthUpload } + get("/next")); + auto const responses = parseResponses(answer.wire); + REQUIRE(responses.size() == 2); + CHECK(responses[0].body == "0123456789"); + CHECK(fieldOf(responses[0].head.fields, "Connection").empty()); + CHECK(handler.calls() == 2); + } + SECTION("a reader still alive once the response is written closes the connection") + { + // The handler outlives the connection and its loop, and destroys the reader it kept after both: + // the reader must reach nothing of the request it belonged to. + auto handler = IgnoringHandler { KeepsReader::Yes }; + auto options = quietOptions(); + options.bodyTotal = 1000ms; + auto served = ServedConnection { handler, options }; + served.send(std::string { LengthUpload } + get("/next")); + served.advance(HttpServerOptions {}.linger.total); + CHECK(parseResponses(served.received()).size() == 1); + CHECK(handler.calls() == 1); + CHECK(served.wire() == FlowEnd::Finished); + } +} + +TEST_CASE("HttpServer.aStalledClientMeetsItsDeadline", "[http][server]") +{ + auto handler = EchoHandler {}; + SECTION("a head started and not finished is 408 after headTimeout") + { + auto options = quietOptions(); + options.headTimeout = 100ms; + auto served = ServedConnection { handler, options }; + served.send("GET / HTTP/1.1\r\nHo"); + served.advance(99ms); + CHECK(served.received().empty()); + served.advance(1ms); + auto const responses = parseResponses(served.received()); + REQUIRE(responses.size() == 1); + CHECK(responses[0].head.status == 408); + CHECK(fieldOf(responses[0].head.fields, "Connection") == "close"); + served.advance(options.linger.total); + CHECK(served.wire() == FlowEnd::Finished); + CHECK(handler.calls() == 0); + } + SECTION("no byte at all is closed silently after idleTimeout") + { + auto options = quietOptions(); + options.idleTimeout = 100ms; + auto served = ServedConnection { handler, options }; + served.advance(99ms); + CHECK(served.server() == FlowEnd::Running); + served.advance(1ms); + served.advance(options.linger.total); + CHECK(served.received().empty()); + CHECK(served.wire() == FlowEnd::Finished); + CHECK(served.server() == FlowEnd::Finished); + } + SECTION("the wait for a first byte is idleTimeout's alone, not headTimeout's") + { + auto options = quietOptions(); + options.idleTimeout = 1000ms; + options.headTimeout = 100ms; + auto served = ServedConnection { handler, options }; + served.advance(999ms); + served.send(get("/")); // well past headTimeout, inside idleTimeout: still served + auto const answered = parseResponses(served.received()); + REQUIRE(answered.size() == 1); + CHECK(answered[0].head.status == 200); + served.advance(1000ms); + served.advance(options.linger.total); + CHECK(parseResponses(served.received()).size() == 1); // the idle one is closed unanswered + CHECK(served.server() == FlowEnd::Finished); + } + SECTION("the head bound starts at the request's first byte, after an idle wait") + { + // Idle and head are separate budgets: a keep-alive client whose next request starts just + // inside idleTimeout still has the whole headTimeout for that head. + auto options = quietOptions(); + options.idleTimeout = 100ms; + options.headTimeout = 100ms; + auto served = ServedConnection { handler, options }; + served.send(get("/1")); + served.advance(90ms); // idle, inside idleTimeout + served.send("GET /2 HTTP/1.1\r\nHo"); + served.advance(90ms); // 180 ms after the idle read started, 90 ms into the head + CHECK(parseResponses(served.received()).size() == 1); + served.send("st: a\r\n\r\n"); + auto const answered = parseResponses(served.received()); + REQUIRE(answered.size() == 2); + CHECK(answered[1].head.status == 200); + served.advance(90ms); + served.send("GET /3 HTTP/1.1\r\nHo"); + served.advance(99ms); + CHECK(parseResponses(served.received()).size() == 2); + served.advance(1ms); // headTimeout after /3's first byte + auto const timedOut = parseResponses(served.received()); + REQUIRE(timedOut.size() == 3); + CHECK(timedOut[2].head.status == 408); + CHECK(handler.calls() == 2); + } + SECTION("the idle wait applies between requests too") + { + auto options = quietOptions(); + options.idleTimeout = 100ms; + auto served = ServedConnection { handler, options }; + served.send(get("/1")); + served.advance(99ms); + served.send(get("/2")); // the idle clock starts again after /1's answer + served.advance(99ms); + CHECK(parseResponses(served.received()).size() == 2); + served.advance(1ms); + served.advance(options.linger.total); + CHECK(parseResponses(served.received()).size() == 2); // the idle one is closed unanswered + CHECK(served.wire() == FlowEnd::Finished); + } + SECTION("a head that trickles within bodyBetweenBytes is 408 at headTimeout") + { + auto options = quietOptions(); + options.headTimeout = 300ms; + options.bodyBetweenBytes = 100ms; + auto served = ServedConnection { handler, options }; + for (auto const octet: std::string_view { "GET" }) // at 0, 90 and 180 ms + { + served.send(std::string(1, octet)); + served.advance(90ms); + } + served.send(" "); // at 270 ms, each byte inside bodyBetweenBytes + served.advance(29ms); + CHECK(served.received().empty()); + served.advance(1ms); + auto const responses = parseResponses(served.received()); + REQUIRE(responses.size() == 1); + CHECK(responses[0].head.status == 408); + CHECK(handler.calls() == 0); + } + SECTION("a body that trickles a byte per bodyBetweenBytes + 1 is closed") + { + auto options = quietOptions(); + options.bodyBetweenBytes = 100ms; + auto served = ServedConnection { handler, options }; + served.send("POST / HTTP/1.1\r\nHost: a\r\nContent-Length: 5\r\n\r\na"); + served.advance(101ms); + served.send("b"); + served.advance(options.linger.total); + auto const responses = parseResponses(served.received()); + REQUIRE(responses.size() == 1); + CHECK(responses[0].head.status == 408); + CHECK(handler.readFailure() == HttpErrorCode::ConnectionReadTimeout); + CHECK(served.wire() == FlowEnd::Finished); + } + SECTION("a body that trickles within bodyBetweenBytes but past bodyTotal is closed") + { + auto options = quietOptions(); + options.bodyBetweenBytes = 100ms; + options.bodyTotal = 300ms; + auto served = ServedConnection { handler, options }; + served.send("POST / HTTP/1.1\r\nHost: a\r\nContent-Length: 10\r\n\r\n"); + for ([[maybe_unused]] auto const step: std::array { 1, 2, 3 }) + { + served.advance(90ms); + served.send("x"); + } + CHECK(served.received().empty()); // 270 ms in + served.advance(30ms); + auto const responses = parseResponses(served.received()); + REQUIRE(responses.size() == 1); + CHECK(responses[0].head.status == 408); + CHECK(handler.readFailure() == HttpErrorCode::ConnectionReadTimeout); + } +} + +TEST_CASE("HttpServer.expectContinueIsAnsweredWhenTheHandlerFirstReads", "[http][server]") +{ + constexpr auto Head = std::string_view { "POST / HTTP/1.1\r\nHost: a\r\nExpect: 100-continue\r\n" + "Content-Length: 5\r\n\r\n" }; + SECTION("not before the read, then the interim response, then the final one") + { + auto* loop = static_cast(nullptr); + auto handler = LateReader { &loop, 50ms }; + auto served = ServedConnection { handler, quietOptions() }; + loop = &served.loop(); + served.send(std::string { Head }); + served.advance(49ms); + CHECK(served.received().empty()); + served.advance(1ms); + CHECK(served.received() == "HTTP/1.1 100 Continue\r\n\r\n"); + served.send("hello"); + auto const responses = parseResponses(served.received()); + REQUIRE(responses.size() == 2); + CHECK(responses[0].head.status == 100); + CHECK(responses[1].head.status == 200); + CHECK(responses[1].body == "hello"); + CHECK(fieldOf(responses[1].head.fields, "Connection").empty()); + } + SECTION("never, when the handler answers without reading; the connection then closes") + { + auto handler = IgnoringHandler {}; + auto served = ServedConnection { handler, quietOptions() }; + served.send(std::string { Head }); + served.advance(HttpServerOptions {}.linger.total); + auto const responses = parseResponses(served.received()); + REQUIRE(responses.size() == 1); + CHECK(responses[0].head.status == 200); + CHECK(fieldOf(responses[0].head.fields, "Connection") == "close"); + CHECK(served.wire() == FlowEnd::Finished); + } + SECTION("never for HTTP/1.0, which has no interim responses") + { + auto handler = EchoHandler {}; + auto const answer = + exchange(handler, + quietOptions(), + "POST / HTTP/1.0\r\nExpect: 100-continue\r\nContent-Length: 5\r\n\r\nhello"); + auto const responses = parseResponses(answer.wire); + REQUIRE(responses.size() == 1); + CHECK(responses[0].head.status == 200); + CHECK(responses[0].body == "hello"); + } +} + +TEST_CASE("HttpServer.aHandlersFailureIs500AndAClose", "[http][server]") +{ + struct Row + { + std::string_view name; + Failure failure; + }; + constexpr auto Rows = std::array { + Row { "an error", Failure::Error }, + Row { "an exception", Failure::Exception }, + Row { "a framing field in its head", Failure::FramingField }, + Row { "a 1xx as its final response", Failure::Interim }, + Row { "a status of four digits", Failure::WideStatus }, + }; + for (auto const& row: Rows) + { + DYNAMIC_SECTION(row.name) + { + auto handler = FailingHandler { row.failure }; + auto const answer = exchange(handler, quietOptions(), get("/") + get("/again")); + auto const responses = parseResponses(answer.wire); + REQUIRE(responses.size() == 1); + CHECK(responses[0].head.status == 500); + CHECK(fieldOf(responses[0].head.fields, "Connection") == "close"); + CHECK(answer.closed == FlowEnd::Finished); + } + } + SECTION("a body that throws after its head closes the connection, lingering") + { + auto handler = FailingHandler { Failure::BodyThrows }; + auto const answer = exchange(handler, quietOptions(), get("/") + get("/again")); + CHECK(answer.wire.starts_with("HTTP/1.1 200 \r\n")); + CHECK_FALSE(answer.wire.contains("500")); + CHECK(answer.closed == FlowEnd::Finished); + CHECK(answer.server == FlowEnd::Finished); // the throw ended no flow: it was the body's failure + } + SECTION("a body that fails after its head closes the connection unanswered") + { + auto handler = FailingHandler { Failure::BodySource }; + auto const answer = exchange(handler, quietOptions(), get("/") + get("/again")); + CHECK(answer.wire.starts_with("HTTP/1.1 200 \r\n")); // the handler left the reason empty + CHECK_FALSE(answer.wire.contains("500")); + CHECK(answer.closed == FlowEnd::Finished); + CHECK(answer.server == FlowEnd::Finished); + } +} + +TEST_CASE("HttpServer.theLastRequestOfAConnectionSaysClose", "[http][server]") +{ + auto options = quietOptions(); + options.maxRequestsPerConnection = 2; + auto handler = EchoHandler {}; + auto const answer = exchange(handler, options, get("/1") + get("/2") + get("/3")); + auto const responses = parseResponses(answer.wire); + REQUIRE(responses.size() == 2); + CHECK(fieldOf(responses[0].head.fields, "Connection").empty()); + CHECK(fieldOf(responses[1].head.fields, "Connection") == "close"); + CHECK(handler.calls() == 2); +} + +TEST_CASE("HttpServer.anHttp10RequestIsAnsweredInItsTerms", "[http][server]") +{ + SECTION("without keep-alive, the response closes") + { + auto handler = EchoHandler {}; + auto const answer = exchange(handler, quietOptions(), "GET / HTTP/1.0\r\n\r\n" + get("/never")); + auto const responses = parseResponses(answer.wire); + REQUIRE(responses.size() == 1); + CHECK(fieldOf(responses[0].head.fields, "Connection") == "close"); + CHECK(handler.calls() == 1); + } + SECTION("a streamed body is sent until close, since HTTP/1.0 has no chunked coding") + { + auto handler = EchoHandler { EchoMode::Streamed }; + auto const answer = + exchange(handler, quietOptions(), "POST / HTTP/1.0\r\nContent-Length: 3\r\n\r\nabc"); + CHECK_FALSE(answer.wire.contains("Transfer-Encoding")); + CHECK(answer.wire.ends_with("\r\n\r\nabc")); + CHECK(answer.closed == FlowEnd::Finished); + } +} + +TEST_CASE("HttpServer.aHeadResponseKeepsTheConnection", "[http][server]") +{ + auto handler = IgnoringHandler {}; + auto const answer = exchange(handler, quietOptions(), "HEAD / HTTP/1.1\r\nHost: a\r\n\r\n" + get("/2")); + CHECK(answer.wire.starts_with("HTTP/1.1 200 \r\nContent-Length: 2\r\n\r\nHTTP/1.1 200 \r\n")); + CHECK(answer.wire.ends_with("\r\n\r\nok")); + CHECK(handler.calls() == 2); +} + +TEST_CASE("HttpServer.aBodyPastMaxBodyBytesIs413WithoutTheHandler", "[http][server]") +{ + auto options = quietOptions(); + options.limits.maxBodyBytes = 9; + auto handler = EchoHandler {}; + auto const answer = exchange(handler, options, std::string { LengthUpload }); + auto const responses = parseResponses(answer.wire); + REQUIRE(responses.size() == 1); + CHECK(responses[0].head.status == 413); + CHECK(handler.calls() == 0); + CHECK(HttpServerOptions {}.limits.maxBodyBytes.has_value()); // bounded by default +} + +TEST_CASE("HttpServer.theHandlerSeesThePeer", "[http][server]") +{ + auto clock = core::platform::ManualClock {}; + auto loop = core::net::testing::TestLoop { clock }; + auto peer = core::net::ResolvedEndpoint {}; + peer.length = 16; + peer.family = 2; + auto pair = core::net::testing::InMemorySocketPair::create( + 0, {}, core::net::testing::InMemoryPairEndpoints { .client = peer, .server = std::nullopt }); + auto handler = EchoHandler {}; + loop.spawn(core::http::serveHttpConnection(&loop, std::move(pair.server), &handler, quietOptions())); + loop.spawn(core::http::test::writeThenFinish(pair.client.get(), get("/"))); + std::ignore = loop.drain(); + REQUIRE(handler.calls() == 1); + REQUIRE(handler.lastPeer().has_value()); + CHECK(handler.lastPeer()->family == 2); + CHECK(handler.lastPeer()->length == 16); +} + +namespace +{ + +/// Connects a client to @p listener, sends @p wire and half-closes, and collects the answer. +struct Client +{ + std::unique_ptr socket; + std::string received; + FlowEnd closed = FlowEnd::Running; +}; + +void connect(core::net::testing::TestLoop& loop, + core::net::testing::InMemoryListener& listener, + Client& client, + std::string wire) +{ + client.socket = listener.connectClient(); + loop.spawn(core::http::test::collect(client.socket.get(), &client.received, &client.closed)); + loop.spawn(core::http::test::writeOnly(client.socket.get(), std::move(wire))); +} + +} // namespace + +TEST_CASE("HttpServer.serveHttpServesConnectionsAtOnceUpToItsCap", "[http][server]") +{ + auto clock = core::platform::ManualClock {}; + auto listener = core::net::testing::InMemoryListener {}; + auto first = Client {}; + auto second = Client {}; + auto third = Client {}; + auto loop = core::net::testing::TestLoop { clock }; + auto options = quietOptions(); + auto const policy = std::make_shared(1); + options.admission = policy; + auto events = std::vector {}; + options.reporting.onEvent = [&events](core::net::AcceptLoopEvent const& event) { + events.push_back(event); + }; + auto handler = EchoHandler {}; + auto accepting = FlowEnd::Running; + loop.spawn( + core::http::test::marking(core::http::serveHttp(&loop, &listener, &handler, options), &accepting)); + + connect(loop, listener, first, get("/first")); // answered, then held open: it is idle, not done + std::ignore = loop.drain(); + CHECK(parseResponses(first.received).size() == 1); + + connect(loop, listener, second, get("/second")); // past the cap: closed unanswered + std::ignore = loop.drain(); + CHECK(second.received.empty()); + CHECK(second.closed == FlowEnd::Finished); + REQUIRE(events.size() == 1); // the refusal is reported, through the injected policy's cap + CHECK(events.front().kind == core::net::AcceptLoopEventKind::Warning); + CHECK(events.front().line.contains("admission cap")); + CHECK(policy->inFlight() == 1); + + first.socket->close(); // gives the slot back + std::ignore = loop.drain(); + connect(loop, listener, third, get("/third")); + std::ignore = loop.drain(); + CHECK(parseResponses(third.received).size() == 1); + CHECK(handler.calls() == 2); + + listener.close(); + std::ignore = loop.drain(); + CHECK(accepting == FlowEnd::Finished); +} + +TEST_CASE("HttpServer.slowConnectionsDoNotHoldOneAnother", "[http][server]") +{ + auto clock = core::platform::ManualClock {}; + auto listener = core::net::testing::InMemoryListener {}; + auto slow = Client {}; + auto fast = Client {}; + auto loop = core::net::testing::TestLoop { clock }; + auto handler = EchoHandler {}; + loop.spawn(core::http::serveHttp(&loop, &listener, &handler, quietOptions())); + connect(loop, listener, slow, "GET / HTTP/1.1\r\nHo"); // a head that never finishes + connect(loop, listener, fast, get("/fast")); + std::ignore = loop.drain(); + CHECK(slow.received.empty()); + CHECK(parseResponses(fast.received).size() == 1); + listener.close(); + std::ignore = loop.drain(); +} + +namespace +{ + +/// The kinds of @p events, in order, each followed by "; ". +std::string kindsOf(std::vector const& events) +{ + auto text = std::string {}; + for (auto const& event: events) + { + switch (event.kind) + { + case core::net::AcceptLoopEventKind::Warning: text += "warning; "; break; + case core::net::AcceptLoopEventKind::Degraded: text += "degraded; "; break; + case core::net::AcceptLoopEventKind::Recovered: text += "recovered; "; break; + case core::net::AcceptLoopEventKind::GaveUp: text += "gave up; "; break; + case core::net::AcceptLoopEventKind::Stopped: text += "stopped; "; break; + } + } + return text; +} + +/// Options whose accept loop reports into @p events. +HttpServerOptions reportingInto(std::vector* events) +{ + auto options = quietOptions(); + options.reporting.onEvent = [events](core::net::AcceptLoopEvent const& event) { + events->push_back(event); + }; + return options; +} + +/// The events of @p events but the rate-limited warnings. +std::vector withoutWarnings(std::vector events) +{ + std::erase_if(events, [](core::net::AcceptLoopEvent const& event) { + return event.kind == core::net::AcceptLoopEventKind::Warning; + }); + return events; +} + +/// Restores the discarding diagnostic sink, whatever a case installed. +struct DiagnosticSinkGuard +{ + DiagnosticSinkGuard() = default; + DiagnosticSinkGuard(DiagnosticSinkGuard const&) = delete; + DiagnosticSinkGuard& operator=(DiagnosticSinkGuard const&) = delete; + DiagnosticSinkGuard(DiagnosticSinkGuard&&) = delete; + DiagnosticSinkGuard& operator=(DiagnosticSinkGuard&&) = delete; + ~DiagnosticSinkGuard() { core::net::setDiagnosticSink({}); } +}; + +} // namespace + +TEST_CASE("HttpServer.theAcceptLoopFollowsTheAcceptPolicy", "[http][server][accept-policy]") +{ + // The accept loop is `net::serve`'s; these are that loop's cases, over serveHttp. + auto clock = core::platform::ManualClock {}; + auto inner = std::make_unique(); + auto* innerListener = inner.get(); + auto client = Client {}; + auto events = std::vector {}; + auto accepting = FlowEnd::Running; + auto handler = EchoHandler {}; + SECTION("a failed accept is backed off on and reported, and the connection behind it served") + { + auto listener = core::net::testing::FailingListener { + std::move(inner), + { core::net::makeNetError(core::net::NetErrorCode::ResourceExhausted, 0, "accept"), + core::net::makeNetError(core::net::NetErrorCode::ConnReset, 0, "AcceptEx"), + core::net::makeNetError(core::net::NetErrorCode::ResourceExhausted, 0, "accept") } + }; + auto loop = core::net::testing::TestLoop { clock }; + loop.spawn(core::http::test::marking( + core::http::serveHttp(&loop, &listener, &handler, reportingInto(&events)), &accepting)); + connect(loop, *innerListener, client, get("/behind")); + for ([[maybe_unused]] auto const pass: std::array { 1, 2, 3, 4 }) + { + std::ignore = loop.drain(); + clock.advance(core::net::AcceptErrorPolicy::MaxBackoff); + } + std::ignore = loop.drain(); + CHECK(listener.failuresAnswered() == 3); + CHECK(parseResponses(client.received).size() == 1); + CHECK(kindsOf(events) == "warning; "); + CHECK(accepting == FlowEnd::Running); + listener.close(); + std::ignore = loop.drain(); + CHECK(accepting == FlowEnd::Finished); + } + SECTION("a long run of unclassified failures is reported degraded once, then recovered") + { + constexpr auto Failures = core::net::AcceptErrorPolicy::UnclassifiedBeforeDegraded + 8; + auto listener = core::net::testing::FailingListener { + std::move(inner), + core::net::testing::repeatedFailures(core::net::NetErrorCode::SystemError, Failures) + }; + auto loop = core::net::testing::TestLoop { clock }; + loop.spawn(core::http::test::marking( + core::http::serveHttp(&loop, &listener, &handler, reportingInto(&events)), &accepting)); + connect(loop, *innerListener, client, get("/after")); + for ([[maybe_unused]] auto const pass: std::views::iota(0U, Failures + 4)) + { + std::ignore = loop.drain(); + clock.advance(core::net::AcceptErrorPolicy::MaxBackoff); + } + std::ignore = loop.drain(); + CHECK(kindsOf(withoutWarnings(events)) == "degraded; recovered; "); + CHECK(parseResponses(client.received).size() == 1); + listener.close(); + std::ignore = loop.drain(); + CHECK(accepting == FlowEnd::Finished); + } + SECTION("a degraded loop that is closed says it stopped") + { + constexpr auto Failures = core::net::AcceptErrorPolicy::UnclassifiedBeforeDegraded + 8; + auto listener = core::net::testing::FailingListener { + std::move(inner), + core::net::testing::repeatedFailures(core::net::NetErrorCode::SystemError, Failures) + }; + auto loop = core::net::testing::TestLoop { clock }; + loop.spawn(core::http::test::marking( + core::http::serveHttp(&loop, &listener, &handler, reportingInto(&events)), &accepting)); + for ([[maybe_unused]] auto const pass: + std::views::iota(0U, core::net::AcceptErrorPolicy::UnclassifiedBeforeDegraded + 2)) + { + std::ignore = loop.drain(); + clock.advance(core::net::AcceptErrorPolicy::MaxBackoff); + } + listener.close(); // during a backoff: the loop returns at once + std::ignore = loop.drain(); + CHECK(accepting == FlowEnd::Finished); + CHECK(kindsOf(withoutWarnings(events)) == "degraded; stopped; "); + } + SECTION("a dead listener is given up on, closed, and reported") + { + auto listener = core::net::testing::FailingListener { + std::move(inner), core::net::testing::repeatedFailures(core::net::NetErrorCode::BadHandle, 1) + }; + auto const closed = listener.closeToken(); + auto loop = core::net::testing::TestLoop { clock }; + loop.spawn(core::http::test::marking( + core::http::serveHttp(&loop, &listener, &handler, reportingInto(&events)), &accepting)); + std::ignore = loop.drain(); + CHECK(accepting == FlowEnd::Finished); + CHECK(closed.stop_requested()); + REQUIRE(kindsOf(events) == "gave up; "); + CHECK(events.front().error.code == core::net::NetErrorCode::BadHandle); + } + SECTION("with no one to tell, the report goes to the diagnostic sink") + { + auto const guard = DiagnosticSinkGuard {}; + auto lines = std::vector {}; + core::net::setDiagnosticSink([&lines](std::string_view line) { lines.emplace_back(line); }); + auto listener = core::net::testing::FailingListener { + std::move(inner), core::net::testing::repeatedFailures(core::net::NetErrorCode::BadHandle, 1) + }; + auto loop = core::net::testing::TestLoop { clock }; + loop.spawn(core::http::test::marking( + core::http::serveHttp(&loop, &listener, &handler, quietOptions()), &accepting)); + std::ignore = loop.drain(); + CHECK(accepting == FlowEnd::Finished); + REQUIRE(lines.size() == 1); + CHECK(lines.front().starts_with("http")); + } +} + +TEST_CASE("HttpServer.aBodyReadLeftRunningNeverMeetsTheClose", "[http][server]") +{ + auto left = core::http::test::LeftRunning {}; + auto* loop = static_cast(nullptr); + SECTION("a read still parked is retired, and has returned, before the close lingers") + { + // The handler answers once its read has parked on the 7 bytes the client never sends. + auto handler = core::http::test::SpawningReader { &loop, &left, 1ms }; + auto served = ServedConnection { handler, quietOptions() }; + loop = &served.loop(); + served.send("POST / HTTP/1.1\r\nHost: a\r\nContent-Length: 10\r\n\r\nabc"); + served.advance(1ms); + served.advance(HttpServerOptions {}.linger.total); + auto const responses = parseResponses(served.received()); + REQUIRE(responses.size() == 1); + CHECK(responses[0].body == "ok"); + CHECK(left.text == "abc"); + CHECK(left.failure == HttpErrorCode::ConnectionTerminated); + CHECK(left.retry == HttpErrorCode::ConnectionTerminated); // the request is over + CHECK(left.end == FlowEnd::Finished); + CHECK(served.server() == FlowEnd::Finished); + CHECK(served.wire() == FlowEnd::Finished); + } + SECTION("a kept reader that reads during the close is refused") + { + auto handler = IgnoringHandler { KeepsReader::Yes }; + auto served = ServedConnection { handler, quietOptions() }; + served.send("POST / HTTP/1.1\r\nHost: a\r\nContent-Length: 10\r\n\r\nabc"); + REQUIRE(handler.kept().size() == 1); + CHECK(served.server() == FlowEnd::Running); // lingering: the client has not closed + served.loop().spawn(core::http::test::readThenRetry(std::move(handler.kept().front()), &left)); + served.drain(); + CHECK(left.failure == HttpErrorCode::ConnectionTerminated); + CHECK(left.text.empty()); + served.advance(HttpServerOptions {}.linger.total); + CHECK(served.server() == FlowEnd::Finished); + } + SECTION("a read writing the interim response has the connection closed under it") + { + // A client that does not read, over a pair that holds 8 bytes: the `100 Continue` stalls. + auto handler = core::http::test::SpawningReader { &loop, &left, 1ms }; + auto served = ServedConnection { handler, quietOptions(), 8, core::http::test::ClientReads::No }; + loop = &served.loop(); + served.send("POST / HTTP/1.1\r\nHost: a\r\nExpect: 100-continue\r\nContent-Length: 10\r\n\r\n"); + served.advance(1ms); + CHECK(served.server() == FlowEnd::Finished); + CHECK(left.failure.has_value()); + } +} + +namespace +{ + +/// A socket whose `cancelRead` takes effect a turn later, as a completion transport's does: the +/// parked read holds the socket's read slot until then. +class DeferredCancelSocket final: public core::net::testing::SocketDecorator +{ + public: + DeferredCancelSocket(core::net::ISocket& inner, core::net::EventLoop& loop) noexcept: + SocketDecorator { inner }, _loop { &loop } + { + } + + void cancelRead() noexcept override + { + _loop->post([target = &inner()] { target->cancelRead(); }); + } + + private: + core::net::EventLoop* _loop; +}; + +} // namespace + +TEST_CASE("HttpServer.theCloseWaitsForARetiredReadToReturn", "[http][server]") +{ + // The retired read returns a turn after its cancel: a close that read before then would arm a + // second read over it, which every socket refuses. + auto clock = core::platform::ManualClock {}; + auto pair = core::net::testing::InMemorySocketPair::create(); + auto left = core::http::test::LeftRunning {}; + auto received = std::string {}; + auto wire = FlowEnd::Running; + auto server = FlowEnd::Running; + auto loop = core::net::testing::TestLoop { clock }; + auto* spawnOn = static_cast(&loop); + auto handler = core::http::test::SpawningReader { &spawnOn, &left, 1ms }; + loop.spawn(core::http::test::marking( + core::http::serveHttpConnection( + &loop, std::make_unique(*pair.server, loop), &handler, quietOptions()), + &server)); + loop.spawn(core::http::test::collect(pair.client.get(), &received, &wire)); + loop.spawn(core::http::test::writeOnly(pair.client.get(), + "POST / HTTP/1.1\r\nHost: a\r\nContent-Length: 10\r\n\r\nabc")); + std::ignore = loop.drain(); + clock.advance(1ms); + std::ignore = loop.drain(); + clock.advance(HttpServerOptions {}.linger.total); + std::ignore = loop.drain(); + CHECK(parseResponses(received).size() == 1); + CHECK(left.failure == HttpErrorCode::ConnectionTerminated); + CHECK(server == FlowEnd::Finished); +} diff --git a/src/core/http/HttpTestSupport.hpp b/src/core/http/HttpTestSupport.hpp index 42c5593e..3674fc26 100644 --- a/src/core/http/HttpTestSupport.hpp +++ b/src/core/http/HttpTestSupport.hpp @@ -4,14 +4,16 @@ /// @file /// Test-only helpers the `core::http` cases share: raw wire text written to a socket, a body read /// to its end, a flow run on a hand-driven loop until it has an answer, a server end a case scripts, -/// and a TLS context whose handshake and failures a case scripts (R29: no `core::net_tls`, so the -/// binaries build without `CORE_CPP_WITH_TLS`). Test-only: in no `FILE_SET`, so never installed. +/// a served connection a case drives byte by byte with the handlers it serves, and a TLS context whose +/// handshake and failures a case scripts (R29: no `core::net_tls`, so the binaries build without +/// `CORE_CPP_WITH_TLS`). Test-only: in no `FILE_SET`, so never installed. #include #include #include #include #include +#include #include #include #include @@ -19,6 +21,9 @@ #include #include #include +#include +#include +#include #include @@ -45,6 +50,19 @@ namespace core::http::test /// does, and to fail where the same behaviour shows natively. A @c bool because the name asks it. [[nodiscard]] bool runsUnderWine() noexcept; +/// What a loopback connection does with a flood its peer never reads. +enum class LoopbackFlood : std::uint8_t +{ + Stalls, ///< The writer stalls once the kernel buffers are full (Linux, macOS, the BSDs). + Absorbed, ///< The whole flood is taken: Windows, natively and under wine, which tunes a + ///< loopback window past the buffer sizes it was given (measured on CI with 4 and + ///< 64 MiB). +}; + +/// @return What this platform's loopback does with an unread flood; defined beside +/// @c runsUnderWine. +[[nodiscard]] LoopbackFlood loopbackFlood() noexcept; + /// @param text The bytes to view. /// @return @p text as the byte span a socket write takes. [[nodiscard]] inline std::span bytesOf(std::string_view text) noexcept @@ -351,6 +369,414 @@ class SlowBodySource final: public IBodySource std::size_t _next = 0; }; +// ------------------------------------------------------------------------------------------------- +// A served connection, driven by a case (Task 18). + +/// Whether a flow a case started has finished. +enum class FlowEnd : std::uint8_t +{ + Running, ///< It is still parked, or has not started. + Finished, ///< It ran to its end. +}; + +/// Runs @p task, then marks @p end finished. +/// @param task The flow. +/// @param end Where it says so; must outlive the returned task. +inline async::Task marking(async::Task task, FlowEnd* end) +{ + co_await std::move(task); + *end = FlowEnd::Finished; +} + +/// Reads @p socket until EOF or an error, appending as it goes, then marks @p end finished: what a +/// client received so far, readable while the server is still writing. +/// @param socket The client end; must outlive the returned task. +/// @param out Where the bytes go; must outlive the returned task. +/// @param end Set once the wire has ended; must outlive the returned task. +inline async::Task collect(net::ISocket* socket, std::string* out, FlowEnd* end) +{ + auto chunk = std::vector(4096); + while (true) + { + auto const got = co_await socket->read(std::span { chunk }); + if (!got.has_value() || *got == 0) + break; + *out += textOf(std::span { chunk }.first(*got)); + } + *end = FlowEnd::Finished; +} + +/// Writes @p text to @p socket in full, then half-closes it: a client that has sent all it will. +/// @param socket The writer; must outlive the returned task. +/// @param text The wire bytes, owned by the frame. +inline async::Task writeThenFinish(net::ISocket* socket, std::string text) +{ + if (!text.empty()) + static_cast(co_await socket->write(bytesOf(text))); + static_cast(co_await socket->shutdownWrite()); +} + +/// Whether a served connection's client end reads what the server writes. +enum class ClientReads : std::uint8_t +{ + Yes, ///< Everything, as it arrives. + No, ///< Nothing: a client that stops reading, which a bounded pair turns into a stalled write. +}; + +/// One connection served by @c serveHttpConnection over an in-memory pair on a hand-driven loop, its +/// client end a case writes raw bytes to. Everything the server wrote is in @c received as soon as a +/// drain has run; the clock moves only when the case advances it. +class ServedConnection +{ + public: + /// Starts serving. + /// @param handler The handler; must outlive this. + /// @param options The server's configuration. + /// @param maxBytesInFlight The pair's per-direction bound; zero means none. + /// @param reads Whether the client end reads. + ServedConnection(IHttpHandler& handler, + HttpServerOptions options, + std::size_t maxBytesInFlight = 0, + ClientReads reads = ClientReads::Yes): + _pair { net::testing::InMemorySocketPair::create(maxBytesInFlight) } + { + _loop.spawn(marking( + serveHttpConnection(&_loop, std::move(_pair.server), &handler, std::move(options)), &_server)); + if (reads == ClientReads::Yes) + _loop.spawn(collect(_pair.client.get(), &_received, &_wire)); + drain(); // the server parks in its first read now, at time zero + } + + ServedConnection(ServedConnection const&) = delete; + ServedConnection& operator=(ServedConnection const&) = delete; + ServedConnection(ServedConnection&&) = delete; + ServedConnection& operator=(ServedConnection&&) = delete; + ~ServedConnection() = default; + + /// Sends @p text and leaves the client end open, then drains. + void send(std::string text) + { + _loop.spawn(writeOnly(_pair.client.get(), std::move(text))); + drain(); + } + + /// Sends @p text and half-closes the client end, then drains. + void finish(std::string text = {}) + { + _loop.spawn(writeThenFinish(_pair.client.get(), std::move(text))); + drain(); + } + + /// Runs the loop until it has nothing to do. + void drain() { std::ignore = _loop.drain(); } + + /// Moves the clock by @p by, then drains. + void advance(std::chrono::milliseconds by) + { + _clock.advance(by); + drain(); + } + + /// @return The loop, for a handler that waits on its clock. + [[nodiscard]] net::EventLoop& loop() noexcept { return _loop; } + + /// @return Everything the server wrote so far. + [[nodiscard]] std::string const& received() const noexcept { return _received; } + + /// @return Whether the server's flow has ended. + [[nodiscard]] FlowEnd server() const noexcept { return _server; } + + /// @return Whether the client end has read the wire's end (EOF or a reset). + [[nodiscard]] FlowEnd wire() const noexcept { return _wire; } + + private: + platform::ManualClock _clock {}; + net::testing::InMemorySocketPair _pair; + std::string _received; + FlowEnd _server = FlowEnd::Running; + FlowEnd _wire = FlowEnd::Running; + net::testing::TestLoop _loop { _clock }; // last: destroyed first, with every flow that uses the above +}; + +/// What a client of one served connection saw. +struct Exchanged +{ + std::string wire; ///< Every byte the server wrote. + FlowEnd server; ///< Whether the server's flow ended. + FlowEnd closed; ///< Whether the client saw the wire end. +}; + +/// Sends @p wire on a fresh connection and half-closes it, then reads what the server answers. +/// @param handler The handler. +/// @param options The server's configuration. +/// @param wire The client's bytes. +/// @return What came back. +[[nodiscard]] inline Exchanged exchange(IHttpHandler& handler, HttpServerOptions options, std::string wire) +{ + auto served = ServedConnection { handler, std::move(options) }; + served.finish(std::move(wire)); + return Exchanged { .wire = served.received(), .server = served.server(), .closed = served.wire() }; +} + +/// One response as a client read it off the wire. +struct ParsedResponse +{ + ResponseHead head; ///< Its head. + std::string body; ///< Its body, decoded. + Fields trailers; ///< Its trailers. +}; + +/// Every response in @p wire, in order, each framed as a response to @p method would be; a malformed +/// one fails the case, and a body cut off at the wire's end ends the list. +/// @param wire What a server wrote. +/// @param method The request method the responses answer. +/// @return The responses, 1xx ones included. +[[nodiscard]] inline std::vector parseResponses(std::string_view wire, + std::string_view method = "GET") +{ + auto responses = std::vector {}; + while (!wire.empty()) + { + auto parser = HeadParser { MessageRole::Response, HttpLimits {} }; + auto fed = parser.feed(wire); + REQUIRE(fed.has_value()); + if (fed->progress != Progress::Complete) + break; + wire.remove_prefix(fed->consumed); + auto response = ParsedResponse { .head = parser.takeResponse(), .body = {}, .trailers = {} }; + auto framing = + responseFraming(method, response.head.version, response.head.status, response.head.fields); + REQUIRE(framing.has_value()); + switch (framing->kind) + { + case BodyFraming::None: break; + case BodyFraming::Length: + if (wire.size() < framing->length) + return responses; + response.body = std::string { wire.substr(0, framing->length) }; + wire.remove_prefix(framing->length); + break; + case BodyFraming::UntilClose: + response.body = std::string { wire }; + wire = {}; + break; + case BodyFraming::Chunked: { + auto decoder = ChunkedDecoder { MessageRole::Response, HttpLimits {} }; + while (true) + { + auto step = decoder.feed(wire); + REQUIRE(step.has_value()); + response.body += std::string { step->data }; + wire.remove_prefix(step->consumed); + if (step->progress == Progress::Complete) + break; + if (wire.empty()) + return responses; + } + response.trailers = decoder.takeTrailers(); + break; + } + } + responses.push_back(std::move(response)); + } + return responses; +} + +/// @return The first value of the field @p name in @p fields, or empty. +[[nodiscard]] inline std::string fieldOf(Fields const& fields, std::string_view name) +{ + auto const values = fields.get(name); + return values.empty() ? std::string {} : std::string { values.front() }; +} + +/// A body source that reads a request body as the response is written: what a handler that streams +/// its request into its response returns. It holds the reader, so the reader lives until the +/// response does. +class ReaderBodySource final: public IBodySource +{ + public: + /// @param reader The request body. + explicit ReaderBodySource(std::unique_ptr reader): _reader { std::move(reader) } {} + + [[nodiscard]] std::optional knownLength() const noexcept override { return std::nullopt; } + [[nodiscard]] TrailerIntent trailerIntent() const noexcept override { return TrailerIntent::Possible; } + [[nodiscard]] async::Task> next() override { return _reader->read(1024); } + [[nodiscard]] async::Task> trailers() override { return _reader->trailers(); } + + private: + std::unique_ptr _reader; +}; + +/// How an @c EchoHandler reads the request body. +enum class EchoMode : std::uint8_t +{ + Buffered, ///< Whole, before it answers: the response has a known length (or trailers). + Streamed, ///< Lazily, as the server writes the response, which is chunked. +}; + +/// Answers every request 200 with its body and trailers, and `X-Echo: `. A body +/// read failure is the handler's failure, and is recorded. +class EchoHandler final: public IHttpHandler +{ + public: + /// @param mode How the body is read. + explicit EchoHandler(EchoMode mode = EchoMode::Buffered): _mode { mode } {} + + [[nodiscard]] async::Task> handle(IncomingRequest request) override + { + return answer(this, std::move(request)); + } + + /// @return How many requests it was called for. + [[nodiscard]] std::size_t calls() const noexcept { return _calls; } + + /// @return The code of the last body read that failed, if one did. + [[nodiscard]] std::optional readFailure() const noexcept { return _readFailure; } + + /// @return The peer of the last request. + [[nodiscard]] std::optional const& lastPeer() const noexcept { return _peer; } + + /// @return The target of every request it was called for, in order. + [[nodiscard]] std::vector const& targets() const noexcept { return _targets; } + + private: + static async::Task> answer(EchoHandler* self, IncomingRequest request) + { + ++self->_calls; + self->_peer = request.peer; + self->_targets.emplace_back(request.head.target.text()); + auto head = ResponseHead {}; + auto const echo = + std::string { request.head.method.text() } + " " + std::string { request.head.target.text() }; + REQUIRE(head.fields.append("X-Echo", echo).has_value()); + if (self->_mode == EchoMode::Streamed) + co_return OutgoingResponse { .head = std::move(head), + .body = + std::make_unique(std::move(request.body)) }; + auto body = co_await readAll(request.body.get(), 1024); + if (body.error.has_value()) + { + self->_readFailure = body.error->code; + co_return std::unexpected(std::move(*body.error)); + } + auto trailers = co_await request.body->trailers(); + if (!trailers.has_value()) + co_return std::unexpected(std::move(trailers.error())); + co_return OutgoingResponse { .head = std::move(head), + .body = std::make_unique(std::move(body.text), + std::move(*trailers)) }; + } + + EchoMode _mode; + std::size_t _calls = 0; + std::optional _readFailure; + std::optional _peer; + std::vector _targets; +}; + +/// Whether an @c IgnoringHandler keeps each request's body reader alive after it answers. +enum class KeepsReader : std::uint8_t +{ + No, ///< The reader is dropped with the request. + Yes, ///< The handler holds it for as long as it lives. +}; + +/// Answers every request `200` with the body `ok`, and never reads the request body. +class IgnoringHandler final: public IHttpHandler +{ + public: + /// @param keeps Whether the unread body readers are kept alive. + explicit IgnoringHandler(KeepsReader keeps = KeepsReader::No): _keeps { keeps } {} + + [[nodiscard]] async::Task> handle(IncomingRequest request) override + { + ++_calls; + if (_keeps == KeepsReader::Yes) + _kept.push_back(std::move(request.body)); + return okResponse(); + } + + /// @return How many requests it was called for. + [[nodiscard]] std::size_t calls() const noexcept { return _calls; } + + /// @return The readers it kept, in order. + [[nodiscard]] std::vector>& kept() noexcept { return _kept; } + + /// @return A 200 response with the body `ok`. + static async::Task> okResponse() + { + co_return OutgoingResponse { .head = ResponseHead {}, + .body = std::make_unique("ok") }; + } + + private: + KeepsReader _keeps; + std::size_t _calls = 0; + std::vector> _kept; +}; + +/// What a body read a handler left running found: the body it read, the failure that ended it, and +/// what a read retried after that failure answered. +struct LeftRunning +{ + std::string text; ///< The body bytes it read. + std::optional failure; ///< What ended the read, if anything did. + std::optional retry; ///< What one more read after the failure answered. + FlowEnd end = FlowEnd::Running; ///< Whether the read's flow has ended. +}; + +/// Reads @p reader to its end and, after a failure, once more: a handler's read that runs on after it. +/// @param reader The body, owned by the flow. +/// @param out What it found; must outlive the returned task. +inline async::Task readThenRetry(std::unique_ptr reader, LeftRunning* out) +{ + auto body = co_await readAll(reader.get(), 1024); + out->text = body.text; + if (body.error.has_value()) + { + out->failure = body.error->code; + auto again = co_await reader->read(1024); + if (!again.has_value()) + out->retry = again.error().code; + } + out->end = FlowEnd::Finished; +} + +/// Answers every request `200` with the body `ok` at once, and leaves a flow reading its body running +/// on the loop: a handler whose body read outlives its response. +class SpawningReader final: public IHttpHandler +{ + public: + /// @param loop Where the read is spawned, set before the first request; must outlive this. + /// @param out What the last read found; must outlive every read. + /// @param answerAfter How long it waits on the loop's clock before it answers; zero answers at once. + SpawningReader(net::EventLoop** loop, + LeftRunning* out, + std::chrono::milliseconds answerAfter = std::chrono::milliseconds { 0 }): + _loop { loop }, _out { out }, _answerAfter { answerAfter } + { + } + + [[nodiscard]] async::Task> handle(IncomingRequest request) override + { + (*_loop)->spawn(readThenRetry(std::move(request.body), _out)); + return answer(*_loop, _answerAfter); + } + + private: + static async::Task> answer(net::EventLoop* loop, + std::chrono::milliseconds after) + { + if (after > std::chrono::milliseconds { 0 }) + co_await loop->delay(after); + co_return co_await IgnoringHandler::okResponse(); + } + + net::EventLoop** _loop; + LeftRunning* _out; + std::chrono::milliseconds _answerAfter; +}; + // ------------------------------------------------------------------------------------------------- // TLS, scripted (R29). diff --git a/src/core/http/Message.hpp b/src/core/http/Message.hpp index 4fa8ffd4..b35b2893 100644 --- a/src/core/http/Message.hpp +++ b/src/core/http/Message.hpp @@ -135,14 +135,16 @@ namespace detail /// What a refusal of a peer's message was for, where its code alone does not say which status a /// server answers it with. /// -/// Not part of the WIT's `error-code`, which has no case for either: both are a -/// @c HttpErrorCode::ProtocolError there. RFC 9110 gives each a status of its own, so the parsers -/// say which it was and a server's @c errorStatusTable maps the pair. +/// Not part of the WIT's `error-code`, which has no case for any of these: the first two are a +/// @c HttpErrorCode::ProtocolError there, and the third a read timeout. RFC 9110 gives the first two a +/// status of their own, and a server closes an idle connection without one (RFC 9112 section 9.5), so +/// the parsers and the connection say which it was and a server's @c errorStatusTable maps the pair. enum class RefusalReason : std::uint8_t { Unclassified, ///< Nothing beyond the code; the default. UnsupportedVersion, ///< The message's version is not HTTP/1.x (RFC 9110 section 15.6.6: 505). UnimplementedCoding, ///< A request transfer coding this layer cannot decode (RFC 9112 6.1: 501). + NothingArrived, ///< A read deadline passed before a message's first byte: an idle connection. }; /// An HTTP failure: its code and the payload the code carries. @@ -301,7 +303,7 @@ struct RequestHead /// A response's status line and its fields. struct ResponseHead { - std::uint16_t status = 200; ///< The status code, 100 to 599. + std::uint16_t status = 200; ///< The status code; one outside 100 to 999 is never written. ReasonPhrase reason; ///< The reason phrase. HttpVersion version = HttpVersion::Http11; ///< The version it is framed by. Fields fields; ///< The header fields. diff --git a/src/core/http/SmugglingCorpus.hpp b/src/core/http/SmugglingCorpus.hpp index f320c46a..8e7995e9 100644 --- a/src/core/http/SmugglingCorpus.hpp +++ b/src/core/http/SmugglingCorpus.hpp @@ -852,6 +852,39 @@ namespace detail .code = HttpErrorCode::InternalError, .status = 200, .body = "" }, + // CL.TE: a front end framing by Content-Length would pass the chunked body's end and the request + // behind it as one body; refused at the head, so nothing after it is ever read as a request + SmugglingCase { .name = "smuggled-get-behind-te-with-cl", + .role = MessageRole::Request, + .wire = "POST / HTTP/1.1\r\n" + "Host: a\r\n" + "Content-Length: 44\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n" + "0\r\n" + "\r\n" + "GET /smuggled HTTP/1.1\r\n" + "Host: a\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 400, + .body = "" }, + // two Content-Length values: one reader takes the shorter, and the rest is a request + SmugglingCase { .name = "smuggled-get-behind-two-lengths", + .role = MessageRole::Request, + .wire = "POST / HTTP/1.1\r\n" + "Host: a\r\n" + "Content-Length: 0\r\n" + "Content-Length: 37\r\n" + "\r\n" + "GET /smuggled HTTP/1.1\r\n" + "Host: a\r\n" + "\r\n"sv, + .verdict = SmugglingVerdict::Refused, + .code = HttpErrorCode::ProtocolError, + .status = 400, + .body = "" }, // a field line is past HttpLimits::maxFieldBytes SmugglingCase { .name = "field-too-large", .role = MessageRole::Request, diff --git a/src/core/http/posix/HttpTestSupport.cpp b/src/core/http/posix/HttpTestSupport.cpp index 2d7d156f..8444580e 100644 --- a/src/core/http/posix/HttpTestSupport.cpp +++ b/src/core/http/posix/HttpTestSupport.cpp @@ -11,4 +11,9 @@ bool runsUnderWine() noexcept return false; } +LoopbackFlood loopbackFlood() noexcept +{ + return LoopbackFlood::Stalls; +} + } // namespace core::http::test diff --git a/src/core/http/windows/HttpTestSupport.cpp b/src/core/http/windows/HttpTestSupport.cpp index 780cc0e6..85cfd754 100644 --- a/src/core/http/windows/HttpTestSupport.cpp +++ b/src/core/http/windows/HttpTestSupport.cpp @@ -16,4 +16,9 @@ bool runsUnderWine() noexcept return ntdll != nullptr && GetProcAddress(ntdll, "wine_get_version") != nullptr; } +LoopbackFlood loopbackFlood() noexcept +{ + return LoopbackFlood::Absorbed; +} + } // namespace core::http::test diff --git a/tests/consumer-vendored/CMakeLists.txt b/tests/consumer-vendored/CMakeLists.txt index afbff716..4136abb1 100644 --- a/tests/consumer-vendored/CMakeLists.txt +++ b/tests/consumer-vendored/CMakeLists.txt @@ -78,6 +78,6 @@ add_test(NAME core-cpp-vendored-copy add_executable(consumer-vendored main.cpp) # core::fs is linked although main.cpp names nothing of it: it is EXCLUDE_FROM_ALL like every target # of the copy, so a link is what makes this build compile it. -target_link_libraries(consumer-vendored PRIVATE core::async core::log core::net core::net_tls core::fs) +target_link_libraries(consumer-vendored PRIVATE core::async core::log core::net core::net_tls core::fs core::http) add_test(NAME consumer-vendored COMMAND consumer-vendored) set_tests_properties(consumer-vendored PROPERTIES TIMEOUT 120) diff --git a/tests/consumer-vendored/main.cpp b/tests/consumer-vendored/main.cpp index 24cef4ee..02459713 100644 --- a/tests/consumer-vendored/main.cpp +++ b/tests/consumer-vendored/main.cpp @@ -3,7 +3,8 @@ // What a consumer with a vendored copy builds: a coroutine flow on core::net's event loop, a // loopback echo over a real socket, a line through a core::log sink of this program's own, and // core::net_tls, which is the one part that needs a system dependency (OpenSSL) rather than a -// fetched one. There is no core::tui here: CORE_CPP_WITH_TUI is off, as it is for a build that +// fetched one; and core::http, which a vendored copy carries unless CORE_CPP_WITH_HTTP is off. There +// is no core::tui here: CORE_CPP_WITH_TUI is off, as it is for a build that // wants no libunicode. // // The first two are in ../consumer-shared/ConsumerSmoke.hpp, which the CPM consumer uses too; what @@ -12,6 +13,8 @@ // // Every step reports through Checks, so a failure names the step rather than only an exit code. +#include +#include #include #include @@ -36,6 +39,13 @@ void checkTls(Checks& checks) checks.expect(context.has_value() && *context != nullptr, "core::net_tls built a client context"); } +/// core::http: a copy that carries it links it, and its pure layer answers. +void checkHttp(Checks& checks) +{ + checks.expect(core::http::chunkHeader(255) == "ff\r\n" && core::http::statusPhrase(100) == "Continue", + "core::http framed a chunk and named a status"); +} + } // namespace int main() @@ -44,6 +54,7 @@ int main() consumer::smoke::checkLoopbackEcho(checks, std::string_view { "hello from a vendored copy" }); consumer::smoke::checkLogging(checks, std::string_view { "a vendored consumer" }); checkTls(checks); + checkHttp(checks); if (checks.failed() != 0) { From 6c05d53c7eaeb79572767321b1a6df36e1216de5 Mon Sep 17 00:00:00 2001 From: Christian Parpart Date: Fri, 27 Nov 2026 06:16:05 +0100 Subject: [PATCH 15/19] feat(base): constant-time byte comparison and secure zeroing core::constantTimeEquals reads every byte of both inputs and passes the accumulated difference through a value barrier after each one, so its time depends only on the length; core::secureZero writes through a volatile pointer and ends with a memory barrier, so the stores survive optimisation. Both are out of line; the barriers are an empty asm volatile under the GNU front end and volatile objects under MSVC's, chosen by CMAKE_CXX_COMPILER_FRONTEND_VARIANT, and hold under LTO too. The gcc-release and clang-release disassembly shows the compare loop branching only on its index. core::net::constantTimeEquals keeps CRYPTO_memcmp. Also in this commit: - hold constantTimeEquals's compare loop to no data-dependent branch - the constant-time check fails closed - MSVC's memory barrier is a signal fence - print AppleClang's arm64 code for the constant-time functions Signed-off-by: Christian Parpart --- .agent/reference/provenance.md | 6 + .github/workflows/build.yml | 21 ++++ docs/modules/base.md | 20 +++ scripts/check-constant-time-selftest.py | 158 ++++++++++++++++++++++++ scripts/check-constant-time.py | 143 +++++++++++++++++++++ src/core/CMakeLists.txt | 14 +++ src/core/ConstantTime.cpp | 35 ++++++ src/core/ConstantTime.hpp | 49 ++++++++ src/core/ConstantTime_test.cpp | 96 ++++++++++++++ src/core/ValueBarrier.hpp | 25 ++++ src/core/ValueBarrierGnu.cpp | 23 ++++ src/core/ValueBarrierMsvc.cpp | 30 +++++ tests/CMakeLists.txt | 33 +++++ 13 files changed, 653 insertions(+) create mode 100644 scripts/check-constant-time-selftest.py create mode 100644 scripts/check-constant-time.py create mode 100644 src/core/ConstantTime.cpp create mode 100644 src/core/ConstantTime.hpp create mode 100644 src/core/ConstantTime_test.cpp create mode 100644 src/core/ValueBarrier.hpp create mode 100644 src/core/ValueBarrierGnu.cpp create mode 100644 src/core/ValueBarrierMsvc.cpp diff --git a/.agent/reference/provenance.md b/.agent/reference/provenance.md index 531982de..71b09e92 100644 --- a/.agent/reference/provenance.md +++ b/.agent/reference/provenance.md @@ -61,6 +61,9 @@ others in notes. | `src/core/Clock_test.cpp` | contour-terminal/endo | `src/platform/Clock_test.cpp` | `f774a210ce989e5947b8f61d715068b1dc96088c` | the steady-clock cases of `src/core/platform/Clock_test.cpp`, moved with the header (U.5) | | `src/core/CMakeLists.txt` | origin: core-cpp | - | - | - | | `src/core/Config.hpp.in` | origin: core-cpp | - | - | generates `core/Config.hpp` | +| `src/core/ConstantTime.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): `constantTimeEquals` and `secureZero`, for Isoline P8 | +| `src/core/ConstantTime.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): the constant-time comparison and secure zeroing, and their guarantee | +| `src/core/ConstantTime_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | | `src/core/Deferred.hpp` | contour-terminal/contour | `src/crispy/Deferred.hpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | - | | `src/core/Defines.hpp` | contour-terminal/contour | `src/crispy/Defines.hpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | `CRISPY_*` macros renamed `CORE_*` | | `src/core/Environment.cpp` | contour-terminal/contour | `src/crispy/Environment.cpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | post-import additions (Task A4): the process-environment writer (`setProcessEnvironmentVariable()`/`unsetProcessEnvironmentVariable()`), and on Windows `LiveEnvironment` reads a variable set to the empty string as set; on Windows, its UTF-16 to UTF-8 conversion is `core::toUtf8()` (`WideString.cpp`); the Windows reader and writer convert through `core::toUtf16()` (`WideString.cpp`) rather than a copy of their own | @@ -96,6 +99,9 @@ others in notes. | `src/core/Utils.cpp` | contour-terminal/contour | `src/crispy/Utils.cpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | post-import fix (Task A9): Windows' `threadName()` frees the thread description on every path, and a failed conversion answers empty instead of throwing; Windows' `threadName()` converts through `core::toUtf8()` (`WideString.cpp`) | | `src/core/Utils.hpp` | contour-terminal/contour | `src/crispy/Utils.hpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | `Overloaded` split out to `Overloaded.hpp`; `views::enumerate` is now a function template; post-import fixes (Task A9): `splitKeyValuePairs()`'s last segment ends where the view does; `toLower()`/`toUpper()` widen through `unsigned char`; `readFileAsString()` takes the path itself, opens it binary and keeps only what it read; `eachElement()`'s end iterator no longer wraps onto its begin; post-import fixes (Task A9 fix round 1): `readFileAsString()` reports a missing file as empty rather than throwing; the case mapping sends a wide character to `towlower`/`towupper` instead of truncating it into the narrow functions' domain; `joinHumanReadableQuoted()`'s separator is a `std::string_view`, so its default is usable; post-import addition: `toLowerHexString()`, for bytes, from fastcached's `HexDigest` (`src/FastCache/Core/Sha256.cpp` at `8c27b162`); post-import fix: `toHexString()` reads each `char` as an unsigned byte rather than sign-extending it into `FFFFFF80`, and shares `detail::spellHex()` with `toLowerHexString()`; post-import fix: `replaceVariables()` emits an unterminated `${` once, instead of repeating the text before it, and ends a name at the next `${`; post-import fix: `homeResolvedPath()` reads its input as UTF-8 (`pathFromUtf8()`); `homeResolvedPath()` returns `std::expected` and takes a `std::string_view`: input that is not UTF-8 is an error rather than an exception (`core::pathFromUtf8()`) | | `src/core/Utils_test.cpp` | contour-terminal/contour | `src/crispy/Utils_test.cpp` | `6777ff05014f8ff163b071e8b0e942830119db80` | post-import additions (Task A9): the bounds, case-mapping, file-reading, `eachElement()` and thread-name cases; post-import additions (Task A9 fix round 1): the missing-file and `joinHumanReadableQuoted()` cases; post-import addition: the `toLowerHexString()` case, and the `toHexString()` case for the fix above; post-import addition: the malformed-marker `replaceVariables()` cases; post-import addition: the UTF-8 `homeResolvedPath()` case; the not-UTF-8 `homeResolvedPath()` case | +| `src/core/ValueBarrier.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): the barriers `ConstantTime.cpp` is built on | +| `src/core/ValueBarrierGnu.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the GNU front end's barriers, empty `asm volatile` | +| `src/core/ValueBarrierMsvc.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): MSVC's front end's barriers, `volatile` objects | | `src/core/WideString.cpp` | origin: core-cpp | - | - | the one UTF-16 to UTF-8 conversion on Windows, which `Environment.cpp`, `Utils.cpp` and `core::platform`'s `WindowsProcessEnvironment.cpp` and `SystemInfo.cpp` each had a copy of; and `toUtf16()`, the strict UTF-8 to UTF-16 conversion behind `core::pathFromUtf8()` and `Environment.cpp`; used by `core::testing`'s `EnvHelper.cpp` as well; public as `core::toUtf8()` and `core::toUtf16()`, which answers `std::expected` with `std::errc::illegal_byte_sequence`, so a consumer's wide calls convert the same way (contour, endo and fastcached each kept a copy); `systemErrorMessage()`, `FormatMessageW()` converted, as contour's `vtpty::systemErrorMessage()` (`src/vtpty/Utf16.cpp`) did, with the trailing line break removed and a message for an error the system has none for | | `src/core/WideString.hpp` | origin: core-cpp | - | - | public, in base's file set, and Windows only: it declares nothing elsewhere, where a `wchar_t` is not UTF-16; it was private, in `core::detail`, until contour needed the conversions too; declares `systemErrorMessage()` | | `src/core/WideString_test.cpp` | origin: core-cpp | - | - | the `toUtf16()` cases, which check the error it answers; the `systemErrorMessage()` cases, under US English and under German where the system has it | diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index c2b129d7..5c2dc70b 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -196,6 +196,10 @@ jobs: - name: Text-encoding self-test run: python scripts/check-text-encoding-selftest.py + # covers: core-cpp.constant-time-selftest + - name: Constant-time check self-test + run: python scripts/check-constant-time-selftest.py + # covers: core-cpp.tidy-record-selftest - name: Tidy-record self-test run: python scripts/tidy-record-selftest.py @@ -559,6 +563,23 @@ jobs: - name: Build run: cmake --build --preset ${{ matrix.preset }} + # The constant-time record for the pull request body: AppleClang's arm64 code for + # core::constantTimeEquals and core::secureZero, as this release build generated it, with the + # barriers they call. Printed, not judged: scripts/check-constant-time.py judges it in ctest. + - name: Disassemble the constant-time functions + if: matrix.name == 'appleclang' + run: | + set -e + uname -m + clang++ --version | head -1 + for object in $(find out/build/${{ matrix.preset }} -name 'ConstantTime.cpp.o' -o -name 'ValueBarrierGnu.cpp.o'); do + echo "::group::otool -tvV -rv $object" + otool -tvV "$object" + # An object's calls are unresolved until the link: the relocations name their targets. + otool -rv "$object" + echo "::endgroup::" + done + - name: Test run: ctest --preset ${{ matrix.preset }} -LE tree-level diff --git a/docs/modules/base.md b/docs/modules/base.md index a8ea0ab1..5c35d416 100644 --- a/docs/modules/base.md +++ b/docs/modules/base.md @@ -13,6 +13,7 @@ fastcached's `src/FastCache/Core` at `ee71f868` (and `Sha256.hpp` at `8c27b162`) | `` | `Require()` and `Guarantee()`, which report through a replaceable fail handler (`core::setFailHandler()`) and abort; `core::todo()` and `core::unreachable()`; `core::throwOrFail()`, a `throw` where exceptions are compiled in and a `Require()`-style failure where they are not. The header builds with `-fno-exceptions` | | `` | `core::base64::encode()` and `decode()`, batch and streaming | | `` | `core::IClock`, the monotonic clock seam: `SteadyClock`, `ManualClock` (the test double), `defaultSteadyClock()` and the `SteadyTimePoint`/`SteadyDuration` types. Here rather than in [platform](platform.md#clocks) so that code linking nothing of the platform layer, the headless TUI, takes the same interface; `` names them in `core::platform` too | +| `` | `core::constantTimeEquals()`, a byte comparison without an early exit, and `core::secureZero()`, zeroing the optimizer may not remove; see [Constant time](#constant-time) below | | `` | generated by the configure: the version and the `CORE_CPP_WITH_*` switches, each 0 or 1 | | `` | `core::Deferred`, a value initialised once, after its owner | | `` | `CORE_PACKED`, `CORE_REQUIRES`, `CORE_CONSTEVAL`, `CORE_CONSTEXPR`, `CORE_LIFETIMEBOUND` (Clang's `[[clang::lifetimebound]]`, nothing elsewhere) | @@ -84,6 +85,25 @@ auto const text = core::toLowerHexString(digest); // 64 hex digits, : + 0: cmp %rcx,%rsi + 3: jne 3d + 10: test %rsi,%rsi + 13: je 40 + 20: movzbl (%rbx,%r12,1),%ecx + 25: xor (%r15,%r12,1),%cl + 29: or %al,%cl + 2e: call 33 + 33: inc %r12 + 36: cmp %r12,%r14 + 39: jne 20 + 3b: jmp 42 + 45: call 4a + 4c: sete %al + 5a: ret + +0000000000000060 )>: + 60: test %rsi,%rsi + 80: movb $0x0,(%rdi,%rcx,1) + ab: cmp %rcx,%rsi + ae: jne 80 +""" +) + +GCC = ( + HEAD + + f"""0000000000000000 <{SIGNATURE}>: + 2: cmp %rcx,%rsi + 5: jne 70 + 30: movzbl (%rbx),%edi + 33: xor (%r12),%dil + 3f: or %eax,%edi + 45: call 4a + 4a: cmp %rbp,%rbx + 4d: jne 30 + 60: call 65 + 67: sete %al + 6e: ret +""" +) + + +class ConstantTimeTest(unittest.TestCase): + def test_the_compilers_loops_are_accepted(self): + for name, listing in (("clang", CLANG), ("gcc", GCC)): + with self.subTest(name): + status, findings = CHECK.check_listing(listing) + self.assertEqual(status, 0, findings) + + def test_a_branch_on_the_data_in_the_loop_is_refused(self): + early = CLANG.replace( + " 29: or %al,%cl\n", " 29: or %al,%cl\n 2b: jne 3d \n" + ) + status, findings = CHECK.check_listing(early) + self.assertEqual(status, 1) + self.assertIn("branches on more than its index", findings[0]) + + def test_a_loop_without_its_barrier_is_refused(self): + bare = GCC.replace(" 45: call 4a \n", "") + status, findings = CHECK.check_listing(bare) + self.assertEqual(status, 1) + self.assertIn("calls no value barrier", findings[0]) + + def test_no_loop_is_refused(self): + unrolled = GCC.replace(" 4d: jne 30 \n", "") + status, _ = CHECK.check_listing(unrolled) + self.assertEqual(status, 1) + + def test_secure_zeros_loop_is_not_judged(self): + # Its back edge is another function's: only constantTimeEquals is held to the rule. + status, findings = CHECK.check_listing(CLANG) + self.assertEqual(len(findings), 1, findings) + + def test_an_aarch64_loop_is_judged_by_its_own_row(self): + listing = ( + HEAD.replace("elf64-x86-64", "elf64-littleaarch64") + + f"""0000000000000000 <{SIGNATURE}>: + 0: cmp x1, x3 + 4: b.ne 40 + 10: ldrb w8, [x2], #1 + 14: eor w0, w0, w8 + 18: bl 0 + 1c: subs x1, x1, #0x1 + 20: b.ne 10 +""" + ) + self.assertEqual(CHECK.check_listing(listing)[0], 0) + early = listing.replace(" 18:\tbl", " 16:\tcbnz\tw8, 40 \n 18:\tbl") + self.assertEqual(CHECK.check_listing(early)[0], 1) + + def test_a_listing_without_the_function_is_refused(self): + status, findings = CHECK.check_listing( + HEAD + "0000000000000000 )>:\n" + ) + self.assertEqual(status, 1) + self.assertIn("nothing was judged", findings[0]) + + def test_a_missing_objdump_object_or_unreadable_object_is_refused(self): + for arguments in ( + ["--objdump=/nonexistent/objdump", "--objects=ConstantTime.cpp.o"], + [f"--objdump={sys.executable}", "--objects=Other.cpp.o|More.cpp.o"], + [f"--objdump={sys.executable}", "--objects=/nonexistent/ConstantTime.cpp.o"], + ): + with self.subTest(arguments): + run = subprocess.run( + [sys.executable, str(CHECKER), *arguments], capture_output=True, text=True, check=False + ) + self.assertEqual(run.returncode, 1, run.stdout) + self.assertIn("REFUSED", run.stdout) + + def test_an_architecture_without_a_row_is_a_skip(self): + status, _ = CHECK.check_listing( + HEAD.replace("elf64-x86-64", "elf32-littleriscv") + CLANG[len(HEAD) :] + ) + self.assertEqual(status, CHECK.SKIP) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/check-constant-time.py b/scripts/check-constant-time.py new file mode 100644 index 00000000..420db877 --- /dev/null +++ b/scripts/check-constant-time.py @@ -0,0 +1,143 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +"""Holds core::constantTimeEquals to its guarantee in the code this build generated: its compare +loop branches on nothing but its index. + + python scripts/check-constant-time.py --objdump --objects "||..." + +It disassembles the object that defines core::constantTimeEquals (ConstantTime.cpp's, picked out +of the base library's objects), finds each loop of that function -- a conditional branch back to an +earlier address -- and refuses any loop whose body holds another conditional branch, or holds no +call (the value barrier): either is a compiler that found a way to stop at the first difference. +The branches before the loop (the length check) and after it are allowed; a length is public. + +**Toolchain dependence, said rather than hidden.** It reads GNU objdump's AT&T x86-64 and AArch64 +listings, which is what GCC and Clang builds on Linux, macOS (with binutils) and the BSDs produce; +it fails closed: no objdump, no ConstantTime.cpp object, an object objdump cannot read (LTO +bitcode among them, which no preset here builds), or no core::constantTimeEquals in it is a +failure, because each would otherwise read as a pass. The one skip (77) is an architecture whose +branch mnemonics it has no row for. The property is one of optimized code: a Debug build's bounds +assertions are branches in the loop, so the registration runs it only for an optimized build type. +""" + +from __future__ import annotations + +import argparse +import re +import subprocess +import sys +from pathlib import Path + +SKIP = 77 +FUNCTION = "core::constantTimeEquals(" + +# One row per architecture: what a conditional branch, an unconditional one and a call are. +ARCHITECTURES = { + "x86-64": { + "conditional": re.compile(r"^j(?!mp)[a-z]+$"), + "call": re.compile(r"^call[qw]?$"), + }, + "aarch64": { + "conditional": re.compile(r"^(b\.[a-z]+|cbn?z|tbn?z)$"), + "call": re.compile(r"^blr?$"), + }, +} + +INSTRUCTION = re.compile(r"^\s*([0-9a-f]+):\s+(?:[0-9a-f]{2}\s)*\s*([a-z][a-z0-9.]*)\s*(.*)$") +TARGET = re.compile(r"^(?:0x)?([0-9a-f]+)\b") + + +def architecture_of(listing: str) -> str | None: + """:return: the row of the listing's object format, or None for one without a row.""" + if "x86-64" in listing: + return "x86-64" + if "aarch64" in listing or "arm64" in listing: + return "aarch64" + return None + + +def function_body(listing: str) -> list[tuple[int, str, str]]: + """:return: (address, mnemonic, operands) of each instruction of constantTimeEquals.""" + body: list[tuple[int, str, str]] = [] + inside = False + for line in listing.splitlines(): + if re.match(r"^[0-9a-f]+ <", line): + inside = FUNCTION in line + continue + if not inside: + continue + match = INSTRUCTION.match(line) + if match: + body.append((int(match.group(1), 16), match.group(2), match.group(3))) + return body + + +def check_listing(listing: str) -> tuple[int, list[str]]: + """Judges one objdump listing. + + :return: (exit status, what it found): 0 and the loops it accepted, 1 and the refusals, or + 77 and why it could not judge. + """ + architecture = architecture_of(listing) + if architecture is None: + return SKIP, ["no branch table for this object's architecture"] + row = ARCHITECTURES[architecture] + body = function_body(listing) + if not body: + return 1, [f"no {FUNCTION}...) in the listing: nothing was judged"] + loops = [] + for address, mnemonic, operands in body: + target = TARGET.match(operands) + if row["conditional"].match(mnemonic) and target and int(target.group(1), 16) <= address: + loops.append((int(target.group(1), 16), address)) + if not loops: + return 1, ["no loop in constantTimeEquals: the compare was turned into something else"] + problems = [] + for start, end in loops: + inner = [(a, m) for a, m, _ in body if start <= a < end] + branches = [f"{a:x}: {m}" for a, m in inner if row["conditional"].match(m)] + calls = [m for _, m in inner if row["call"].match(m)] + if branches: + problems.append(f"loop {start:x}..{end:x} branches on more than its index: {', '.join(branches)}") + if not calls: + problems.append(f"loop {start:x}..{end:x} calls no value barrier") + if problems: + return 1, problems + return 0, [ + f"loop {start:x}..{end:x}: one back edge, a barrier call, no other branch" for start, end in loops + ] + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--objdump", default="") + parser.add_argument("--objects", default="", help="the base library's objects, '|'-separated") + arguments = parser.parse_args() + objects = [Path(o) for o in arguments.objects.split("|") if Path(o).name.startswith("ConstantTime.cpp.")] + if not arguments.objdump or not Path(arguments.objdump).exists(): + print(f"check-constant-time: REFUSED -- no objdump in this toolchain ({arguments.objdump!r})") + return 1 + if not objects: + print("check-constant-time: REFUSED -- no ConstantTime.cpp object among the base library's") + return 1 + disassembly = subprocess.run( + [arguments.objdump, "-d", "-C", "--no-show-raw-insn", str(objects[0])], + capture_output=True, + text=True, + check=False, + ) + if disassembly.returncode != 0: + print( + f"check-constant-time: REFUSED -- objdump could not read {objects[0]} (LTO bitcode?): " + f"{disassembly.stderr.strip()}" + ) + return 1 + status, findings = check_listing(disassembly.stdout) + verdict = {0: "ok", 1: "REFUSED", SKIP: "SKIPPED"}[status] + for finding in findings: + print(f"check-constant-time: {verdict} -- {finding}") + return status + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt index ca59b86c..98fb33d9 100644 --- a/src/core/CMakeLists.txt +++ b/src/core/CMakeLists.txt @@ -27,11 +27,21 @@ if(WIN32) list(APPEND _coreCppBaseWindowsLibs bcrypt) endif() +# The value and memory barriers behind core::constantTimeEquals and core::secureZero, one per +# compiler front end: GNU inline assembly where the front end has it (GCC, Clang, Emscripten, WASI), +# a volatile object under MSVC's (cl, clang-cl), which has no inline assembly on x64 or arm64. +if(CMAKE_CXX_COMPILER_FRONTEND_VARIANT STREQUAL "MSVC") + set(_coreCppBaseValueBarrier ValueBarrierMsvc.cpp) +else() + set(_coreCppBaseValueBarrier ValueBarrierGnu.cpp) +endif() + core_cpp_add_module(base KIND STATIC HEADERS Assert.hpp Base64.hpp Clock.hpp + ConstantTime.hpp Deferred.hpp Defines.hpp Environment.hpp @@ -54,12 +64,15 @@ core_cpp_add_module(base KIND STATIC SOURCES Assert.cpp Clock.cpp + ConstantTime.cpp Environment.cpp Random.cpp SystemRandomSource.hpp UserInfo.cpp Utf8Path.cpp Utils.cpp + ValueBarrier.hpp + ${_coreCppBaseValueBarrier} # One fillFromSystemRandom() per platform (core::systemRandom()): getentropy() on every POSIX # system, under Emscripten and under WASI (whose libc answers it from random_get), BCryptGenRandom() # on Windows. @@ -88,6 +101,7 @@ core_cpp_add_test(base SOURCES Base64_test.cpp Clock_test.cpp + ConstantTime_test.cpp Environment_test.cpp Escape_test.cpp Flags_test.cpp diff --git a/src/core/ConstantTime.cpp b/src/core/ConstantTime.cpp new file mode 100644 index 00000000..a2cb1db2 --- /dev/null +++ b/src/core/ConstantTime.cpp @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: Apache-2.0 +#include + +#include + +#include +#include +#include +#include + +namespace core +{ + +bool constantTimeEquals(std::span lhs, std::span rhs) noexcept +{ + // The length is public (see the header): only the bytes are compared in constant time. + if (lhs.size() != rhs.size()) + return false; + auto difference = std::uint8_t { 0 }; + for (auto const index: std::views::iota(std::size_t { 0 }, lhs.size())) + difference = detail::valueBarrier( + static_cast(difference | std::to_integer(lhs[index] ^ rhs[index]))); + return detail::valueBarrier(difference) == 0; +} + +void secureZero(std::span bytes) noexcept +{ + // Every store through a volatile lvalue is performed as written, needed or not. + auto* const target = static_cast(bytes.data()); + for (auto const index: std::views::iota(std::size_t { 0 }, bytes.size())) + target[index] = std::byte { 0 }; + detail::memoryBarrier(bytes.data()); +} + +} // namespace core diff --git a/src/core/ConstantTime.hpp b/src/core/ConstantTime.hpp new file mode 100644 index 00000000..35a4b074 --- /dev/null +++ b/src/core/ConstantTime.hpp @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// Byte comparison whose time does not depend on where the bytes differ, and zeroing a compiler +/// may not remove: for keys, MACs and signatures, where an early exit tells an attacker how many +/// leading bytes of a guess were right, and a dead store left a secret in memory. +/// +/// **What is guaranteed, and how.** Both functions are out of line, neither `constexpr` nor +/// `inline`, so no caller's optimizer sees through them. `constantTimeEquals` reads every byte of +/// both inputs, accumulates the XOR of each pair, and passes the accumulator through a value +/// barrier after every byte (an empty `asm volatile` that claims to change it, or a `volatile` +/// object under MSVC's front end), so the compiler can neither prove the result early nor turn the +/// loop into a search that stops at the first difference. Its time depends only on the length. +/// `secureZero` writes every byte through a `volatile` pointer and then passes the buffer through +/// a memory barrier, so the stores are neither elided as dead nor merged away. The barriers are +/// compiler barriers in themselves, not merely calls the optimizer cannot see into, so they hold +/// under link-time optimization too, where a call may be inlined after all. This holds against +/// the compiler; what a CPU does with a data-dependent load it never sees is outside it, and none +/// is made. +/// +/// **What is not hidden: the length.** Inputs of different lengths compare unequal at once. A MAC +/// or a key has a public, fixed length; compare equal-length values. +/// +/// That the compare loop has no data-dependent branch is a property of the generated code: it is +/// checked by reading the disassembly of the release builds, not by a unit test, which cannot see a +/// timing difference reliably. + +#include + +#include +#include + +namespace core +{ + +/// Compares @p lhs and @p rhs, every byte, without an early exit. A bool: the name asks the question. +/// @param lhs One value. +/// @param rhs The other. +/// @return Whether both have the same length and the same bytes; false on a length difference, at once. +[[nodiscard]] CORE_BASE_API bool constantTimeEquals(std::span lhs, + std::span rhs) noexcept; + +/// Overwrites @p bytes with zeros; the stores survive optimization (volatile writes and a memory +/// barrier, out of line), even when the buffer is never read again. +/// @param bytes What to clear. +CORE_BASE_API void secureZero(std::span bytes) noexcept; + +} // namespace core diff --git a/src/core/ConstantTime_test.cpp b/src/core/ConstantTime_test.cpp new file mode 100644 index 00000000..fb653875 --- /dev/null +++ b/src/core/ConstantTime_test.cpp @@ -0,0 +1,96 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// What a unit test can see of the constant-time helpers: the answers. That the comparison takes the +// same time for every pair of equal-length inputs is a property of the code generated, held by +// construction (see ConstantTime.hpp) and checked by reading the disassembly, not by a clock. +#include + +#include + +#include +#include +#include +#include +#include + +using core::constantTimeEquals; +using core::secureZero; + +namespace +{ + +[[nodiscard]] std::vector filled(std::size_t size, std::byte value) +{ + return std::vector(size, value); +} + +} // namespace + +TEST_CASE("constantTimeEquals compares every byte and the length", "[base][constant-time]") +{ + auto const reference = filled(32, std::byte { 0x5A }); + SECTION("equal") + { + CHECK(constantTimeEquals(reference, filled(32, std::byte { 0x5A }))); + } + SECTION("the last byte differs") + { + auto other = reference; + other.back() = std::byte { 0x5B }; + CHECK_FALSE(constantTimeEquals(reference, other)); + } + SECTION("the first byte differs") + { + auto other = reference; + other.front() = std::byte { 0x00 }; + CHECK_FALSE(constantTimeEquals(reference, other)); + } + SECTION("a single bit differs in the middle") + { + auto other = reference; + other[16] ^= std::byte { 0x80 }; + CHECK_FALSE(constantTimeEquals(reference, other)); + } + SECTION("different lengths, one a prefix of the other") + { + auto const longer = filled(33, std::byte { 0x5A }); + CHECK_FALSE(constantTimeEquals(reference, longer)); + CHECK_FALSE(constantTimeEquals(longer, reference)); + } + SECTION("both empty") + { + CHECK(constantTimeEquals(std::span {}, std::span {})); + } + SECTION("one empty") + { + CHECK_FALSE(constantTimeEquals(std::span {}, reference)); + } +} + +TEST_CASE("secureZero clears every byte", "[base][constant-time]") +{ + SECTION("a 64-byte buffer") + { + auto buffer = filled(64, std::byte { 0xA5 }); + secureZero(buffer); + CHECK(std::ranges::all_of(buffer, [](std::byte value) { return value == std::byte { 0 }; })); + } + SECTION("an array on the stack, and only the span given") + { + auto buffer = std::array {}; + std::ranges::fill(buffer, std::byte { 0xA5 }); + secureZero(std::span { buffer }.first(4)); + CHECK(std::ranges::all_of(std::span { buffer }.first(4), + [](std::byte value) { return value == std::byte { 0 }; })); + CHECK(std::ranges::all_of(std::span { buffer }.last(4), + [](std::byte value) { return value == std::byte { 0xA5 }; })); + } + SECTION("an empty span touches nothing") + { + auto buffer = std::array {}; + std::ranges::fill(buffer, std::byte { 0xA5 }); + secureZero(std::span { buffer }.first(0)); + secureZero(std::span {}); + CHECK(std::ranges::all_of(buffer, [](std::byte value) { return value == std::byte { 0xA5 }; })); + } +} diff --git a/src/core/ValueBarrier.hpp b/src/core/ValueBarrier.hpp new file mode 100644 index 00000000..f53ab25d --- /dev/null +++ b/src/core/ValueBarrier.hpp @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// The barriers ConstantTime.cpp is built on, one definition per compiler front end, chosen by CMake +/// (`ValueBarrierGnu.cpp` for GCC and Clang, `ValueBarrierMsvc.cpp` for MSVC and clang-cl). Each is +/// out of line in a source of its own, so no caller can see that it changes nothing. Private to +/// the base module. + +#include + +namespace core::detail +{ + +/// @param value Any value. +/// @return @p value, which the compiler must treat as unknown: nothing about it is proven across +/// the call. +[[nodiscard]] std::uint8_t valueBarrier(std::uint8_t value) noexcept; + +/// Makes the compiler assume the memory behind @p memory is read here, so stores to it before the +/// call are neither elided nor sunk past it. +/// @param memory The start of the memory. +void memoryBarrier(void const* memory) noexcept; + +} // namespace core::detail diff --git a/src/core/ValueBarrierGnu.cpp b/src/core/ValueBarrierGnu.cpp new file mode 100644 index 00000000..9ce1e3ff --- /dev/null +++ b/src/core/ValueBarrierGnu.cpp @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The barriers for the GNU front end (GCC, Clang, Apple Clang, Emscripten, WASI): an empty asm +// statement that the compiler must assume reads and changes its operand, or reads all memory. +#include + +#include + +namespace core::detail +{ + +std::uint8_t valueBarrier(std::uint8_t value) noexcept +{ + asm volatile("" : "+r"(value)); + return value; +} + +void memoryBarrier(void const* memory) noexcept +{ + asm volatile("" : : "r"(memory) : "memory"); +} + +} // namespace core::detail diff --git a/src/core/ValueBarrierMsvc.cpp b/src/core/ValueBarrierMsvc.cpp new file mode 100644 index 00000000..604ca385 --- /dev/null +++ b/src/core/ValueBarrierMsvc.cpp @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The barriers for MSVC's front end (cl and clang-cl), which has no GNU inline assembly on x64 or +// arm64. The value barrier is a volatile object, whose every read and write the compiler must +// perform as written, so a value passed through one is unknown to it afterwards. A volatile access +// orders only other volatile accesses, so the memory barrier is a signal fence: a compiler fence +// that emits no instruction and keeps every memory access before it from being sunk past it, with +// the pointer stored to a volatile object first so the memory it names is taken to escape. +#include + +#include +#include + +namespace core::detail +{ + +std::uint8_t valueBarrier(std::uint8_t value) noexcept +{ + auto volatile hidden = value; + return hidden; +} + +void memoryBarrier(void const* memory) noexcept +{ + auto const* volatile hidden = memory; + static_cast(hidden); + std::atomic_signal_fence(std::memory_order_seq_cst); +} + +} // namespace core::detail diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 920eac35..0af1870c 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -614,6 +614,39 @@ endif() set_tests_properties(core-cpp.text-encoding core-cpp.text-encoding-selftest PROPERTIES LABELS "core-cpp;hygiene;tree-level" TIMEOUT 60) +# core::constantTimeEquals branches on nothing but its index, in the code this build generated +# (ConstantTime.hpp): scripts/check-constant-time.py disassembles ConstantTime.cpp's object with +# objdump and refuses a compare loop holding another conditional branch or no barrier call. It is a +# fact about an optimized build, since a Debug build's bounds assertions are branches in the loop, +# and it reads GNU objdump's x86-64 and AArch64 listings: it runs for the GNU front end's optimized +# builds and says why it did not run anywhere else (MSVC's front end, Debug, no objdump, another +# architecture, Apple: Apple's objdump lists a Mach-O object's functions under local labels, `ltmp0`, +# so no listing there names constantTimeEquals; Emscripten and WASI, whose objects are WebAssembly). NOT tree-level: its input is this build's object. Its self-test judges planted +# listings, so its answer cannot differ between platforms: tree-level, run by the `style` job. +if(Python3_Interpreter_FOUND AND TARGET core-cpp-base AND NOT CMAKE_CXX_COMPILER_FRONTEND_VARIANT STREQUAL "MSVC" + AND NOT APPLE AND NOT CMAKE_SYSTEM_NAME MATCHES "^(Emscripten|WASI)$" + AND CMAKE_BUILD_TYPE MATCHES "^(Release|RelWithDebInfo|MinSizeRel)$") + add_test(NAME core-cpp.constant-time + COMMAND "${Python3_EXECUTABLE}" "${CORE_CPP_SOURCE_DIR}/scripts/check-constant-time.py" + "--objdump=${CMAKE_OBJDUMP}" + "--objects=$,|>") + set_tests_properties(core-cpp.constant-time PROPERTIES SKIP_RETURN_CODE ${CORE_CPP_SKIP_EXIT_CODE}) +else() + add_test(NAME core-cpp.constant-time COMMAND "${CMAKE_COMMAND}" -E echo + "core-cpp.constant-time: SKIPPED -- it judges a GNU front end's optimized ELF build with Python 3, and this is not one") + set_tests_properties(core-cpp.constant-time PROPERTIES SKIP_REGULAR_EXPRESSION "SKIPPED") +endif() +set_tests_properties(core-cpp.constant-time PROPERTIES LABELS "core-cpp;hygiene" TIMEOUT 60) +if(Python3_Interpreter_FOUND) + add_test(NAME core-cpp.constant-time-selftest + COMMAND "${Python3_EXECUTABLE}" "${CORE_CPP_SOURCE_DIR}/scripts/check-constant-time-selftest.py") +else() + add_test(NAME core-cpp.constant-time-selftest COMMAND "${CMAKE_COMMAND}" -E echo + "core-cpp.constant-time-selftest: SKIPPED -- no Python 3 interpreter was found at configure time") + set_tests_properties(core-cpp.constant-time-selftest PROPERTIES SKIP_REGULAR_EXPRESSION "SKIPPED") +endif() +set_tests_properties(core-cpp.constant-time-selftest PROPERTIES LABELS "core-cpp;hygiene;tree-level" TIMEOUT 60) + # Outside a git checkout (a source archive) the check cannot tell which files are the tree's. set_tests_properties(core-cpp.text-encoding PROPERTIES SKIP_RETURN_CODE 77) From 4d7bd5ef1afcd8882a61c4d5ca7a0f558b8b8b46 Mon Sep 17 00:00:00 2001 From: Christian Parpart Date: Fri, 27 Nov 2026 06:16:05 +0100 Subject: [PATCH 16/19] feat(platform): cacheHome core::platform::cacheHome reads XDG_CACHE_HOME, then LOCALAPPDATA, then the OS's row below the home directory: ~/.cache on Linux and the BSDs, ~/Library/Caches on macOS, ~/AppData/Local on Windows, from a CMake-selected source per OS, with per-OS test cases selected the same way. An empty, non-UTF-8 or relative variable counts as unset, and a relative home names no cache, so the answer is always absolute. Also in this commit: - put the SystemPipe comment back above the libraries it explains Signed-off-by: Christian Parpart --- .agent/reference/provenance.md | 7 ++++ docs/modules/platform.md | 15 ++++++-- src/core/platform/CMakeLists.txt | 18 +++++++++ src/core/platform/UserPaths.hpp | 34 +++++++++++++++++ src/core/platform/UserPathsTestSupport.hpp | 31 +++++++++++++++ src/core/platform/UserPaths_test.cpp | 10 +++++ .../platform/darwin/CacheHomeCases_test.cpp | 35 +++++++++++++++++ src/core/platform/darwin/CacheHomeRow.cpp | 16 ++++++++ .../platform/posix/CacheHomeCases_test.cpp | 38 +++++++++++++++++++ src/core/platform/posix/CacheHomeRow.cpp | 17 +++++++++ .../platform/windows/CacheHomeCases_test.cpp | 35 +++++++++++++++++ src/core/platform/windows/CacheHomeRow.cpp | 17 +++++++++ 12 files changed, 269 insertions(+), 4 deletions(-) create mode 100644 src/core/platform/UserPathsTestSupport.hpp create mode 100644 src/core/platform/darwin/CacheHomeCases_test.cpp create mode 100644 src/core/platform/darwin/CacheHomeRow.cpp create mode 100644 src/core/platform/posix/CacheHomeCases_test.cpp create mode 100644 src/core/platform/posix/CacheHomeRow.cpp create mode 100644 src/core/platform/windows/CacheHomeCases_test.cpp create mode 100644 src/core/platform/windows/CacheHomeRow.cpp diff --git a/.agent/reference/provenance.md b/.agent/reference/provenance.md index 71b09e92..33b44602 100644 --- a/.agent/reference/provenance.md +++ b/.agent/reference/provenance.md @@ -392,6 +392,13 @@ others in notes. | `src/core/platform/PlatformTestSupport.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): `runsUnderWine` for the platform tests | | `src/core/platform/posix/PlatformTestSupport.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): `runsUnderWine` on POSIX | | `src/core/platform/windows/PlatformTestSupport.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): `runsUnderWine` on Windows | +| `src/core/platform/UserPathsTestSupport.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): the per-OS `cacheHome` cases' declaration | +| `src/core/platform/darwin/CacheHomeCases_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/platform/darwin/CacheHomeRow.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): macOS's cache row | +| `src/core/platform/posix/CacheHomeCases_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/platform/posix/CacheHomeRow.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the XDG cache row | +| `src/core/platform/windows/CacheHomeCases_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/platform/windows/CacheHomeRow.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): Windows' cache row | | `src/core/testing/windows/SuppressWindowsDialogs_test.cpp` | origin: core-cpp | - | - | 0.3.0: reads back from WerGetFlags that suppressWindowsDialogs() asked Windows Error Reporting for no UI | | `src/core/net/CallbackAllocation_test.cpp` | origin: core-cpp | - | - | 0.3.0 review: a drain-step callback that queues nothing costs no allocation, measured by replacing the global allocation functions, which is why it is a binary of its own | | `src/core/net/CompletionClaim_test.cpp` | origin: core-cpp | - | - | 0.4.0: the claim a frame-free completion queues for a chain nobody owns -- counted, armed, holding no reference -- and its free at teardown and take-back; a `[bench]` case for the completion path | diff --git a/docs/modules/platform.md b/docs/modules/platform.md index 1ca0296d..45625d59 100644 --- a/docs/modules/platform.md +++ b/docs/modules/platform.md @@ -27,7 +27,7 @@ the interrupt throttle. | `` | `FileInfoProvider`, a directory listing with `stat(2)` metadata (`FileEntry`), a single file or a glob pattern | | `` | `ProcessEnvironment`, a `core::Environment` a shell writes: variables with a set-then-export model, each write a `std::expected`; `isValidEnvironmentName()` | | `` | `WorkingDirectory`: `changeDirectory()` and `currentDirectory()`, both over `std::filesystem::path`, so the answer round-trips on Windows whatever it spells | -| `` | `homeDirectory()`, `userName()` and `configHome()` over a `core::Environment`, by default the process environment | +| `` | `homeDirectory()`, `userName()`, `configHome()` and `cacheHome()` over a `core::Environment`, by default the process environment | | `` | path spelling: `normalizePath()`, `joinPath()`, `absolutePath()`, `canonicalCasePath()`, `stripTrailingSeparator()`, `isCaseOnlyRename()`, `resolveDevicePath()` | | `` | `globMatchFilename()` (`*`, `?`, `[...]`) and `containsGlobChars()` | | `` | RFC 3986 percent-encoding and RFC 8089 `file://` URIs | @@ -231,10 +231,17 @@ dispatch needs it, and its `dispatch()` is the `noexcept` boundary of the except that is not UTF-8. - **`UserPaths` reads through a `core::Environment`**, so a test passes a `core::testing::FakeEnvironment`. Its default argument is a `core::LiveEnvironment`, so - `homeDirectory()`, `userName()` and `configHome()` called without one read the process environment (on - Windows the operating system's block) through the same body the tests run. A directory variable - that is not UTF-8 names no directory on Windows, so it counts as unset there + `homeDirectory()`, `userName()`, `configHome()` and `cacheHome()` called without one read the process + environment (on Windows the operating system's block) through the same body the tests run. A + directory variable that is not UTF-8 names no directory on Windows, so it counts as unset there (`core::pathFromUtf8()`, in [base](base.md#paths-and-utf-8)). +- **`cacheHome()` answers an absolute path or none.** It reads `XDG_CACHE_HOME`, then + `LOCALAPPDATA`, then falls back to the operating system's row below the home directory: + `~/.cache` on Linux and the BSDs, `~/Library/Caches` on macOS, `~/AppData/Local` on Windows. The + row comes from a source CMake selects per OS, and each OS's test cases are selected the same way. + An empty, non-UTF-8 or relative variable counts as unset, as the XDG Base Directory specification + says, and a relative home directory names no cache, so a cache never lands below the working + directory. - **`Wakeup`'s constructor throws** `std::runtime_error` when the operating system refuses the eventfd, self-pipe or event, which it does only when descriptors, handles or kernel memory are exhausted. That is unrecoverable, since no event loop can run without its wakeup channel, so it diff --git a/src/core/platform/CMakeLists.txt b/src/core/platform/CMakeLists.txt index 34661ba5..fe6c7878 100644 --- a/src/core/platform/CMakeLists.txt +++ b/src/core/platform/CMakeLists.txt @@ -72,6 +72,20 @@ else() set(_coreCppPlatformSystemPowerSource UnavailableSystemPower.cpp) endif() +# Where a user's caches live below the home directory (core::platform::cacheHome), one row per OS, +# and the cases that hold each OS to its own row: macOS's ~/Library/Caches, Windows' AppData/Local, +# and every other system's ~/.cache (the XDG default). An Emscripten build answers as POSIX does. +if(APPLE) + set(_coreCppPlatformCacheHomeRow darwin/CacheHomeRow.cpp) + set(_coreCppPlatformCacheHomeCases darwin/CacheHomeCases_test.cpp) +elseif(WIN32) + set(_coreCppPlatformCacheHomeRow windows/CacheHomeRow.cpp) + set(_coreCppPlatformCacheHomeCases windows/CacheHomeCases_test.cpp) +else() + set(_coreCppPlatformCacheHomeRow posix/CacheHomeRow.cpp) + set(_coreCppPlatformCacheHomeCases posix/CacheHomeCases_test.cpp) +endif() + # Sockets back SystemPipe on Windows: a loopback pair mapped to a waitable event. set(_coreCppPlatformLibs "") if(APPLE) @@ -134,6 +148,7 @@ core_cpp_add_module(platform KIND STATIC ${_coreCppPlatformSystemPowerSource} WinsockInit.cpp testing/InMemoryFileSystem.cpp + ${_coreCppPlatformCacheHomeRow} SOURCES_POSIX ${_coreCppPlatformPosixProviders} posix/PosixDurableFiles.cpp @@ -158,6 +173,7 @@ core_cpp_add_module(platform KIND STATIC ${_coreCppPlatformCpuCounterSource} SystemPower.cpp ${_coreCppPlatformSystemPowerSource} + ${_coreCppPlatformCacheHomeRow} PUBLIC_LIBS core::base PRIVATE_LIBS ${_coreCppPlatformLibs}) @@ -187,6 +203,8 @@ core_cpp_add_test(platform SystemPipe_test.cpp SystemPower_test.cpp UserPaths_test.cpp + UserPathsTestSupport.hpp + ${_coreCppPlatformCacheHomeCases} Wakeup_test.cpp DEFINITIONS ${_coreCppPlatformPowerDefinitions} SOURCES_WINDOWS diff --git a/src/core/platform/UserPaths.hpp b/src/core/platform/UserPaths.hpp index 5aacf6a9..86fab630 100644 --- a/src/core/platform/UserPaths.hpp +++ b/src/core/platform/UserPaths.hpp @@ -3,11 +3,13 @@ #include #include +#include #include #include #include #include +#include #include namespace core::platform @@ -69,4 +71,36 @@ namespace core::platform return std::nullopt; } +namespace detail +{ + /// Where this OS keeps a user's caches below the home directory, `/`-separated, when no + /// variable names them: `.cache` (the XDG default; Linux, the BSDs), `Library/Caches` (macOS), + /// `AppData/Local` (Windows). Defined by a CMake-selected source per OS. + /// @return The row. + [[nodiscard]] CORE_PLATFORM_API std::string_view cacheHomeBelowHome() noexcept; +} // namespace detail + +/// @brief Returns the user's cache base directory. +/// +/// $XDG_CACHE_HOME, then %LOCALAPPDATA%, then the OS's row below homeDirectory(): ~/.cache (Linux, +/// FreeBSD), ~/Library/Caches (macOS), ~/AppData/Local (Windows). Each variable is read as UTF-8, as +/// for homeDirectory(); an empty one, one that is not UTF-8, or **a relative one counts as unset**, +/// as the XDG Base Directory specification says, so a cache never lands below the working directory. +/// A relative home directory names no cache. +/// +/// @param environment The environment to read the variables from: by default the process +/// environment as it is now, and in a test a fake one. +/// @return The absolute cache directory path, or std::nullopt if it cannot be determined. +[[nodiscard]] inline auto cacheHome(core::Environment const& environment = core::LiveEnvironment {}) + -> std::optional +{ + for (auto const* const name: { "XDG_CACHE_HOME", "LOCALAPPDATA" }) + if (auto const value = environment.get(name); value && !value->empty()) + if (auto path = core::pathFromUtf8(*value); path && path->is_absolute()) + return *std::move(path); + if (auto home = homeDirectory(environment); home && home->is_absolute()) + return *home / std::filesystem::path { detail::cacheHomeBelowHome() }; // ASCII: no conversion to fail + return std::nullopt; +} + } // namespace core::platform diff --git a/src/core/platform/UserPathsTestSupport.hpp b/src/core/platform/UserPathsTestSupport.hpp new file mode 100644 index 00000000..6a93a9ee --- /dev/null +++ b/src/core/platform/UserPathsTestSupport.hpp @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// The rows `cacheHome` is held to, one table per operating system: each is defined in a +/// CMake-selected `*/CacheHomeCases_test.cpp`, since what an absolute path looks like, and the row +/// below the home directory, differ per OS. Test-only; never part of the module. + +#include +#include +#include +#include +#include +#include +#include + +namespace core::platform::test +{ + +/// One environment and the cache directory it gives. +struct CacheHomeCase +{ + std::string_view name; ///< What the row is about. + std::map> environment; ///< The variables set; every other is unset. + std::optional expected; ///< What cacheHome answers. +}; + +/// @return This operating system's rows. +[[nodiscard]] std::vector cacheHomeCases(); + +} // namespace core::platform::test diff --git a/src/core/platform/UserPaths_test.cpp b/src/core/platform/UserPaths_test.cpp index edb7c1e1..4a3e8074 100644 --- a/src/core/platform/UserPaths_test.cpp +++ b/src/core/platform/UserPaths_test.cpp @@ -1,5 +1,6 @@ // SPDX-License-Identifier: Apache-2.0 #include +#include #include #include @@ -153,3 +154,12 @@ TEST_CASE("userName.none_set", "[platform]") static_assert(requires { homeDirectory(); }); static_assert(requires { configHome(); }); static_assert(requires { userName(); }); + +TEST_CASE("cacheHome follows XDG_CACHE_HOME, LOCALAPPDATA, then the OS row", "[platform]") +{ + for (auto const& row: core::platform::test::cacheHomeCases()) + { + INFO(row.name); + CHECK(core::platform::cacheHome(FakeEnvironment { row.environment }) == row.expected); + } +} diff --git a/src/core/platform/darwin/CacheHomeCases_test.cpp b/src/core/platform/darwin/CacheHomeCases_test.cpp new file mode 100644 index 00000000..223283b5 --- /dev/null +++ b/src/core/platform/darwin/CacheHomeCases_test.cpp @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// cacheHome's rows on macOS: ~/Library/Caches below HOME, after the variables. +#include + +#include + +namespace core::platform::test +{ + +std::vector cacheHomeCases() +{ + return { + { .name = "XDG_CACHE_HOME first, on macOS too", + .environment = { { "XDG_CACHE_HOME", "/x/cache" }, + { "LOCALAPPDATA", "/x/local" }, + { "HOME", "/x/home" } }, + .expected = "/x/cache" }, + { .name = "an empty XDG_CACHE_HOME is unset: LOCALAPPDATA", + .environment = { { "XDG_CACHE_HOME", "" }, { "LOCALAPPDATA", "/x/local" }, { "HOME", "/x/home" } }, + .expected = "/x/local" }, + { .name = "a relative XDG_CACHE_HOME is ignored", + .environment = { { "XDG_CACHE_HOME", "cache" }, { "HOME", "/x/home" } }, + .expected = "/x/home/Library/Caches" }, + { .name = "the OS row: ~/Library/Caches", + .environment = { { "HOME", "/x/home" } }, + .expected = "/x/home/Library/Caches" }, + { .name = "a relative HOME names no cache", + .environment = { { "HOME", "home" } }, + .expected = std::nullopt }, + { .name = "nothing set", .environment = {}, .expected = std::nullopt }, + }; +} + +} // namespace core::platform::test diff --git a/src/core/platform/darwin/CacheHomeRow.cpp b/src/core/platform/darwin/CacheHomeRow.cpp new file mode 100644 index 00000000..8d5dbde0 --- /dev/null +++ b/src/core/platform/darwin/CacheHomeRow.cpp @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// Where a user's caches live below the home directory: macOS's per-user caches. +#include + +#include + +namespace core::platform::detail +{ + +std::string_view cacheHomeBelowHome() noexcept +{ + return "Library/Caches"; +} + +} // namespace core::platform::detail diff --git a/src/core/platform/posix/CacheHomeCases_test.cpp b/src/core/platform/posix/CacheHomeCases_test.cpp new file mode 100644 index 00000000..b9962b35 --- /dev/null +++ b/src/core/platform/posix/CacheHomeCases_test.cpp @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// cacheHome's rows on Linux, FreeBSD and every other POSIX system but macOS: ~/.cache below HOME. +#include + +#include + +namespace core::platform::test +{ + +std::vector cacheHomeCases() +{ + return { + { .name = "XDG_CACHE_HOME first", + .environment = { { "XDG_CACHE_HOME", "/x/cache" }, + { "LOCALAPPDATA", "/x/local" }, + { "HOME", "/x/home" } }, + .expected = "/x/cache" }, + { .name = "an empty XDG_CACHE_HOME is unset: LOCALAPPDATA", + .environment = { { "XDG_CACHE_HOME", "" }, { "LOCALAPPDATA", "/x/local" }, { "HOME", "/x/home" } }, + .expected = "/x/local" }, + { .name = "a relative XDG_CACHE_HOME is ignored, as the XDG specification says", + .environment = { { "XDG_CACHE_HOME", "cache" }, { "HOME", "/x/home" } }, + .expected = "/x/home/.cache" }, + { .name = "a relative LOCALAPPDATA is ignored too", + .environment = { { "LOCALAPPDATA", "local" }, { "HOME", "/x/home" } }, + .expected = "/x/home/.cache" }, + { .name = "the OS row: ~/.cache", + .environment = { { "HOME", "/x/home" } }, + .expected = "/x/home/.cache" }, + { .name = "a relative HOME names no cache", + .environment = { { "HOME", "home" } }, + .expected = std::nullopt }, + { .name = "nothing set", .environment = {}, .expected = std::nullopt }, + }; +} + +} // namespace core::platform::test diff --git a/src/core/platform/posix/CacheHomeRow.cpp b/src/core/platform/posix/CacheHomeRow.cpp new file mode 100644 index 00000000..9c484f22 --- /dev/null +++ b/src/core/platform/posix/CacheHomeRow.cpp @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// Where a user's caches live below the home directory: the XDG Base Directory default, on Linux, the BSDs and +// every POSIX system but macOS. +#include + +#include + +namespace core::platform::detail +{ + +std::string_view cacheHomeBelowHome() noexcept +{ + return ".cache"; +} + +} // namespace core::platform::detail diff --git a/src/core/platform/windows/CacheHomeCases_test.cpp b/src/core/platform/windows/CacheHomeCases_test.cpp new file mode 100644 index 00000000..623f4440 --- /dev/null +++ b/src/core/platform/windows/CacheHomeCases_test.cpp @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// cacheHome's rows on Windows: %LOCALAPPDATA%, and AppData/Local below the profile where it is unset. +#include + +#include + +namespace core::platform::test +{ + +std::vector cacheHomeCases() +{ + return { + { .name = "XDG_CACHE_HOME first, where a user set it", + .environment = { { "XDG_CACHE_HOME", "C:/x/cache" }, + { "LOCALAPPDATA", "C:/Users/u/AppData/Local" }, + { "USERPROFILE", "C:/Users/u" } }, + .expected = "C:/x/cache" }, + { .name = "LOCALAPPDATA", + .environment = { { "LOCALAPPDATA", "C:/Users/u/AppData/Local" }, { "USERPROFILE", "C:/Users/u" } }, + .expected = "C:/Users/u/AppData/Local" }, + { .name = "a drive-relative LOCALAPPDATA is ignored", + .environment = { { "LOCALAPPDATA", "/Users/u/AppData/Local" }, { "USERPROFILE", "C:/Users/u" } }, + .expected = "C:/Users/u/AppData/Local" }, + { .name = "the OS row: AppData/Local below the profile", + .environment = { { "USERPROFILE", "C:/Users/u" } }, + .expected = "C:/Users/u/AppData/Local" }, + { .name = "a relative profile names no cache", + .environment = { { "USERPROFILE", "Users/u" } }, + .expected = std::nullopt }, + { .name = "nothing set", .environment = {}, .expected = std::nullopt }, + }; +} + +} // namespace core::platform::test diff --git a/src/core/platform/windows/CacheHomeRow.cpp b/src/core/platform/windows/CacheHomeRow.cpp new file mode 100644 index 00000000..389f7d70 --- /dev/null +++ b/src/core/platform/windows/CacheHomeRow.cpp @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// Where a user's caches live below the home directory: where %LOCALAPPDATA% points on every Windows since +// Vista. +#include + +#include + +namespace core::platform::detail +{ + +std::string_view cacheHomeBelowHome() noexcept +{ + return "AppData/Local"; +} + +} // namespace core::platform::detail From f9b33abfe5b11dddda2752b5121112fe414dbe11 Mon Sep 17 00:00:00 2001 From: Christian Parpart Date: Fri, 27 Nov 2026 06:15:56 +0100 Subject: [PATCH 17/19] feat(fs): owner-only creation and an access scope read on the handle OpenFlags::OwnerOnly and createDirectoryAt's new CreationAccess make a file or directory the owner's alone from the moment it exists: POSIX hands 0600/0700 to openat and mkdirat themselves; Windows hands NtCreateFile a security descriptor owned by the process token's user with a protected DACL granting that user alone, so an elevated process's file stays the user's. DescriptorStat::access reports who may reach an object, read from the very handle: fstat on Linux, plus the NFSv4 ACL on FreeBSD, the extended ACL on macOS, and the owner and DACL on Windows, where every stat open now asks READ_CONTROL. One CMake-selected reader per OS fills AccessFacts; classifyAccess decides from them, the same table on every OS. createDirectoryAt gains its CreationAccess parameter before v0.24.0 ships, so no consumer breaks. Also in this commit: - owner-only holds from creation on every platform, and a stat survives a DACL without READ_CONTROL - stage owner-only creations on macOS and FreeBSD, so no inherited ACL is ever live - hold the staged placeholder owner-only and draw staging names from a key - include windows.h in AccessFacts.hpp as NtFile.hpp does Signed-off-by: Christian Parpart --- .agent/reference/provenance.md | 20 + .github/workflows/build.yml | 4 + src/core/fs/AccessScope.cpp | 61 +++ src/core/fs/AccessScope.hpp | 108 +++++ src/core/fs/AccessScope_test.cpp | 143 ++++++ src/core/fs/CMakeLists.txt | 44 +- src/core/fs/Descriptor.hpp | 44 +- src/core/fs/DescriptorContract_test.cpp | 178 +++++++- src/core/fs/DescriptorEscape_test.cpp | 9 +- src/core/fs/DescriptorTestSupport.hpp | 20 +- src/core/fs/DirectoryStream_test.cpp | 12 +- src/core/fs/NativeDescriptor_test.cpp | 12 +- src/core/fs/Rights.cpp | 8 +- src/core/fs/Rights.hpp | 7 +- src/core/fs/bsd/AccessFacts.cpp | 97 ++++ src/core/fs/bsd/InheritableAcl_test.cpp | 19 + src/core/fs/darwin/AccessFacts.cpp | 110 +++++ src/core/fs/darwin/InheritableAcl_test.cpp | 21 + src/core/fs/detail/NativeSupport.cpp | 8 +- src/core/fs/detail/NativeSupport.hpp | 16 +- src/core/fs/posix/AccessFacts.cpp | 38 ++ src/core/fs/posix/DescriptorTestSupport.cpp | 14 + src/core/fs/posix/InheritableAcl.hpp | 22 + src/core/fs/posix/InheritableAcl_test.cpp | 19 + src/core/fs/posix/OwnerOnlyCreation.cpp | 310 +++++++++++++ src/core/fs/posix/OwnerOnlyCreation.hpp | 100 ++++ src/core/fs/posix/OwnerOnly_test.cpp | 429 ++++++++++++++++++ src/core/fs/posix/PosixDescriptor.cpp | 84 +++- src/core/fs/posix/PosixSystem.hpp | 37 ++ .../testing/InMemoryDescriptorFileSystem.cpp | 68 ++- .../testing/InMemoryDescriptorFileSystem.hpp | 10 + src/core/fs/windows/AccessFacts.cpp | 133 ++++++ src/core/fs/windows/AccessFacts.hpp | 34 ++ src/core/fs/windows/DescriptorEscape_test.cpp | 5 +- src/core/fs/windows/DescriptorTestSupport.cpp | 19 + src/core/fs/windows/NtFile.hpp | 6 +- src/core/fs/windows/OwnerOnly_test.cpp | 426 +++++++++++++++++ src/core/fs/windows/OwnerSecurity.cpp | 116 +++++ src/core/fs/windows/OwnerSecurity.hpp | 68 +++ src/core/fs/windows/WindowsDescriptor.cpp | 166 +++++-- 40 files changed, 2920 insertions(+), 125 deletions(-) create mode 100644 src/core/fs/AccessScope.cpp create mode 100644 src/core/fs/AccessScope.hpp create mode 100644 src/core/fs/AccessScope_test.cpp create mode 100644 src/core/fs/bsd/AccessFacts.cpp create mode 100644 src/core/fs/bsd/InheritableAcl_test.cpp create mode 100644 src/core/fs/darwin/AccessFacts.cpp create mode 100644 src/core/fs/darwin/InheritableAcl_test.cpp create mode 100644 src/core/fs/posix/AccessFacts.cpp create mode 100644 src/core/fs/posix/DescriptorTestSupport.cpp create mode 100644 src/core/fs/posix/InheritableAcl.hpp create mode 100644 src/core/fs/posix/InheritableAcl_test.cpp create mode 100644 src/core/fs/posix/OwnerOnlyCreation.cpp create mode 100644 src/core/fs/posix/OwnerOnlyCreation.hpp create mode 100644 src/core/fs/posix/OwnerOnly_test.cpp create mode 100644 src/core/fs/windows/AccessFacts.cpp create mode 100644 src/core/fs/windows/AccessFacts.hpp create mode 100644 src/core/fs/windows/DescriptorTestSupport.cpp create mode 100644 src/core/fs/windows/OwnerOnly_test.cpp create mode 100644 src/core/fs/windows/OwnerSecurity.cpp create mode 100644 src/core/fs/windows/OwnerSecurity.hpp diff --git a/.agent/reference/provenance.md b/.agent/reference/provenance.md index 33b44602..5ff281d3 100644 --- a/.agent/reference/provenance.md +++ b/.agent/reference/provenance.md @@ -160,6 +160,9 @@ others in notes. | `src/core/codec/Stream.cpp` | contour-terminal/contour | `src/vtbackend/state/StateCodec.cpp` | `3334cdeb80789e8999b8f199501debfc1af657da` | `StateWriter`/`StateReader` without the stream header, as `Writer`/`Reader` | | `src/core/codec/Stream.hpp` | contour-terminal/contour | `src/vtbackend/state/StateCodec.hpp` | `3334cdeb80789e8999b8f199501debfc1af657da` | `StateWriter`/`StateReader` without the stream header, as `Writer`/`Reader` | | `src/core/codec/Stream_test.cpp` | origin: core-cpp | - | - | - | +| `src/core/fs/AccessScope.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): `classifyAccess`, the one access table of every OS | +| `src/core/fs/AccessScope.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): `AccessScope`, `AccessFacts` and `classifyAccess` | +| `src/core/fs/AccessScope_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | | `src/core/fs/CMakeLists.txt` | origin: core-cpp | - | - | 0.24.0 (P13): the module, its per-OS error tables and its test binary | | `src/core/fs/Descriptor.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): `IDescriptorFileSystem`, `IDescriptor`, `IDirectoryStream` and their vocabulary, shaped after WASI 0.3 `wasi:filesystem` | | `src/core/fs/DescriptorContract_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): what every descriptor owes its caller, per fixture kind | @@ -175,7 +178,11 @@ others in notes. | `src/core/fs/PathPolicy.hpp` | origin: core-cpp | - | - | 0.24.0 (P13) | | `src/core/fs/Rights.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the rights table and `checkOpenRights`, after wasmtime's descriptor permissions | | `src/core/fs/Rights.hpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/fs/bsd/AccessFacts.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): FreeBSD's access reader, NFSv4 ACLs | | `src/core/fs/bsd/ErrnoTable.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): Apple and the BSDs; `EMLINK` for FreeBSD's `O_NOFOLLOW` | +| `src/core/fs/bsd/InheritableAcl_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): an NFSv4 `setfacl`, FreeBSD | +| `src/core/fs/darwin/AccessFacts.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): macOS's access reader, extended ACLs | +| `src/core/fs/darwin/InheritableAcl_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): `chmod +a`, macOS | | `src/core/fs/darwin/PosixSystem.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): Apple: `st_atimespec`, `F_RDADVISE`, `F_FULLFSYNC`, `EACCES` for `O_CREAT` on a directory | | `src/core/fs/detail/DirectoryStream.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | | `src/core/fs/detail/DirectoryStream.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): the batched directory stream every implementation reads through | @@ -199,8 +206,10 @@ others in notes. | `src/core/fs/linux/Openat2.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): `openat2(RESOLVE_BENEATH | RESOLVE_NO_MAGICLINKS)`, the probe and the bounded `EAGAIN` retry | | `src/core/fs/linux/Openat2.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): the `openat2` system-call seam | | `src/core/fs/linux/Openat2_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/fs/posix/AccessFacts.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the access reader of Linux and every POSIX system without an ACL of its own | | `src/core/fs/posix/Append.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the second, `O_APPEND` handle of every POSIX system but Linux | | `src/core/fs/posix/BeneathDefault.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): `Best` is the walk on every POSIX system but Linux; `#ifdef O_PATH` inside the data picks the walk's open flags | +| `src/core/fs/posix/DescriptorTestSupport.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): `runsUnderWine` on POSIX | | `src/core/fs/posix/DirectoryEntries.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): what a directory entry is: `d_type`, else a stat without following | | `src/core/fs/posix/DirectoryEntries_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): `DT_UNKNOWN` stat'ed without following; refused names | | `src/core/fs/posix/DirectoryRead.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): `fdopendir` and `readdir` for every POSIX system but Linux | @@ -208,9 +217,14 @@ others in notes. | `src/core/fs/posix/DirectoryStreamMemory_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): a large listing read within an allocation budget; replaces the global allocation functions | | `src/core/fs/posix/ErrnoRows.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): the errno rows `posix/` and `bsd/ErrnoTable.cpp` share | | `src/core/fs/posix/ErrnoTable.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/fs/posix/InheritableAcl.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): how a test plants an inheritable ACL, per OS | +| `src/core/fs/posix/InheritableAcl_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): `setfacl -d`, Linux | | `src/core/fs/posix/Lease.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): no leases off Linux: `WouldBlock` | | `src/core/fs/posix/NativePathPolicy.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | | `src/core/fs/posix/OwnedHandleAllocation_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the last close when its frame cannot be allocated; replaces the global allocation functions | +| `src/core/fs/posix/OwnerOnlyCreation.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): owner-only creation, direct or through a stripped staging directory | +| `src/core/fs/posix/OwnerOnlyCreation.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): owner-only creation on POSIX | +| `src/core/fs/posix/OwnerOnly_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | | `src/core/fs/posix/PosixDescriptor.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the POSIX native descriptors | | `src/core/fs/posix/PosixDescriptor_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): a FIFO opens without waiting; a name that is not UTF-8 is one refused entry | | `src/core/fs/posix/PosixPathWalk.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the component walker over held directory descriptors | @@ -221,14 +235,20 @@ others in notes. | `src/core/fs/testing/InMemoryDescriptorFileSystem.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | | `src/core/fs/testing/InMemoryDescriptorFileSystem.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): the in-memory model, resolving and enforcing through the code the native one uses | | `src/core/fs/testing/InMemoryDescriptorFileSystem_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/fs/windows/AccessFacts.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the Windows access reader, owner and DACL by handle | +| `src/core/fs/windows/AccessFacts.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): the Windows access reader | | `src/core/fs/windows/BeneathDefault.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): `Best` is the walk on Windows | | `src/core/fs/windows/DescriptorEscape_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): junctions, mount points, backslash targets, link flavour, private reparse tags | +| `src/core/fs/windows/DescriptorTestSupport.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): `runsUnderWine` on Windows | | `src/core/fs/windows/DirectoryRecords.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): `FILE_ID_BOTH_DIR_INFO` records, field by field, within their buffer | | `src/core/fs/windows/DirectoryRecords.hpp` | origin: core-cpp | - | - | 0.24.0 (P13) | | `src/core/fs/windows/DirectoryRecords_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | | `src/core/fs/windows/NativePathPolicy.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | | `src/core/fs/windows/NtFile.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): `NtCreateFile` relative to a held directory | | `src/core/fs/windows/NtStatusTable.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/fs/windows/OwnerOnly_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/fs/windows/OwnerSecurity.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the token user and the owner-only security descriptors | +| `src/core/fs/windows/OwnerSecurity.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): the token user and the owner-only security descriptors | | `src/core/fs/windows/ReparsePoint.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): reparse data, field by field | | `src/core/fs/windows/ReparsePoint.hpp` | origin: core-cpp | - | - | 0.24.0 (P13) | | `src/core/fs/windows/Win32ErrorTable.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 5c2dc70b..29b7d3c5 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -619,6 +619,10 @@ jobs: env: VCPKG_COMMIT: e6f9e70a29a3e80a1fc510d8503304315447112f VCPKG_ARCHIVES: ${{ github.workspace }}/.cache/vcpkg-archives + # GitHub's Windows runners run elevated (administrator, UAC off), so the fs cases that need + # elevation -- an owner-only file created elevated, a file given to BUILTIN\Administrators -- + # fail here instead of skipping (src/core/fs/windows/OwnerOnly_test.cpp). + CORE_TEST_REQUIRE_ELEVATED: "1" steps: - uses: actions/checkout@v7 with: diff --git a/src/core/fs/AccessScope.cpp b/src/core/fs/AccessScope.cpp new file mode 100644 index 00000000..5e46eb4e --- /dev/null +++ b/src/core/fs/AccessScope.cpp @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: Apache-2.0 +#include + +#include +#include +#include + +namespace core::fs +{ + +namespace +{ + + using Kind = AccessEntry::Kind; + using Principal = AccessEntry::Principal; + using Rights = AccessEntry::Rights; + using AclState = AccessFacts::AclState; + + /// The mode bits of the group and of others: any one of them lets someone else in. + constexpr auto SharedModeBits = std::uint32_t { 0077 }; + + /// The principals an ALLOW entry may name and leave the object owner-only: the user, and the two + /// that can reach every object whatever its DACL says. + constexpr auto OwnerSidePrincipals = + std::to_array({ Principal::Owner, Principal::System, Principal::Administrators }); + + /// @return Whether @p entry lets someone other than the owner side in. + [[nodiscard]] constexpr bool widens(AccessEntry const& entry) noexcept + { + switch (entry.kind) + { + case Kind::Deny: return false; + case Kind::Unknown: return true; + case Kind::Allow: + return entry.rights != Rights::None + && std::ranges::find(OwnerSidePrincipals, entry.principal) + == OwnerSidePrincipals.end(); + } + return true; + } + +} // namespace + +AccessScope classifyAccess(AccessFacts const& facts) noexcept +{ + if (facts.owner != AccessFacts::Owner::CurrentUser) + return AccessScope::ForeignOwner; + if ((facts.posixMode & SharedModeBits) != 0) + return AccessScope::Shared; + switch (facts.acl) + { + case AclState::Absent: + case AclState::Trivial: return AccessScope::OwnerOnly; + case AclState::Present: + return std::ranges::any_of(facts.entries, widens) ? AccessScope::Shared : AccessScope::OwnerOnly; + case AclState::Null: return AccessScope::Shared; + } + return AccessScope::Shared; +} + +} // namespace core::fs diff --git a/src/core/fs/AccessScope.hpp b/src/core/fs/AccessScope.hpp new file mode 100644 index 00000000..733065b4 --- /dev/null +++ b/src/core/fs/AccessScope.hpp @@ -0,0 +1,108 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// Who may reach a file system object, decided from facts read off its open handle. +/// +/// Each operating system has its own reader, selected by CMake, that turns what the handle says +/// (`fstat`; an NFSv4 ACL on FreeBSD; an extended ACL on macOS; the owner and DACL on Windows) into +/// one OS-neutral @c AccessFacts. The decision is @c classifyAccess, one table, the same on every +/// OS, so every OS's rows are tested everywhere. **Nothing is decided by name**: a check of a path +/// followed by an open of it is a race another user wins by renaming, so the facts are always read +/// from the handle the caller then uses. + +#include + +#include +#include + +namespace core::fs +{ + +/// Who may reach an object, read from its open handle. **`Shared` is zero**, so a default value +/// fails closed. +enum class AccessScope : std::uint8_t +{ + /// Someone other than the owner may read or write it, or that cannot be ruled out: a group or + /// other mode bit, an ACL entry granting another principal, a NULL DACL, an entry not understood. + Shared, + /// Only the current user may: on POSIX no group or other bit and no ACL beyond the mode; on + /// Windows every ALLOW entry names the user, LocalSystem or BUILTIN\Administrators. + OwnerOnly, + /// Another user owns it, and so may change who reaches it at any time. + ForeignOwner, +}; + +/// One entry of an access control list, as the per-OS reader understood it. +struct AccessEntry +{ + /// What the entry does. + enum class Kind : std::uint8_t + { + Allow, ///< Grants its rights (Windows `ACCESS_ALLOWED_ACE_TYPE`). + Deny, ///< Denies them; never widens access, so it is ignored. + Unknown, ///< Any other type, or an entry the reader cannot interpret: counts as granting. + }; + /// Whom it names. + enum class Principal : std::uint8_t + { + Owner, ///< The current user (Windows `TokenUser`). + System, ///< LocalSystem, which can reach every object anyway. + Administrators, ///< BUILTIN\Administrators, which can take ownership of every object anyway. + Other, ///< Anyone else: Everyone, Users, Authenticated Users, any group or account. + }; + /// What it grants. + enum class Rights : std::uint8_t + { + None, ///< An empty access mask. + ReadOrWrite, ///< Any right at all. + }; + /// Where it came from. Inherited entries count exactly as explicit ones do: an object reachable + /// through an entry its parent handed down is reachable all the same. + enum class Origin : std::uint8_t + { + Explicit, ///< Set on the object itself. + Inherited, ///< Handed down from a parent (Windows `INHERITED_ACE`). + }; + + Kind kind = Kind::Unknown; ///< What it does; unknown by default, which fails closed. + Principal principal = Principal::Other; ///< Whom it names. + Rights rights = Rights::ReadOrWrite; ///< What it grants. + Origin origin = Origin::Explicit; ///< Where it came from. +}; + +/// What a per-OS reader extracts from an open handle; @c classifyAccess decides from it alone. +struct AccessFacts +{ + /// Who owns the object. + enum class Owner : std::uint8_t + { + CurrentUser, ///< The effective uid; Windows' `TokenUser`. + Other, ///< Anyone else, BUILTIN\Administrators included. + }; + /// What the access control list beyond the mode is. + enum class AclState : std::uint8_t + { + Absent, ///< None: the mode is all (Linux, where POSIX ACL entries are bounded by the mode's group + ///< bits). + Trivial, ///< One equivalent to the mode (a trivial FreeBSD NFSv4 ACL). + Present, ///< One of its own: @c entries lists it, an entry the reader cannot judge as `Unknown`. + Null, ///< A Windows NULL DACL, which grants everyone everything. + }; + + Owner owner = Owner::Other; ///< Who owns it; another by default, which fails closed. + std::uint32_t posixMode = 07777; ///< The POSIX mode bits; 0 where the OS has none (Windows). + AclState acl = AclState::Null; ///< The ACL beyond the mode; NULL by default, which fails closed. + std::vector entries; ///< Its entries, where @c acl is @c AclState::Present. +}; + +/// Decides who may reach an object. Pure: the same facts give the same answer on every OS. +/// +/// `ForeignOwner` where another user owns it; else `Shared` where a group or other mode bit is set, +/// the DACL is NULL, or an entry that is not a DENY is unknown or grants any right to a principal +/// other than the user, LocalSystem or BUILTIN\Administrators; else `OwnerOnly`. +/// @param facts What the handle told. +/// @return The scope. +[[nodiscard]] CORE_FS_API AccessScope classifyAccess(AccessFacts const& facts) noexcept; + +} // namespace core::fs diff --git a/src/core/fs/AccessScope_test.cpp b/src/core/fs/AccessScope_test.cpp new file mode 100644 index 00000000..762f9149 --- /dev/null +++ b/src/core/fs/AccessScope_test.cpp @@ -0,0 +1,143 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The access classifier is pure, so every operating system's row of facts is held to it on every +// operating system: what a Linux fstat, a FreeBSD NFSv4 ACL, a macOS extended ACL or a Windows DACL +// would make of an object. +#include + +#include +#include + +#include +#include +#include + +using core::fs::AccessEntry; +using core::fs::AccessFacts; +using core::fs::AccessScope; +using core::fs::classifyAccess; + +namespace +{ + +using Kind = AccessEntry::Kind; +using Principal = AccessEntry::Principal; +using Rights = AccessEntry::Rights; +using Origin = AccessEntry::Origin; +using Owner = AccessFacts::Owner; +using AclState = AccessFacts::AclState; + +struct Row +{ + std::string_view name; + AccessFacts facts; + AccessScope expected; +}; + +[[nodiscard]] AccessEntry allow(Principal principal, Origin origin = Origin::Explicit) +{ + return AccessEntry { + .kind = Kind::Allow, .principal = principal, .rights = Rights::ReadOrWrite, .origin = origin + }; +} + +[[nodiscard]] AccessFacts posix(std::uint32_t mode, Owner owner = Owner::CurrentUser) +{ + return AccessFacts { .owner = owner, .posixMode = mode, .acl = AclState::Absent, .entries = {} }; +} + +/// Windows has no mode: its facts are the owner and the DACL's entries. +[[nodiscard]] AccessFacts windows(std::vector entries, Owner owner = Owner::CurrentUser) +{ + return AccessFacts { + .owner = owner, .posixMode = 0, .acl = AclState::Present, .entries = std::move(entries) + }; +} + +} // namespace + +TEST_CASE("classifyAccess follows the table", "[fs][access]") +{ + auto const row = GENERATE( + Row { "POSIX 0600, owned by the user", posix(0600), AccessScope::OwnerOnly }, + Row { "POSIX 0700 directory", posix(040700), AccessScope::OwnerOnly }, + Row { "POSIX 0640: the group may read", posix(0640), AccessScope::Shared }, + Row { "POSIX 0602: others may write", posix(0602), AccessScope::Shared }, + Row { "POSIX 0620: the group may write", posix(0620), AccessScope::Shared }, + Row { "POSIX 0601: others may search", posix(0601), AccessScope::Shared }, + Row { "POSIX 0600 owned by another uid", posix(0600, Owner::Other), AccessScope::ForeignOwner }, + Row { "POSIX 0644 owned by another uid", posix(0644, Owner::Other), AccessScope::ForeignOwner }, + Row { "FreeBSD 0600 with a trivial NFSv4 ACL", + AccessFacts { + .owner = Owner::CurrentUser, .posixMode = 0600, .acl = AclState::Trivial, .entries = {} }, + AccessScope::OwnerOnly }, + Row { "FreeBSD 0600 with a non-trivial NFSv4 ACL", + AccessFacts { .owner = Owner::CurrentUser, + .posixMode = 0600, + .acl = AclState::Present, + .entries = { AccessEntry {} } }, + AccessScope::Shared }, + Row { "macOS 0600 with an extended ACL entry", + AccessFacts { .owner = Owner::CurrentUser, + .posixMode = 0600, + .acl = AclState::Present, + .entries = { AccessEntry { .kind = Kind::Unknown, + .principal = Principal::Other, + .rights = Rights::ReadOrWrite, + .origin = Origin::Explicit } } }, + AccessScope::Shared }, + Row { + "Windows NULL DACL", + AccessFacts { .owner = Owner::CurrentUser, .posixMode = 0, .acl = AclState::Null, .entries = {} }, + AccessScope::Shared }, + Row { "Windows empty DACL: nobody but the owner", windows({}), AccessScope::OwnerOnly }, + Row { "Windows owner only", windows({ allow(Principal::Owner) }), AccessScope::OwnerOnly }, + Row { + "Windows SYSTEM, Administrators and the owner", + windows({ allow(Principal::System), allow(Principal::Administrators), allow(Principal::Owner) }), + AccessScope::OwnerOnly }, + Row { "Windows the same, inherited", + windows({ allow(Principal::System, Origin::Inherited), + allow(Principal::Administrators, Origin::Inherited), + allow(Principal::Owner, Origin::Inherited) }), + AccessScope::OwnerOnly }, + Row { "Windows Everyone ALLOW, explicit", + windows({ allow(Principal::Owner), allow(Principal::Other) }), + AccessScope::Shared }, + Row { "Windows Everyone ALLOW, inherited", + windows({ allow(Principal::Owner), allow(Principal::Other, Origin::Inherited) }), + AccessScope::Shared }, + Row { "Windows an ALLOW of no right to another SID", + windows({ allow(Principal::Owner), + AccessEntry { .kind = Kind::Allow, + .principal = Principal::Other, + .rights = Rights::None, + .origin = Origin::Explicit } }), + AccessScope::OwnerOnly }, + Row { "Windows DENY Everyone never widens", + windows({ allow(Principal::Owner), + AccessEntry { .kind = Kind::Deny, + .principal = Principal::Other, + .rights = Rights::ReadOrWrite, + .origin = Origin::Explicit } }), + AccessScope::OwnerOnly }, + Row { "Windows an entry of unknown type", + windows({ allow(Principal::Owner), + AccessEntry { .kind = Kind::Unknown, + .principal = Principal::Owner, + .rights = Rights::ReadOrWrite, + .origin = Origin::Explicit } }), + AccessScope::Shared }, + Row { "Windows owned by Administrators, not the user", + windows({ allow(Principal::Owner) }, Owner::Other), + AccessScope::ForeignOwner }, + Row { "default facts fail closed", AccessFacts {}, AccessScope::ForeignOwner }); + INFO(row.name); + CHECK(classifyAccess(row.facts) == row.expected); +} + +TEST_CASE("a default AccessScope is Shared", "[fs][access]") +{ + // A zero-initialised scope must never read as owner-only. + CHECK(AccessScope {} == AccessScope::Shared); +} diff --git a/src/core/fs/CMakeLists.txt b/src/core/fs/CMakeLists.txt index ff71e4a0..7da919c9 100644 --- a/src/core/fs/CMakeLists.txt +++ b/src/core/fs/CMakeLists.txt @@ -27,17 +27,28 @@ # system has leases (posix/). # - DirectoryRead.cpp: a directory stream reads Linux's getdents64 records into a fixed buffer # (linux/); every other POSIX system reads through fdopendir and readdir (posix/). +# - AccessFacts.cpp: who may reach an object, read from its handle. Linux, and every POSIX system +# without an ACL of its own, needs only the fstat (posix/); FreeBSD reads an NFSv4 ACL +# (bsd/), macOS an extended one (darwin/), Windows the owner and DACL (windows/, beside +# OwnerSecurity.cpp, the descriptor owner-only creations are made with). Each fills the same +# AccessFacts, and AccessScope.cpp decides from them on every OS. if(WIN32) - set(_coreCppFsPlatform windows/Win32ErrorTable.cpp windows/NtStatusTable.cpp windows/BeneathDefault.cpp) - set(_coreCppFsPrivateLibs ntdll) + set(_coreCppFsPlatform windows/Win32ErrorTable.cpp windows/NtStatusTable.cpp windows/BeneathDefault.cpp windows/AccessFacts.cpp) + set(_coreCppFsPrivateLibs ntdll advapi32) elseif(APPLE) - set(_coreCppFsPlatform bsd/ErrnoTable.cpp darwin/PosixSystem.cpp posix/Append.cpp posix/BeneathDefault.cpp posix/DirectoryRead.cpp posix/Lease.cpp) + set(_coreCppFsPlatform bsd/ErrnoTable.cpp darwin/PosixSystem.cpp posix/Append.cpp posix/BeneathDefault.cpp posix/DirectoryRead.cpp posix/Lease.cpp darwin/AccessFacts.cpp) elseif(CORE_CPP_PLATFORM_BSD) set(_coreCppFsPlatform bsd/ErrnoTable.cpp posix/PosixSystem.cpp posix/Append.cpp posix/BeneathDefault.cpp posix/DirectoryRead.cpp posix/Lease.cpp) + # NFSv4 ACLs are FreeBSD's; the other BSDs have none beyond what the mode bounds. + if(CMAKE_SYSTEM_NAME STREQUAL "FreeBSD") + list(APPEND _coreCppFsPlatform bsd/AccessFacts.cpp) + else() + list(APPEND _coreCppFsPlatform posix/AccessFacts.cpp) + endif() elseif(LINUX) - set(_coreCppFsPlatform posix/ErrnoTable.cpp posix/PosixSystem.cpp linux/Append.cpp linux/BeneathDefault.cpp linux/DirectoryRead.cpp linux/Lease.cpp) + set(_coreCppFsPlatform posix/ErrnoTable.cpp posix/PosixSystem.cpp linux/Append.cpp linux/BeneathDefault.cpp linux/DirectoryRead.cpp linux/Lease.cpp posix/AccessFacts.cpp) else() - set(_coreCppFsPlatform posix/ErrnoTable.cpp posix/PosixSystem.cpp posix/Append.cpp posix/BeneathDefault.cpp posix/DirectoryRead.cpp posix/Lease.cpp) + set(_coreCppFsPlatform posix/ErrnoTable.cpp posix/PosixSystem.cpp posix/Append.cpp posix/BeneathDefault.cpp posix/DirectoryRead.cpp posix/Lease.cpp posix/AccessFacts.cpp) endif() # The openat2 path spells the call's ABI itself (linux/Openat2.hpp), so no UAPI 5.6 headers or glibc @@ -46,6 +57,7 @@ endif() core_cpp_add_module(fs KIND STATIC HEADERS + AccessScope.hpp Descriptor.hpp FsError.hpp NativeFileSystem.hpp @@ -53,6 +65,7 @@ core_cpp_add_module(fs KIND STATIC Rights.hpp testing/InMemoryDescriptorFileSystem.hpp SOURCES + AccessScope.cpp FsError.cpp PathPolicy.cpp Rights.cpp @@ -71,6 +84,8 @@ core_cpp_add_module(fs KIND STATIC posix/DirectoryRead.hpp posix/ErrnoRows.hpp posix/NativePathPolicy.cpp + posix/OwnerOnlyCreation.cpp + posix/OwnerOnlyCreation.hpp posix/PosixDescriptor.cpp posix/PosixPathWalk.cpp posix/PosixPathWalk.hpp @@ -84,7 +99,10 @@ core_cpp_add_module(fs KIND STATIC windows/DirectoryRecords.cpp windows/DirectoryRecords.hpp windows/NativePathPolicy.cpp + windows/AccessFacts.hpp windows/NtFile.hpp + windows/OwnerSecurity.cpp + windows/OwnerSecurity.hpp windows/ReparsePoint.cpp windows/ReparsePoint.hpp windows/WindowsDescriptor.cpp @@ -104,10 +122,20 @@ if(LINUX) USAGE core::base core::async core::platform) endif() +# How a test plants an inheritable ACL through the host: per OS, as the readers are chosen above. +if(APPLE) + set(_coreCppFsInheritableAcl darwin/InheritableAcl_test.cpp) +elseif(CMAKE_SYSTEM_NAME STREQUAL "FreeBSD") + set(_coreCppFsInheritableAcl bsd/InheritableAcl_test.cpp) +else() + set(_coreCppFsInheritableAcl posix/InheritableAcl_test.cpp) +endif() + # One binary: every case links core::fs and nothing the module's row does not list. # DescriptorTestSupport.hpp is the test-only fixture the descriptor cases share. core_cpp_add_test(fs SOURCES + AccessScope_test.cpp DescriptorContract_test.cpp DescriptorEscape_test.cpp DescriptorTestSupport.hpp @@ -117,7 +145,11 @@ core_cpp_add_test(fs detail/PathWalk_test.cpp testing/InMemoryDescriptorFileSystem_test.cpp SOURCES_POSIX + posix/DescriptorTestSupport.cpp posix/DirectoryEntries_test.cpp + posix/InheritableAcl.hpp + ${_coreCppFsInheritableAcl} + posix/OwnerOnly_test.cpp posix/PosixDescriptor_test.cpp posix/PosixPathWalk_test.cpp SOURCES_LINUX @@ -128,7 +160,9 @@ core_cpp_add_test(fs linux/Openat2_test.cpp SOURCES_WINDOWS windows/DescriptorEscape_test.cpp + windows/DescriptorTestSupport.cpp windows/DirectoryRecords_test.cpp + windows/OwnerOnly_test.cpp windows/WindowsPathWalk_test.cpp) # What the last owner of a handle does when its queued close cannot be allocated: a binary of its own diff --git a/src/core/fs/Descriptor.hpp b/src/core/fs/Descriptor.hpp index 04d4d981..ffb9ac7f 100644 --- a/src/core/fs/Descriptor.hpp +++ b/src/core/fs/Descriptor.hpp @@ -17,6 +17,7 @@ /// - **Paths are UTF-8**, relative, and checked against the file system's @c PathPolicy. #include +#include #include #include @@ -83,6 +84,35 @@ enum class OpenFlags : std::uint8_t Directory = 0b10, ///< Fail unless the object is a directory. Exclusive = 0b100, ///< With @c Create: fail where something exists. Truncate = 0b1000, ///< Truncate a regular file to zero bytes. + /// With @c Create and @c Exclusive (else `Invalid`): the file is created so that no other user + /// can reach it at any moment, under its final name or before it: + /// - **Linux:** mode 0600 is given to `openat` itself; a default ACL cannot widen it, since + /// each entry it hands down is capped by the mode (the mask by the group bits). + /// - **macOS, FreeBSD:** an inherited ACL (extended; NFSv4) could, so the file is made inside a + /// fresh staging directory beside it: that directory is created 0700, its inherited ACL + /// stripped and its access verified before anything is created in it, so another user who + /// opened it early holds a descriptor that searches nothing. The file is created there, + /// stripped and verified too, then linked to its final name (which fails, as `Exclusive` + /// says, where something exists) and the staging directory removed. + /// - **Windows:** owned by the process token's user, with a protected DACL (nothing inherited) + /// granting that user alone, given to `NtCreateFile` itself. + /// + /// Nothing has been written to it when the call returns. Where any step fails, what was made is + /// removed through the parent's handle and the call fails (`NotPermitted` where the access read + /// back is not @c AccessScope::OwnerOnly, else what refused the step). + OwnerOnly = 0b1'0000, +}; + +/// Who may reach a directory @c IDescriptor::createDirectoryAt creates. +enum class CreationAccess : std::uint8_t +{ + Default, ///< What the system gives: POSIX 0777 less the umask; Windows the inherited DACL. + /// No other user can reach it at any moment, as for @c OpenFlags::OwnerOnly: Linux gives 0700 to + /// `mkdirat`; macOS and FreeBSD make it inside a stripped, verified 0700 staging directory, strip + /// and verify it too, then rename it over an empty placeholder made with the final name (so an + /// existing entry is `Exist`); Windows gives it the same protected DACL, its entry inheritable. + /// Where a step fails, what was made is removed and the call fails. + OwnerOnly, }; /// @param a The first mask. @@ -159,6 +189,16 @@ struct DescriptorStat std::optional accessed; ///< Last access, where the system keeps it. std::optional modified; ///< Last modification of its data. std::optional statusChanged; ///< Last change of its metadata. + /// Who may reach it, read from the handle the stat was made through (@c classifyAccess). + /// + /// **nullopt means "cannot judge", never "probably fine"**: an ACL that cannot be read, a + /// Windows object whose DACL withholds `READ_CONTROL`, a FreeBSD or macOS + /// @c IDescriptor::statAt, which holds no handle to read an ACL from. A consumer that guards a + /// secret with this (a key directory, a key file) must refuse nullopt as it refuses + /// @c AccessScope::Shared: fail closed. An object created owner-only (@c OpenFlags::OwnerOnly, + /// @c CreationAccess::OwnerOnly) reads @c AccessScope::OwnerOnly through its handle when it is + /// returned. + std::optional access; }; /// One entry of a directory. @@ -297,8 +337,10 @@ class IDescriptor /// Creates the directory @p path. Needs `MutateDirectory`. /// @param path The relative path. + /// @param access Who may reach it, given to the creating call itself. /// @return Nothing, or why not. - [[nodiscard]] virtual async::Task> createDirectoryAt(std::string path) = 0; + [[nodiscard]] virtual async::Task> createDirectoryAt(std::string path, + CreationAccess access) = 0; /// Reads what @p path refers to without opening it. Needs `Read`. /// @param policy Whether a final symbolic link is followed. diff --git a/src/core/fs/DescriptorContract_test.cpp b/src/core/fs/DescriptorContract_test.cpp index 2637e870..e2263b55 100644 --- a/src/core/fs/DescriptorContract_test.cpp +++ b/src/core/fs/DescriptorContract_test.cpp @@ -2,11 +2,13 @@ // // What every IDescriptor owes its caller, whichever file system is under it. Each case GENERATEs // the fixture kinds it holds for: the in-memory model and the native descriptors. +#include #include #include #include #include #include +#include #include #include @@ -24,7 +26,10 @@ #include #include +using core::fs::AccessFacts; +using core::fs::AccessScope; using core::fs::Advice; +using core::fs::CreationAccess; using core::fs::DescriptorFlags; using core::fs::DescriptorStat; using core::fs::DescriptorType; @@ -71,7 +76,7 @@ TEST_CASE("contract: written bytes read back with an end marker", "[fs][contract TEST_CASE("contract: a path that climbs above its descriptor is NotPermitted", "[fs][contract]") { auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); - REQUIRE(fixture.run(fixture.root().createDirectoryAt("a")).has_value()); + REQUIRE(fixture.run(fixture.root().createDirectoryAt("a", CreationAccess::Default)).has_value()); fixture.createFile("x", "inside"); auto const escaped = fixture.run( @@ -90,7 +95,7 @@ TEST_CASE("contract: a read-only preopen refuses every mutation and changes noth { auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); fixture.createFile("f", "content"); - REQUIRE(fixture.run(fixture.root().createDirectoryAt("d")).has_value()); + REQUIRE(fixture.run(fixture.root().createDirectoryAt("d", CreationAccess::Default)).has_value()); auto readOnly = fixture.openRoot(DescriptorFlags::Read); REQUIRE(readOnly.has_value()); auto& dir = **readOnly; @@ -109,7 +114,7 @@ TEST_CASE("contract: a read-only preopen refuses every mutation and changes noth == FsErrorCode::NotPermitted); CHECK(refusal(dir.openAt(SymlinkPolicy::NoFollow, "f", OpenFlags::Truncate, DescriptorFlags::Read)) == FsErrorCode::NotPermitted); - CHECK(refusal(dir.createDirectoryAt("e")) == FsErrorCode::NotPermitted); + CHECK(refusal(dir.createDirectoryAt("e", CreationAccess::Default)) == FsErrorCode::NotPermitted); CHECK(refusal(dir.unlinkFileAt("f")) == FsErrorCode::NotPermitted); CHECK(refusal(dir.removeDirectoryAt("d")) == FsErrorCode::NotPermitted); CHECK(refusal(dir.renameAt("f", &dir, "g")) == FsErrorCode::NotPermitted); @@ -136,7 +141,7 @@ TEST_CASE("contract: a read-only preopen refuses every mutation and changes noth TEST_CASE("contract: a child opened with more flags than its parent is NotPermitted", "[fs][contract]") { auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); - REQUIRE(fixture.run(fixture.root().createDirectoryAt("d")).has_value()); + REQUIRE(fixture.run(fixture.root().createDirectoryAt("d", CreationAccess::Default)).has_value()); auto readOnly = fixture.openRoot(DescriptorFlags::Read); REQUIRE(readOnly.has_value()); @@ -159,7 +164,7 @@ TEST_CASE("contract: an open the parent may not make is NotPermitted before its { // wasmtime's order: the parent's rights first, then Directory with Create is Invalid. auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); - REQUIRE(fixture.run(fixture.root().createDirectoryAt("d")).has_value()); + REQUIRE(fixture.run(fixture.root().createDirectoryAt("d", CreationAccess::Default)).has_value()); auto readOnly = fixture.openRoot(DescriptorFlags::Read); REQUIRE(readOnly.has_value()); @@ -239,7 +244,7 @@ TEST_CASE("contract: a symbolic link is followed only beneath its descriptor", " auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); if (fixture.requireSymlinks() == SymlinkSupport::Unavailable) SKIP("this file system cannot create symbolic links"); - REQUIRE(fixture.run(fixture.root().createDirectoryAt("a")).has_value()); + REQUIRE(fixture.run(fixture.root().createDirectoryAt("a", CreationAccess::Default)).has_value()); fixture.createFile("target", "through the link"); CHECK(outcomeOf(fixture.run(fixture.root().symlinkAt("/etc/passwd", "absolute"))) @@ -271,7 +276,7 @@ TEST_CASE("contract: a symbolic link is followed only beneath its descriptor", " TEST_CASE("contract: a directory descriptor never carries Write", "[fs][contract]") { auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); - REQUIRE(fixture.run(fixture.root().createDirectoryAt("d")).has_value()); + REQUIRE(fixture.run(fixture.root().createDirectoryAt("d", CreationAccess::Default)).has_value()); CHECK(outcomeOf(fixture.run(fixture.root().openAt( SymlinkPolicy::NoFollow, "d", OpenFlags::None, DescriptorFlags::Read | DescriptorFlags::Write))) == FsErrorCode::IsDirectory); @@ -350,7 +355,9 @@ std::vector rightsCases() { CreateDirectoryAt, DescriptorFlags::MutateDirectory, Directory, - [](auto& fx, auto& d) { return outcomeOf(fx.run(d.createDirectoryAt("new"))); } }, + [](auto& fx, auto& d) { + return outcomeOf(fx.run(d.createDirectoryAt("new", CreationAccess::Default))); + } }, { StatAt, DescriptorFlags::Read, Directory, @@ -397,7 +404,7 @@ Outcome callWith(FixtureKind kind, RightsCase const& rightsCase, DescriptorFlags { auto fixture = DescriptorFixture::create(kind); fixture.createFile("f", "content"); - REQUIRE(fixture.run(fixture.root().createDirectoryAt("sub")).has_value()); + REQUIRE(fixture.run(fixture.root().createDirectoryAt("sub", CreationAccess::Default)).has_value()); if (fixture.requireSymlinks() == SymlinkSupport::Available) REQUIRE(fixture.run(fixture.root().symlinkAt("f", "link")).has_value()); auto holder = @@ -466,7 +473,8 @@ TEST_CASE("contract: a file descriptor resolves no path and carries no MutateDir CHECK(outcomeOf(fixture.run( (*file)->openAt(SymlinkPolicy::NoFollow, "x", OpenFlags::None, DescriptorFlags::Read))) == FsErrorCode::NotDirectory); - CHECK(outcomeOf(fixture.run((*file)->createDirectoryAt("x"))) == FsErrorCode::NotPermitted); + CHECK(outcomeOf(fixture.run((*file)->createDirectoryAt("x", CreationAccess::Default))) + == FsErrorCode::NotPermitted); CHECK(outcomeOf(fixture.run(fixture.root().renameAt("g", file->get(), "x"))) == FsErrorCode::NotPermitted); CHECK(fixture.run(fixture.root().statAt(SymlinkPolicy::NoFollow, "g")).has_value()); @@ -487,7 +495,7 @@ TEST_CASE("contract: a trailing slash requires a directory", "[fs][contract]") auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); auto& root = fixture.root(); fixture.createFile("file", "content"); - REQUIRE(fixture.run(root.createDirectoryAt("dir")).has_value()); + REQUIRE(fixture.run(root.createDirectoryAt("dir", CreationAccess::Default)).has_value()); auto const nf = SymlinkPolicy::NoFollow; auto const notDirectory = Outcome { FsErrorCode::NotDirectory }; @@ -516,7 +524,7 @@ TEST_CASE("contract: a trailing slash requires a directory", "[fs][contract]") CAPTURE(name); CHECK(outcomeOf(fixture.run(root.statAt(nf, name))) == FsErrorCode::NoEntry); } - REQUIRE(fixture.run(root.createDirectoryAt("made/")).has_value()); + REQUIRE(fixture.run(root.createDirectoryAt("made/", CreationAccess::Default)).has_value()); CHECK(fixture.run(root.statAt(nf, "made"))->type == DescriptorType::Directory); } SECTION("a directory named with a trailing slash") @@ -565,7 +573,7 @@ TEST_CASE("contract: a directory named through its own dot is not removed", "[fs // `dir/.` names the directory itself, not an entry of its parent: Linux's rmdir answers EINVAL. auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); auto& root = fixture.root(); - REQUIRE(fixture.run(root.createDirectoryAt("dir")).has_value()); + REQUIRE(fixture.run(root.createDirectoryAt("dir", CreationAccess::Default)).has_value()); CHECK(outcomeOf(fixture.run(root.removeDirectoryAt("dir/."))) == FsErrorCode::Invalid); CHECK(outcomeOf(fixture.run(root.removeDirectoryAt("dir/./"))) == FsErrorCode::Invalid); @@ -575,7 +583,7 @@ TEST_CASE("contract: a directory named through its own dot is not removed", "[fs TEST_CASE("contract: Create opens no directory and creates nothing through a link", "[fs][contract]") { auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); - REQUIRE(fixture.run(fixture.root().createDirectoryAt("dir")).has_value()); + REQUIRE(fixture.run(fixture.root().createDirectoryAt("dir", CreationAccess::Default)).has_value()); CHECK(outcomeOf(fixture.run(fixture.root().openAt( SymlinkPolicy::NoFollow, "dir", OpenFlags::Create, DescriptorFlags::Read))) == FsErrorCode::IsDirectory); @@ -774,7 +782,7 @@ TEST_CASE("contract: openAt creates, truncates and requires a directory as it is auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); auto& root = fixture.root(); fixture.createFile("f", "content"); - REQUIRE(fixture.run(root.createDirectoryAt("d")).has_value()); + REQUIRE(fixture.run(root.createDirectoryAt("d", CreationAccess::Default)).has_value()); auto const nf = SymlinkPolicy::NoFollow; auto const sizeOf = [&](std::string name) { return fixture.run(root.statAt(nf, std::move(name)))->size; @@ -844,12 +852,150 @@ TEST_CASE("contract: a final link is followed where the call says so, and no fur CHECK(fixture.run(root.statAt(SymlinkPolicy::NoFollow, "absent"))->type == DescriptorType::RegularFile); } +namespace +{ + +/// The access @p descriptor's own handle reports; fails the case where the stat does not answer. +[[nodiscard]] std::optional accessOf(DescriptorFixture const& fixture, IDescriptor& descriptor) +{ + auto const status = fixture.run(descriptor.stat()); + REQUIRE(status.has_value()); + return status->access; +} + +} // namespace + +TEST_CASE("contract: an OwnerOnly file is owner-only", "[fs][contract][access]") +{ + auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); + auto file = + fixture.run(fixture.root().openAt(SymlinkPolicy::NoFollow, + "secret", + OpenFlags::Create | OpenFlags::Exclusive | OpenFlags::OwnerOnly, + DescriptorFlags::Read | DescriptorFlags::Write)); + REQUIRE(file.has_value()); + CHECK(accessOf(fixture, **file) == AccessScope::OwnerOnly); + // By name too, where the file system reads it without a handle of its own. + auto const byName = fixture.run(fixture.root().statAt(SymlinkPolicy::NoFollow, "secret")); + REQUIRE(byName.has_value()); + CHECK((!byName->access.has_value() || *byName->access == AccessScope::OwnerOnly)); +} + +TEST_CASE("contract: an OwnerOnly directory is owner-only", "[fs][contract][access]") +{ + auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); + REQUIRE(fixture.run(fixture.root().createDirectoryAt("keys", CreationAccess::OwnerOnly)).has_value()); + auto directory = fixture.run( + fixture.root().openAt(SymlinkPolicy::NoFollow, "keys", OpenFlags::Directory, DescriptorFlags::Read)); + REQUIRE(directory.has_value()); + CHECK(accessOf(fixture, **directory) == AccessScope::OwnerOnly); +} + +TEST_CASE("contract: OwnerOnly asks for an exclusive creation", "[fs][contract][access]") +{ + auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); + fixture.createFile("existing", "x"); + // Without Create there is nothing to make owner-only: the caller would get whatever is there. + CHECK(outcomeOf(fixture.run(fixture.root().openAt( + SymlinkPolicy::NoFollow, "existing", OpenFlags::OwnerOnly, DescriptorFlags::Read))) + == FsErrorCode::Invalid); + // Without Exclusive the file might be another's, whose ACL would be stripped and whose name unlinked. + for (auto const* const name: { "existing", "absent" }) + { + INFO(name); + CHECK(outcomeOf(fixture.run(fixture.root().openAt(SymlinkPolicy::NoFollow, + name, + OpenFlags::Create | OpenFlags::OwnerOnly, + DescriptorFlags::Write))) + == FsErrorCode::Invalid); + } + CHECK(outcomeOf(fixture.run(fixture.root().statAt(SymlinkPolicy::NoFollow, "absent"))) + == FsErrorCode::NoEntry); + auto readOnly = fixture.openRoot(DescriptorFlags::Read); + REQUIRE(readOnly.has_value()); + // A parent without MutateDirectory refuses it first, as it refuses every flag that changes entries. + CHECK(outcomeOf(fixture.run((*readOnly)->openAt( + SymlinkPolicy::NoFollow, "existing", OpenFlags::OwnerOnly, DescriptorFlags::Read))) + == FsErrorCode::NotPermitted); + CHECK( + outcomeOf(fixture.run((*readOnly)->openAt( + SymlinkPolicy::NoFollow, "new", OpenFlags::Create | OpenFlags::OwnerOnly, DescriptorFlags::Read))) + == FsErrorCode::NotPermitted); +} + +TEST_CASE("contract: access is read on the open handle", "[fs][contract][access]") +{ + auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); + auto& root = fixture.root(); + auto file = fixture.run(root.openAt(SymlinkPolicy::NoFollow, + "key", + OpenFlags::Create | OpenFlags::Exclusive | OpenFlags::OwnerOnly, + DescriptorFlags::Read)); + REQUIRE(file.has_value()); + fixture.createFile("planted", "attacker"); + auto const planted = fixture.run(root.statAt(SymlinkPolicy::NoFollow, "planted")); + REQUIRE(planted.has_value()); + if (planted->access == AccessScope::OwnerOnly) + SKIP("a Default file is owner-only here (an owner-only umask or directory ACL); the OS's own case " + "widens one explicitly"); + // Someone renames a file anyone may write over the name: the handle still answers for its own object. + auto const renamed = fixture.run(root.renameAt("planted", &root, "key")); + if (!renamed && fixture.kind() == FixtureKind::Native && core::fs::test::runsUnderWine()) + SKIP("wine refuses to replace a file that is open (" << renamed.error().toString() << ")"); + REQUIRE(renamed.has_value()); + CHECK(accessOf(fixture, **file) == AccessScope::OwnerOnly); + auto const byName = fixture.run(root.statAt(SymlinkPolicy::NoFollow, "key")); + REQUIRE(byName.has_value()); + CHECK(byName->access == planted->access); +} + +TEST_CASE("contract: a foreign owner is ForeignOwner", "[fs][contract][access]") +{ + // The model only: a native object of another owner needs a privilege, which each OS's own case + // takes where it has it. + auto fixture = DescriptorFixture::create(FixtureKind::InMemory); + fixture.createFile("theirs", "x"); + fixture.inMemory().setAccessFacts("root/theirs", + AccessFacts { .owner = AccessFacts::Owner::Other, + .posixMode = 0600, + .acl = AccessFacts::AclState::Absent, + .entries = {} }); + auto file = fixture.run( + fixture.root().openAt(SymlinkPolicy::NoFollow, "theirs", OpenFlags::None, DescriptorFlags::Read)); + REQUIRE(file.has_value()); + CHECK(accessOf(fixture, **file) == AccessScope::ForeignOwner); +} + +TEST_CASE("contract: renameAt replaces an existing file atomically", "[fs][contract]") +{ + auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); + auto& root = fixture.root(); + fixture.createFile("a", "new bytes"); + fixture.createFile("b", "old"); + auto reader = + fixture.run(root.openAt(SymlinkPolicy::NoFollow, "b", OpenFlags::None, DescriptorFlags::Read)); + REQUIRE(reader.has_value()); + + // Windows replaces an open file only with POSIX semantics (FileRenameInformationEx, NTFS). + auto const renamed = fixture.run(root.renameAt("a", &root, "b")); + if (!renamed && fixture.kind() == FixtureKind::Native && core::fs::test::runsUnderWine()) + SKIP("wine refuses to replace a file that is open (" << renamed.error().toString() << ")"); + REQUIRE(renamed.has_value()); + CHECK(outcomeOf(fixture.run(root.statAt(SymlinkPolicy::NoFollow, "a"))) == FsErrorCode::NoEntry); + auto replaced = + fixture.run(root.openAt(SymlinkPolicy::NoFollow, "b", OpenFlags::None, DescriptorFlags::Read)); + REQUIRE(replaced.has_value()); + CHECK(textOf(fixture.run((*replaced)->read(64, 0)).value().bytes) == "new bytes"); + // The reader that held the old b still reads the old bytes: no moment had b half-written. + CHECK(textOf(fixture.run((*reader)->read(64, 0)).value().bytes) == "old"); +} + TEST_CASE("contract: a directory's descriptor reads no bytes", "[fs][contract]") { // POSIX's pread answers EISDIR, Windows' ReadFile ERROR_INVALID_FUNCTION: both are IsDirectory. auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); auto& root = fixture.root(); - REQUIRE(fixture.run(root.createDirectoryAt("dir")).has_value()); + REQUIRE(fixture.run(root.createDirectoryAt("dir", CreationAccess::Default)).has_value()); auto directory = fixture.run(root.openAt(SymlinkPolicy::NoFollow, "dir", OpenFlags::Directory, DescriptorFlags::Read)); REQUIRE(directory.has_value()); diff --git a/src/core/fs/DescriptorEscape_test.cpp b/src/core/fs/DescriptorEscape_test.cpp index 1e60299b..eb128445 100644 --- a/src/core/fs/DescriptorEscape_test.cpp +++ b/src/core/fs/DescriptorEscape_test.cpp @@ -222,7 +222,8 @@ constexpr auto Ops = std::to_array({ { .operation = "createDirectoryAt", .aimedAt = "fresh", .start = [](Call c) -> Task { - co_return outcomeOf(co_await c.fixture->root().createDirectoryAt(c.path)); + co_return outcomeOf( + co_await c.fixture->root().createDirectoryAt(c.path, core::fs::CreationAccess::Default)); }, .onFinalLink = FsErrorCode::Exist }, }); @@ -271,7 +272,8 @@ DescriptorFixture escapeFixture(Variant const& variant) auto fixture = DescriptorFixture::create(variant.kind, { .strategy = variant.strategy }); if (fixture.requireSymlinks() == SymlinkSupport::Unavailable) return fixture; - REQUIRE(fixture.run(fixture.root().createDirectoryAt("a")).has_value()); + REQUIRE( + fixture.run(fixture.root().createDirectoryAt("a", core::fs::CreationAccess::Default)).has_value()); fixture.createFile("f", "inside"); REQUIRE(fixture.run(fixture.root().symlinkAt("../", "up")).has_value()); REQUIRE(fixture.run(fixture.root().symlinkAt("..", "uplink")).has_value()); @@ -319,7 +321,8 @@ TEST_CASE("a symlink cycle ends in Loop, not a hang", "[fs][escape]") CHECK(outcomeOf(fixture.run(root.statAt(SymlinkPolicy::Follow, "ping"))) == FsErrorCode::Loop); CHECK(outcomeOf(fixture.run(root.statAt(SymlinkPolicy::NoFollow, "ping/x"))) == FsErrorCode::Loop); - CHECK(outcomeOf(fixture.run(root.createDirectoryAt("pong/new"))) == FsErrorCode::Loop); + CHECK(outcomeOf(fixture.run(root.createDirectoryAt("pong/new", core::fs::CreationAccess::Default))) + == FsErrorCode::Loop); CHECK(outcomeOf(fixture.run( root.openAt(SymlinkPolicy::NoFollow, "ping/f", OpenFlags::Create, DescriptorFlags::Write))) == FsErrorCode::Loop); diff --git a/src/core/fs/DescriptorTestSupport.hpp b/src/core/fs/DescriptorTestSupport.hpp index 82c9fd89..5530c17e 100644 --- a/src/core/fs/DescriptorTestSupport.hpp +++ b/src/core/fs/DescriptorTestSupport.hpp @@ -43,6 +43,13 @@ namespace core::fs::test { +/// Whether this process runs under wine rather than on Windows or a POSIX system. Defined per +/// platform (`posix/DescriptorTestSupport.cpp`, `windows/DescriptorTestSupport.cpp`); only a binary +/// that links one of them may call it. A case uses it to accept a behaviour wine has and no native +/// file system does, and to fail where the same behaviour shows natively. A @c bool because the +/// name asks it. +[[nodiscard]] bool runsUnderWine() noexcept; + /// Which implementation of @c IDescriptorFileSystem a fixture builds. enum class FixtureKind : std::uint8_t { @@ -309,6 +316,15 @@ class DescriptorFixture /// @return The file system. [[nodiscard]] IDescriptorFileSystem& fileSystem() const noexcept { return *_fileSystem; } + /// @return The model under an in-memory fixture, for a setup no descriptor can make. + /// @throws std::logic_error For a native fixture. + [[nodiscard]] testing::InMemoryDescriptorFileSystem& inMemory() const + { + if (_inMemory == nullptr) + throw std::logic_error { "DescriptorFixture::inMemory: only an in-memory fixture has a model" }; + return *_inMemory; + } + /// @return The directory the root is preopened on, in the host's terms. [[nodiscard]] std::filesystem::path const& hostDirectory() const noexcept { return _hostDirectory; } @@ -381,7 +397,7 @@ class DescriptorFixture for (auto const& name: names | std::views::take(names.size() - 1)) { parent += parent.empty() ? name : "/" + name; - if (auto made = run(root().createDirectoryAt(parent)); + if (auto made = run(root().createDirectoryAt(parent, CreationAccess::Default)); !made && made.error().code != FsErrorCode::Exist) throw std::runtime_error { "DescriptorFixture::writeFile: " + made.error().toString() }; } @@ -408,7 +424,7 @@ class DescriptorFixture /// @throws std::runtime_error Where it could not. void createOutsideDirectory(std::string const& name) { - if (auto made = run(outside().createDirectoryAt(name)); !made) + if (auto made = run(outside().createDirectoryAt(name, CreationAccess::Default)); !made) throw std::runtime_error { "DescriptorFixture::createOutsideDirectory: " + made.error().toString() }; _decoys.push_back(name); diff --git a/src/core/fs/DirectoryStream_test.cpp b/src/core/fs/DirectoryStream_test.cpp index 974cae4d..ddb81d7b 100644 --- a/src/core/fs/DirectoryStream_test.cpp +++ b/src/core/fs/DirectoryStream_test.cpp @@ -76,7 +76,8 @@ void populate(DescriptorFixture const& fixture) { for (auto const index: std::views::iota(std::size_t { 0 }, FileCount)) fixture.createFile(fileName(index), "x"); - REQUIRE(fixture.run(fixture.root().createDirectoryAt("sub")).has_value()); + REQUIRE( + fixture.run(fixture.root().createDirectoryAt("sub", core::fs::CreationAccess::Default)).has_value()); } std::unique_ptr openStream(DescriptorFixture const& fixture, IDescriptor& directory) @@ -143,7 +144,8 @@ TEST_CASE("directory stream: a symbolic link is typed as one, never followed", " if (fixture.requireSymlinks() == SymlinkSupport::Unavailable) SKIP("this file system cannot create symbolic links"); fixture.createFile("f", "x"); - REQUIRE(fixture.run(fixture.root().createDirectoryAt("d")).has_value()); + REQUIRE( + fixture.run(fixture.root().createDirectoryAt("d", core::fs::CreationAccess::Default)).has_value()); REQUIRE(fixture.run(fixture.root().symlinkAt("f", "to-file")).has_value()); REQUIRE(fixture.run(fixture.root().symlinkAt("d", "to-directory")).has_value()); REQUIRE(fixture.run(fixture.root().symlinkAt("missing", "dangling")).has_value()); @@ -265,7 +267,8 @@ TEST_CASE("directory stream: a directory changed while it is read is read to an // in batches the system has not read yet. for (auto const index: std::views::iota(std::size_t { 0 }, LongCount)) fixture.createFile(longName(index), "x"); - REQUIRE(fixture.run(fixture.root().createDirectoryAt("sub")).has_value()); + REQUIRE( + fixture.run(fixture.root().createDirectoryAt("sub", core::fs::CreationAccess::Default)).has_value()); auto stream = openStream(fixture, fixture.root()); // Every tenth file is removed, unless the stream has handed it out already, and as many new ones @@ -399,7 +402,8 @@ TEST_CASE("metadataHashAt: equals the hash of a descriptor of the same object", { auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); fixture.createFile("f", "x"); - REQUIRE(fixture.run(fixture.root().createDirectoryAt("d")).has_value()); + REQUIRE( + fixture.run(fixture.root().createDirectoryAt("d", core::fs::CreationAccess::Default)).has_value()); for (auto const* name: { "f", "d" }) { CAPTURE(name); diff --git a/src/core/fs/NativeDescriptor_test.cpp b/src/core/fs/NativeDescriptor_test.cpp index 9a1cce1f..555c43c1 100644 --- a/src/core/fs/NativeDescriptor_test.cpp +++ b/src/core/fs/NativeDescriptor_test.cpp @@ -102,7 +102,7 @@ constexpr auto ParkRows = std::to_array({ } }, { "createDirectoryAt", [](ParkContext c) -> core::async::Task { - co_return outcomeOf(co_await c.root->createDirectoryAt("new")); + co_return outcomeOf(co_await c.root->createDirectoryAt("new", core::fs::CreationAccess::Default)); } }, { "statAt", [](ParkContext c) -> core::async::Task { @@ -170,7 +170,8 @@ TEST_CASE("native: every descriptor operation parks on the blocking executor", " CAPTURE(row.operation); auto fixture = DescriptorFixture::createNative(); fixture.createFile("f", "content"); - REQUIRE(fixture.run(fixture.root().createDirectoryAt("sub")).has_value()); + REQUIRE(fixture.run(fixture.root().createDirectoryAt("sub", core::fs::CreationAccess::Default)) + .has_value()); if (fixture.requireSymlinks() == SymlinkSupport::Available) REQUIRE(fixture.run(fixture.root().symlinkAt("f", "link")).has_value()); auto const file = openExisting(fixture, "f", DescriptorFlags::Read | DescriptorFlags::Write); @@ -303,7 +304,8 @@ constexpr auto BarPolicy = core::fs::PathPolicy { TEST_CASE("native: a name never holds what the kernel splits on, whatever the policy", "[fs][native]") { auto fixture = DescriptorFixture::createNative({ .policy = &BarPolicy }); - REQUIRE(fixture.run(fixture.root().createDirectoryAt("a")).has_value()); + REQUIRE( + fixture.run(fixture.root().createDirectoryAt("a", core::fs::CreationAccess::Default)).has_value()); fixture.createFile("f", "content"); auto const nf = SymlinkPolicy::NoFollow; @@ -311,7 +313,9 @@ TEST_CASE("native: a name never holds what the kernel splits on, whatever the po for (auto const* name: { "a/b", "a/." }) { CAPTURE(name); - CHECK(outcomeOf(fixture.run(fixture.root().createDirectoryAt(name))) == FsErrorCode::Invalid); + CHECK( + outcomeOf(fixture.run(fixture.root().createDirectoryAt(name, core::fs::CreationAccess::Default))) + == FsErrorCode::Invalid); CHECK(outcomeOf(fixture.run(fixture.root().statAt(nf, name))) == FsErrorCode::Invalid); CHECK( outcomeOf(fixture.run(fixture.root().openAt(nf, name, OpenFlags::Create, DescriptorFlags::Write))) diff --git a/src/core/fs/Rights.cpp b/src/core/fs/Rights.cpp index 2369063e..3a43bda3 100644 --- a/src/core/fs/Rights.cpp +++ b/src/core/fs/Rights.cpp @@ -83,7 +83,7 @@ FsResult checkOpenRights(DescriptorFlags parent, OpenFlags open, Descripto // wasmtime's order: what the parent may not grant is NotPermitted before the flags themselves // are judged. auto const changesEntries = hasFlag(open, OpenFlags::Create) || hasFlag(open, OpenFlags::Truncate) - || hasFlag(open, OpenFlags::Exclusive); + || hasFlag(open, OpenFlags::Exclusive) || hasFlag(open, OpenFlags::OwnerOnly); if (hasFlag(child, Read) && !hasFlag(parent, Read)) return refuse(FsErrorCode::NotPermitted); auto const needsMutate = hasFlag(child, Write) || hasFlag(child, MutateDirectory) || changesEntries; @@ -91,6 +91,12 @@ FsResult checkOpenRights(DescriptorFlags parent, OpenFlags open, Descripto return refuse(FsErrorCode::NotPermitted); if (hasFlag(open, OpenFlags::Directory) && changesEntries) return refuse(FsErrorCode::Invalid); + // Owner-only is a property of a creation this call surely made: without Create the caller would + // get whatever is there, and without Exclusive an ACL stripped, or a name unlinked on failure, + // could be another's. + if (hasFlag(open, OpenFlags::OwnerOnly) + && (!hasFlag(open, OpenFlags::Create) || !hasFlag(open, OpenFlags::Exclusive))) + return refuse(FsErrorCode::Invalid); if (hasFlag(open, OpenFlags::Directory) && hasFlag(child, Write)) return refuse(FsErrorCode::IsDirectory); return {}; diff --git a/src/core/fs/Rights.hpp b/src/core/fs/Rights.hpp index da3303f1..f244a6a2 100644 --- a/src/core/fs/Rights.hpp +++ b/src/core/fs/Rights.hpp @@ -60,11 +60,12 @@ struct RightsRow /// Checks what a child opened by @c IDescriptor::openAt may carry, against its parent directory: /// - `Read` needs the parent's `Read`; -/// - `Write` or `MutateDirectory`, and `Create`, `Truncate` or `Exclusive`, need the parent's -/// `MutateDirectory`; +/// - `Write` or `MutateDirectory`, and `Create`, `Truncate`, `Exclusive` or `OwnerOnly`, need the +/// parent's `MutateDirectory`; /// - the three sync flags are a mode, not a right, and need nothing; /// - then, as wasmtime checks them only once the rights hold: `Directory` with `Create`, -/// `Truncate` or `Exclusive` is `Invalid`, and a directory never carries `Write` (`IsDirectory`). +/// `Truncate`, `Exclusive` or `OwnerOnly` is `Invalid`, and a directory never carries `Write` +/// (`IsDirectory`); `OwnerOnly` without both `Create` and `Exclusive` is `Invalid`. /// @param parent The flags of the directory @c openAt is called on. /// @param open How the child is opened. /// @param child The flags the child asks for. diff --git a/src/core/fs/bsd/AccessFacts.cpp b/src/core/fs/bsd/AccessFacts.cpp new file mode 100644 index 00000000..3f456ce8 --- /dev/null +++ b/src/core/fs/bsd/AccessFacts.cpp @@ -0,0 +1,97 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// Who may reach an object on FreeBSD: the owner and the mode of an fstat, and where the file system +// keeps NFSv4 ACLs (ZFS, UFS mounted with nfsv4acls), the ACL of the very handle. A trivial one says +// no more than the mode; any other is judged Shared, since its entries can grant anyone. A POSIX.1e +// ACL, UFS's other kind, is bounded by the mode's group bits, as on Linux. +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include + +namespace core::fs::detail +{ + +namespace +{ + + struct AclDeleter + { + void operator()(std::remove_pointer_t* acl) const noexcept { ::acl_free(acl); } + }; + +} // namespace + +std::optional accessFactsOf(int handle, struct ::stat const& status) +{ + // An ACL is read from a handle or not at all: by name, another user could rename in between. + if (handle < 0) + return std::nullopt; + auto facts = modeFactsOf(status); + errno = 0; // -1 with errno untouched answers nothing, and fails closed below. + auto const nfs4 = ::fpathconf(handle, _PC_ACL_NFS4); + // 0, or EINVAL where the file system does not know the variable at all, is no NFSv4 ACL. + if (nfs4 == 0 || (nfs4 < 0 && errno == EINVAL)) + return facts; + if (nfs4 < 0) + return std::nullopt; + auto const acl = + std::unique_ptr, AclDeleter> { ::acl_get_fd_np(handle, ACL_TYPE_NFS4) }; + if (acl == nullptr) + return std::nullopt; + auto trivial = 0; + if (::acl_is_trivial_np(acl.get(), &trivial) != 0) + return std::nullopt; + if (trivial != 0) + { + facts.acl = AccessFacts::AclState::Trivial; + return facts; + } + // Its entries are not judged one by one: any non-trivial ACL can grant someone else. + facts.acl = AccessFacts::AclState::Present; + facts.entries.push_back(AccessEntry {}); + return facts; +} + +FsResult stripInheritedAcl(int handle, ::mode_t mode) +{ + // Only an NFSv4 ACL inherits entries beyond the mode (ZFS aclinherit, UFS nfsv4acls); a + // POSIX.1e default ACL is capped by the mode, as on Linux. + errno = 0; // -1 with errno untouched answers nothing, and fails closed below. + auto const nfs4 = ::fpathconf(handle, _PC_ACL_NFS4); + if (nfs4 == 0 || (nfs4 < 0 && errno == EINVAL)) + return {}; + if (nfs4 < 0) + return errnoError("fpathconf(_PC_ACL_NFS4)"); + auto const inherited = + std::unique_ptr, AclDeleter> { ::acl_get_fd_np(handle, ACL_TYPE_NFS4) }; + if (inherited == nullptr) + return errnoError("acl_get_fd_np(ACL_TYPE_NFS4)"); + // acl_strip_np(3): the trivial ACL, equivalent to the mode alone. Then the mode again, which ZFS + // may have recomputed from the inherited entries. + auto const trivial = + std::unique_ptr, AclDeleter> { ::acl_strip_np(inherited.get(), 0) }; + if (trivial == nullptr) + return errnoError("acl_strip_np"); + if (::acl_set_fd_np(handle, trivial.get(), ACL_TYPE_NFS4) != 0) + return errnoError("acl_set_fd_np(ACL_TYPE_NFS4)"); + if (::fchmod(handle, mode) != 0) + return errnoError("fchmod"); + return {}; +} + +OwnerOnlyCreation nativeOwnerOnlyCreation() noexcept +{ + // An NFSv4 ACL a directory hands down can widen a new object. + return OwnerOnlyCreation::Staged; +} + +} // namespace core::fs::detail diff --git a/src/core/fs/bsd/InheritableAcl_test.cpp b/src/core/fs/bsd/InheritableAcl_test.cpp new file mode 100644 index 00000000..74a2dbf9 --- /dev/null +++ b/src/core/fs/bsd/InheritableAcl_test.cpp @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// FreeBSD's inheritable ACL: an NFSv4 entry (setfacl -m on ZFS, or UFS mounted nfsv4acls) granting everyone@ +// every right, inherited by files and directories. +#include + +#include +#include +#include + +namespace core::fs::test +{ + +std::vector inheritableAclCommand(std::filesystem::path const& directory) +{ + return { "setfacl", "-m", "everyone@:full_set:fd:allow", directory.string() }; +} + +} // namespace core::fs::test diff --git a/src/core/fs/darwin/AccessFacts.cpp b/src/core/fs/darwin/AccessFacts.cpp new file mode 100644 index 00000000..adec600b --- /dev/null +++ b/src/core/fs/darwin/AccessFacts.cpp @@ -0,0 +1,110 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// Who may reach an object on macOS: the owner and the mode of an fstat, and the extended ACL of the +// very handle. macOS keeps no ACL equivalent to the mode, so any entry at all is judged Shared (an +// ALLOW for another user would be the one that matters, but a reader that guesses fails open). +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace core::fs::detail +{ + +namespace +{ + + struct AclDeleter + { + void operator()(std::remove_pointer_t* acl) const noexcept { ::acl_free(acl); } + }; + + /// What a file system without extended ACLs answers an ACL call with. + constexpr auto NoAclErrnos = std::to_array({ ENOTSUP, EOPNOTSUPP }); + + [[nodiscard]] bool isNoAcl(int error) noexcept + { + return std::ranges::find(NoAclErrnos, error) != NoAclErrnos.end(); + } + + /// Whether @p handle's file system keeps extended ACLs at all (`_PC_EXTENDED_SECURITY_NP`, as + /// FreeBSD's reader asks `_PC_ACL_NFS4`); nullopt where it cannot be asked. + [[nodiscard]] std::optional keepsAcls(int handle) noexcept + { + // errno is cleared first: -1 with errno untouched answers nothing, and fails closed. + errno = 0; + auto const answer = ::fpathconf(handle, _PC_EXTENDED_SECURITY_NP); + if (answer > 0) + return true; + if (answer == 0 || errno == EINVAL) + return false; + return std::nullopt; + } + +} // namespace + +std::optional accessFactsOf(int handle, struct ::stat const& status) +{ + // An ACL is read from a handle or not at all: by name, another user could rename in between. + if (handle < 0) + return std::nullopt; + auto facts = modeFactsOf(status); + // A file system without extended ACLs (some FAT, SMB, NFS mounts) leaves the mode all there is. + auto const keeps = keepsAcls(handle); + if (!keeps.has_value()) + return std::nullopt; + if (!*keeps) + return facts; + auto const acl = std::unique_ptr, AclDeleter> { ::acl_get_fd_np( + handle, ACL_TYPE_EXTENDED) }; + if (acl == nullptr) + { + // ENOENT is the answer for an object with no extended ACL, ENOTSUP for a file system with + // none; any other failure tells nothing. + if (errno == ENOENT || isNoAcl(errno)) + return facts; + return std::nullopt; + } + auto entry = acl_entry_t {}; + if (::acl_get_entry(acl.get(), ACL_FIRST_ENTRY, &entry) != 0) + return facts; + facts.acl = AccessFacts::AclState::Present; + facts.entries.push_back(AccessEntry {}); + return facts; +} + +FsResult stripInheritedAcl(int handle, ::mode_t /*mode*/) +{ + // A file system without extended ACLs handed nothing down: the mode alone is verified after. + auto const keeps = keepsAcls(handle); + if (!keeps.has_value()) + return errnoError("fpathconf(_PC_EXTENDED_SECURITY_NP)"); + if (!*keeps) + return {}; + // An empty extended ACL replaces whatever the new object inherited (acl_set_fd_np(3)); the + // mode was never touched by the inheritance. + auto const empty = std::unique_ptr, AclDeleter> { ::acl_init(0) }; + if (empty == nullptr) + return errnoError("acl_init"); + if (::acl_set_fd_np(handle, empty.get(), ACL_TYPE_EXTENDED) != 0 && !isNoAcl(errno)) + return errnoError("acl_set_fd_np(ACL_TYPE_EXTENDED)"); + return {}; +} + +OwnerOnlyCreation nativeOwnerOnlyCreation() noexcept +{ + // An extended ACL a directory hands down can widen a new object. + return OwnerOnlyCreation::Staged; +} + +} // namespace core::fs::detail diff --git a/src/core/fs/darwin/InheritableAcl_test.cpp b/src/core/fs/darwin/InheritableAcl_test.cpp new file mode 100644 index 00000000..61bb6639 --- /dev/null +++ b/src/core/fs/darwin/InheritableAcl_test.cpp @@ -0,0 +1,21 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// macOS's inheritable ACL: an extended ACL entry (chmod +a) granting everyone read and write, inherited by +// the files and directories created inside. +#include + +#include +#include +#include + +namespace core::fs::test +{ + +std::vector inheritableAclCommand(std::filesystem::path const& directory) +{ + return { + "chmod", "+a", "everyone allow read,write,append,file_inherit,directory_inherit", directory.string() + }; +} + +} // namespace core::fs::test diff --git a/src/core/fs/detail/NativeSupport.cpp b/src/core/fs/detail/NativeSupport.cpp index c6ef27c0..2a0e7090 100644 --- a/src/core/fs/detail/NativeSupport.cpp +++ b/src/core/fs/detail/NativeSupport.cpp @@ -77,7 +77,9 @@ NativeContext::NativeContext(async::IExecutor& homeExecutor, IRandom& random, NativeFileSystemOptions fileSystemOptions, std::string_view separators, - INtFiles const* files): + INtFiles const* files, + std::shared_ptr security, + std::shared_ptr creator): home { &homeExecutor }, blocking { &blockingExecutor }, wallClock { &clock }, @@ -90,7 +92,9 @@ NativeContext::NativeContext(async::IExecutor& homeExecutor, && fileSystemOptions.maxSymlinkHops >= DefaultMaxSymlinkHops ? makeBestBeneathOpener() : nullptr }, - ntFiles { files } + ntFiles { files }, + ownerSecurity { std::move(security) }, + ownerOnlyCreator { std::move(creator) } { random.fill(secret); } diff --git a/src/core/fs/detail/NativeSupport.hpp b/src/core/fs/detail/NativeSupport.hpp index 53af6848..99387673 100644 --- a/src/core/fs/detail/NativeSupport.hpp +++ b/src/core/fs/detail/NativeSupport.hpp @@ -32,7 +32,9 @@ namespace core::fs::detail { -class INtFiles; // windows/WindowsPathWalk.hpp +class INtFiles; // windows/WindowsPathWalk.hpp +class OwnerSecurity; // windows/OwnerSecurity.hpp +class OwnerOnlyCreator; // posix/OwnerOnlyCreation.hpp /// @param code What refused. /// @return The refusal, with no system code. @@ -67,6 +69,12 @@ struct NativeContext /// The NT calls a Windows file system opens, inspects and identifies through: the system's, or a /// test's scripted ones. Null on every other system. INtFiles const* ntFiles = nullptr; + /// The process token's user, and the security descriptors an owner-only creation is made with, + /// read once, when the file system is built. Null on every system but Windows. + std::shared_ptr ownerSecurity; + /// What makes an owner-only file or directory, its staging key drawn when the file system is + /// built. Null on Windows. + std::shared_ptr ownerOnlyCreator; /// @param homeExecutor Where every operation resumes. /// @param blockingExecutor Where every system call runs. @@ -75,6 +83,8 @@ struct NativeContext /// @param fileSystemOptions What the file system is built with; a null policy is the native one. /// @param separators What this kernel splits a name on. /// @param files The NT calls on Windows; null elsewhere. Must outlive the file system. + /// @param security The owner's security on Windows; null elsewhere. + /// @param creator What makes owner-only objects on POSIX; null on Windows. /// The strategy's opener is made here: under `Best`, from @c makeBestBeneathOpener. NativeContext(async::IExecutor& homeExecutor, async::IExecutor& blockingExecutor, @@ -82,7 +92,9 @@ struct NativeContext IRandom& random, NativeFileSystemOptions fileSystemOptions, std::string_view separators, - INtFiles const* files); + INtFiles const* files, + std::shared_ptr security, + std::shared_ptr creator); }; /// How a native file system and its descriptors share their @c NativeContext. diff --git a/src/core/fs/posix/AccessFacts.cpp b/src/core/fs/posix/AccessFacts.cpp new file mode 100644 index 00000000..121e2ba5 --- /dev/null +++ b/src/core/fs/posix/AccessFacts.cpp @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// Who may reach an object on Linux, and on every POSIX system without an ACL of its own: the owner +// and the mode of an fstat. A POSIX.1e ACL needs no reading of its own here: its named entries are +// bounded by the mask, which the mode's group bits show, so a mode with no group or other bit +// leaves no named entry any right. Nothing else is read, so the facts hold for an fstatat by name +// as for a handle. +#include +#include +#include + +#include + +#include + +namespace core::fs::detail +{ + +std::optional accessFactsOf(int /*handle*/, struct ::stat const& status) +{ + return modeFactsOf(status); +} + +FsResult stripInheritedAcl(int /*handle*/, ::mode_t /*mode*/) +{ + // A POSIX.1e default ACL replaces the umask step, but each entry it hands down is ANDed with the + // mode argument's bits: the mask with the group bits, other with the other bits. Under 0600 or + // 0700 both are zero, so no named entry and no other is left any right; nothing to strip. + return {}; +} + +OwnerOnlyCreation nativeOwnerOnlyCreation() noexcept +{ + // The mode caps every entry a default ACL hands down. + return OwnerOnlyCreation::Direct; +} + +} // namespace core::fs::detail diff --git a/src/core/fs/posix/DescriptorTestSupport.cpp b/src/core/fs/posix/DescriptorTestSupport.cpp new file mode 100644 index 00000000..1f13c02a --- /dev/null +++ b/src/core/fs/posix/DescriptorTestSupport.cpp @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The POSIX half of DescriptorTestSupport.hpp's platform questions: no POSIX process runs under wine. +#include + +namespace core::fs::test +{ + +bool runsUnderWine() noexcept +{ + return false; +} + +} // namespace core::fs::test diff --git a/src/core/fs/posix/InheritableAcl.hpp b/src/core/fs/posix/InheritableAcl.hpp new file mode 100644 index 00000000..930cac95 --- /dev/null +++ b/src/core/fs/posix/InheritableAcl.hpp @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// How a test plants, through the host, an ACL a new object inherits from its directory and that +/// grants others access: one command per OS, defined by a CMake-selected +/// `*/InheritableAcl_test.cpp` (`setfacl -d` on Linux, `chmod +a` on macOS, an NFSv4 `setfacl` on +/// FreeBSD). Test-only; never part of the module. + +#include +#include +#include + +namespace core::fs::test +{ + +/// @param directory An existing directory, by host path. +/// @return The command, as its argument vector, that gives @p directory an inheritable ACL granting +/// others read and write. +[[nodiscard]] std::vector inheritableAclCommand(std::filesystem::path const& directory); + +} // namespace core::fs::test diff --git a/src/core/fs/posix/InheritableAcl_test.cpp b/src/core/fs/posix/InheritableAcl_test.cpp new file mode 100644 index 00000000..523682e9 --- /dev/null +++ b/src/core/fs/posix/InheritableAcl_test.cpp @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The inheritable ACL of Linux and every POSIX system without one of its own: a POSIX.1e default ACL (setfacl +// -d) granting other, and the user nobody, everything. +#include + +#include +#include +#include + +namespace core::fs::test +{ + +std::vector inheritableAclCommand(std::filesystem::path const& directory) +{ + return { "setfacl", "-d", "-m", "u::rwx,g::rwx,o::rwx,u:nobody:rwx,m::rwx", directory.string() }; +} + +} // namespace core::fs::test diff --git a/src/core/fs/posix/OwnerOnlyCreation.cpp b/src/core/fs/posix/OwnerOnlyCreation.cpp new file mode 100644 index 00000000..afe4541c --- /dev/null +++ b/src/core/fs/posix/OwnerOnlyCreation.cpp @@ -0,0 +1,310 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// Owner-only creation on POSIX. Direct where the mode alone decides (Linux); staged where an +// inherited ACL could widen a new object before it is stripped (macOS, FreeBSD): +// +// 1. a fresh staging directory is made beside the target, 0700, and through its handle stripped +// of what it inherited and verified owner-only -- before anything is created inside it, so a +// user who opened it in the meantime holds a descriptor through which the kernel, checking +// search permission at each lookup, finds nothing; +// 2. the object is created inside it, where nothing can be inherited, and stripped and verified +// too; +// 3. it is moved to its final name: a file by linkat, which fails where the name exists, as +// O_EXCL does; a directory by renameat over an empty placeholder made with the final name by +// mkdirat, which is what fails where the name exists, and which is stripped and verified as +// well, so that what it inherited lets nobody leave an entry in it under the final name; +// 4. the staging directory is removed. +// +// A staging name is an HMAC of a counter under a key drawn once per file system, so nobody can make +// one in advance to stand in the way. Every step that fails removes what the earlier ones made, +// through the parent's handle. +#include + +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace core::fs::detail +{ + +namespace +{ + + constexpr ::mode_t OwnerOnlyFileMode = 0600; + constexpr ::mode_t OwnerOnlyDirectoryMode = 0700; + + /// The name of the object inside its staging directory, which holds nothing else. + constexpr auto StagedName = ".object"; + + /// How many staging names are tried before giving up: each one that exists (another flow's, + /// or one an attacker made) is skipped, never used. + constexpr auto MaxStagingAttempts = 64; + + /// How many bytes of a staging name's HMAC its hex spells. + constexpr auto StagingNameBytes = std::size_t { 16 }; + + /// A staging directory: its name beneath the parent, and its handle. + struct Staging + { + std::string name; + UniqueHandle handle; + }; + + [[nodiscard]] UniqueHandle openDirectory(int directory, char const* name) + { + return UniqueHandle { retryOnInterrupt( + [&] { return ::openat(directory, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC); }) }; + } + + /// What a staging directory still holds when it is removed. + enum class Leftover : std::uint8_t + { + Nothing, ///< The object was never made, or has been renamed out. + File, ///< A file, unlinked (linked to its final name, or a failure's). + Directory, ///< A directory, removed. + }; + + /// Removes @p staging and what @p leftover says it holds. Best effort: a staging directory + /// someone filled before its strip stays behind, owner-only. + void removeStaging(int directory, Staging const& staging, Leftover leftover) + { + if (leftover != Leftover::Nothing) + ::unlinkat(staging.handle.get(), StagedName, leftover == Leftover::Directory ? AT_REMOVEDIR : 0); + ::unlinkat(directory, staging.name.c_str(), AT_REMOVEDIR); + } + + /// A refusal to go on with an object that does not read owner-only. + [[nodiscard]] std::unexpected notOwnerOnly() + { + return std::unexpected { FsError { .code = FsErrorCode::NotPermitted, + .systemCode = 0, + .context = "the new object is not owner-only" } }; + } + + /// Opens the directory just made as @p name beneath @p directory and holds it to owner-only. + [[nodiscard]] FsResult holdDirectory(OwnerOnlyCreator const& creator, + int directory, + char const* name) + { + auto const made = openDirectory(directory, name); + if (made.get() < 0) + return errnoError("openat(O_DIRECTORY)"); + return creator.holdOwnerOnly(made.get(), OwnerOnlyDirectoryMode); + } + + /// Makes a staging directory beneath @p directory, owner-only before it is returned. + [[nodiscard]] FsResult makeStaging(OwnerOnlyCreator const& creator, int directory) + { + for ([[maybe_unused]] auto const attempt: std::views::iota(0, MaxStagingAttempts)) + { + auto name = creator.nextStagingName(); + if (::mkdirat(directory, name.c_str(), OwnerOnlyDirectoryMode) != 0) + { + if (errno == EEXIST) + continue; + return errnoError("mkdirat(staging)"); + } + auto handle = openDirectory(directory, name.c_str()); + if (handle.get() < 0) + { + auto failed = errnoError("openat(staging)"); + ::unlinkat(directory, name.c_str(), AT_REMOVEDIR); + return failed; + } + if (auto held = creator.holdOwnerOnly(handle.get(), OwnerOnlyDirectoryMode); !held) + { + ::unlinkat(directory, name.c_str(), AT_REMOVEDIR); + return std::unexpected { held.error() }; + } + return Staging { .name = std::move(name), .handle = std::move(handle) }; + } + return std::unexpected { FsError { + .code = FsErrorCode::Exist, .systemCode = EEXIST, .context = "no free staging name" } }; + } + + [[nodiscard]] FsResult createFileDirect(OwnerOnlyCreator const& creator, + int directory, + std::string const& name, + int flags) + { + auto file = UniqueHandle { retryOnInterrupt( + [&] { return ::openat(directory, name.c_str(), flags, OwnerOnlyFileMode); }) }; + if (file.get() < 0) + return errnoError("openat"); + if (auto held = creator.holdOwnerOnly(file.get(), OwnerOnlyFileMode); !held) + { + // By name, which another process could have replaced since: reached only where the file + // system ignores the mode it was given (vfat or exfat under fmask, cifs under noperm), + // since Linux's mode caps every ACL entry. Whatever stands there was made under O_EXCL by + // this call or renamed over it by someone who could write the directory anyway. + ::unlinkat(directory, name.c_str(), 0); + return std::unexpected { held.error() }; + } + return file; + } + + [[nodiscard]] FsResult createFileStaged(OwnerOnlyCreator const& creator, + int directory, + std::string const& name, + int flags) + { + auto staging = makeStaging(creator, directory); + if (!staging) + return std::unexpected { staging.error() }; + auto file = UniqueHandle { retryOnInterrupt( + [&] { return ::openat(staging->handle.get(), StagedName, flags, OwnerOnlyFileMode); }) }; + if (file.get() < 0) + { + auto failed = errnoError("openat(staged)"); + removeStaging(directory, *staging, Leftover::Nothing); + return failed; + } + auto const held = + creator.holdOwnerOnly(file.get(), OwnerOnlyFileMode).and_then([&]() -> FsResult { + // linkat, not renameat: it refuses a name that exists, as O_EXCL does. + if (::linkat(staging->handle.get(), StagedName, directory, name.c_str(), 0) != 0) + return errnoError("linkat"); + return {}; + }); + removeStaging(directory, *staging, Leftover::File); + if (!held) + return std::unexpected { held.error() }; + return file; + } + + [[nodiscard]] FsResult createDirectoryDirect(OwnerOnlyCreator const& creator, + int directory, + std::string const& name) + { + if (::mkdirat(directory, name.c_str(), OwnerOnlyDirectoryMode) != 0) + return errnoError("mkdirat"); + auto held = holdDirectory(creator, directory, name.c_str()); + // By name, as a direct file's: reached where the file system ignores the mode (vfat, exfat, + // cifs under noperm). AT_REMOVEDIR removes nothing that is not an empty directory. + if (!held) + ::unlinkat(directory, name.c_str(), AT_REMOVEDIR); + return held; + } + + [[nodiscard]] FsResult createDirectoryStaged(OwnerOnlyCreator const& creator, + int directory, + std::string const& name) + { + auto staging = makeStaging(creator, directory); + if (!staging) + return std::unexpected { staging.error() }; + if (::mkdirat(staging->handle.get(), StagedName, OwnerOnlyDirectoryMode) != 0) + { + auto failed = errnoError("mkdirat(staged)"); + removeStaging(directory, *staging, Leftover::Nothing); + return failed; + } + if (auto held = holdDirectory(creator, staging->handle.get(), StagedName); !held) + { + removeStaging(directory, *staging, Leftover::Directory); + return held; + } + // The placeholder is what refuses an existing name; the rename replaces it, empty, at once. + // It is held to owner-only first: what it inherited could otherwise let another user leave + // an entry in it, which would fail the rename and keep their entry under the final name. + if (::mkdirat(directory, name.c_str(), OwnerOnlyDirectoryMode) != 0) + { + auto failed = errnoError("mkdirat"); + removeStaging(directory, *staging, Leftover::Directory); + return failed; + } + if (auto held = holdDirectory(creator, directory, name.c_str()); !held) + { + ::unlinkat(directory, name.c_str(), AT_REMOVEDIR); + removeStaging(directory, *staging, Leftover::Directory); + return held; + } + if (::renameat(staging->handle.get(), StagedName, directory, name.c_str()) != 0) + { + auto failed = errnoError("renameat"); + ::unlinkat(directory, name.c_str(), AT_REMOVEDIR); + removeStaging(directory, *staging, Leftover::Directory); + return failed; + } + removeStaging(directory, *staging, Leftover::Nothing); + return {}; + } + +} // namespace + +int systemStatHandle(int handle, struct ::stat* status) +{ + return ::fstat(handle, status); +} + +OwnerOnlyCreator::OwnerOnlyCreator(IRandom& random, OwnerOnlyCreation how, StatHandle statHandle): + _how { how }, _statHandle { std::move(statHandle) } +{ + random.fill(_stagingKey); +} + +std::string OwnerOnlyCreator::nextStagingName() const +{ + auto const count = _stagingCounter.fetch_add(1, std::memory_order_relaxed); + auto message = std::array {}; + for (auto const index: std::views::iota(std::size_t { 0 }, message.size())) + message[index] = static_cast(count >> (8U * index)); + auto const tag = hmacSha256(_stagingKey, message); + constexpr auto Digits = std::string_view { "0123456789abcdef" }; + auto name = std::string { ".core-cpp-owner-only." }; + for (auto const byte: std::span { tag }.first(StagingNameBytes)) + { + name += Digits[std::to_integer(byte) >> 4U]; + name += Digits[std::to_integer(byte) & 0xFU]; + } + return name; +} + +FsResult OwnerOnlyCreator::holdOwnerOnly(int handle, ::mode_t mode) const +{ + return stripInheritedAcl(handle, mode) + .and_then([&]() -> FsResult { + struct ::stat status {}; + if (_statHandle(handle, &status) != 0) + return errnoError("fstat"); + return status; + }) + .and_then([&](struct ::stat const& status) -> FsResult { + if (accessFactsOf(handle, status).transform(classifyAccess) == AccessScope::OwnerOnly) + return {}; + return notOwnerOnly(); + }); +} + +FsResult OwnerOnlyCreator::createFile(int directory, std::string const& name, int flags) const +{ + return _how == OwnerOnlyCreation::Staged ? createFileStaged(*this, directory, name, flags) + : createFileDirect(*this, directory, name, flags); +} + +FsResult OwnerOnlyCreator::createDirectory(int directory, std::string const& name) const +{ + return _how == OwnerOnlyCreation::Staged ? createDirectoryStaged(*this, directory, name) + : createDirectoryDirect(*this, directory, name); +} + +} // namespace core::fs::detail diff --git a/src/core/fs/posix/OwnerOnlyCreation.hpp b/src/core/fs/posix/OwnerOnlyCreation.hpp new file mode 100644 index 00000000..242f717c --- /dev/null +++ b/src/core/fs/posix/OwnerOnlyCreation.hpp @@ -0,0 +1,100 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// How the POSIX descriptors create a file or directory no other user can reach at any moment +/// (@c OpenFlags::OwnerOnly, @c CreationAccess::OwnerOnly). Private to the fs module. + +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace core::fs::detail +{ + +/// Where an owner-only object is created. +enum class OwnerOnlyCreation : std::uint8_t +{ + /// Under its final name, with mode 0600/0700 given to the creating call: right where no ACL a + /// directory hands down can widen the mode (Linux, whose default ACL entries the mode caps). + Direct, + /// Inside a fresh 0700 staging directory beside it, stripped of its inherited ACL and verified + /// before anything is created in it, then moved to its final name: where an inherited ACL could + /// widen the new object between its creation and a strip (macOS, FreeBSD). + Staged, +}; + +/// @return How this system creates owner-only objects; defined with its ACL reader +/// (`posix/`, `bsd/`, `darwin/AccessFacts.cpp`). +[[nodiscard]] CORE_FS_API OwnerOnlyCreation nativeOwnerOnlyCreation() noexcept; + +/// Reads the status of an open object: `fstat`, or a test's stand-in for a file system that +/// reports another mode than it was given (vfat or exfat under `fmask`, cifs under `noperm`). +using StatHandle = std::function; + +/// `fstat` itself, the @c StatHandle every native file system uses. +/// @param handle The open object. +/// @param status Where its status goes. +/// @return 0, or -1 with `errno` set. +[[nodiscard]] CORE_FS_API int systemStatHandle(int handle, struct ::stat* status); + +/// Creates files and directories beneath a held directory that no other user can reach at any +/// moment, as @c OwnerOnlyCreation says. One per file system, fixed at construction; safe to use +/// from every thread at once. Where any step fails, what was made is removed through the directory. +class CORE_FS_API OwnerOnlyCreator +{ + public: + /// @param random Draws the key of the staging names, once, here: nobody without it can tell a + /// staging name before it is made, so no name made in advance can stand in the way. + /// @param how Where an object is created. + /// @param statHandle How a new object's status is read back. + OwnerOnlyCreator(IRandom& random, + OwnerOnlyCreation how, + StatHandle statHandle = StatHandle { &systemStatHandle }); + + /// Creates the regular file @p name beneath @p directory, mode 0600. + /// @param directory The held parent. + /// @param name One component. + /// @param flags The `openat` flags, `O_CREAT | O_EXCL` among them. + /// @return The open file; `Exist` where @p name exists; `NotPermitted` where the new file does + /// not read owner-only; or what refused a step. + [[nodiscard]] FsResult createFile(int directory, std::string const& name, int flags) const; + + /// Creates the directory @p name beneath @p directory, mode 0700. + /// @param directory The held parent. + /// @param name One component. + /// @return Nothing; `Exist` where @p name exists; `NotPermitted` where the new directory does not + /// read owner-only; or what refused a step. + [[nodiscard]] FsResult createDirectory(int directory, std::string const& name) const; + + /// @return A staging name no earlier call returned and nobody without the key can predict: + /// HMAC-SHA-256 of a counter under the key, 128 bits of it in hex. + [[nodiscard]] std::string nextStagingName() const; + + /// Strips an ACL @p handle's new object inherited (@c stripInheritedAcl) and reads its access + /// back through the @c StatHandle. + /// @param handle The new object. + /// @param mode The mode it was created with. + /// @return Nothing once its handle reads owner-only; `NotPermitted` where it does not, or what + /// refused the stripping. + [[nodiscard]] FsResult holdOwnerOnly(int handle, ::mode_t mode) const; + + private: + std::array _stagingKey {}; + OwnerOnlyCreation _how; + StatHandle _statHandle; + mutable std::atomic _stagingCounter { 0 }; ///< Each call's own staging name. +}; + +} // namespace core::fs::detail diff --git a/src/core/fs/posix/OwnerOnly_test.cpp b/src/core/fs/posix/OwnerOnly_test.cpp new file mode 100644 index 00000000..c348b63b --- /dev/null +++ b/src/core/fs/posix/OwnerOnly_test.cpp @@ -0,0 +1,429 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// What the POSIX descriptors owe an owner-only creation: the mode is given to openat and mkdirat +// themselves, so no other user ever holds the object between its creation and a chmod; the umask can +// only take bits away. And what they read back: the access a handle reports comes from that handle's +// fstat, whatever has since been renamed over its name. +#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 + +using core::fs::AccessScope; +using core::fs::CreationAccess; +using core::fs::DescriptorFlags; +using core::fs::FsErrorCode; +using core::fs::OpenFlags; +using core::fs::SymlinkPolicy; +using core::fs::test::DescriptorFixture; + +namespace +{ + +/// Sets the process's umask for the case and restores it after. +class ScopedUmask +{ + public: + explicit ScopedUmask(::mode_t mask) noexcept: _previous { ::umask(mask) } {} + ScopedUmask(ScopedUmask const&) = delete; + ScopedUmask(ScopedUmask&&) = delete; + ScopedUmask& operator=(ScopedUmask const&) = delete; + ScopedUmask& operator=(ScopedUmask&&) = delete; + ~ScopedUmask() { ::umask(_previous); } + + private: + ::mode_t _previous; +}; + +/// @return The permission bits of @p path, as the host sees them. +[[nodiscard]] ::mode_t modeOf(std::filesystem::path const& path) +{ + struct ::stat status {}; + REQUIRE(::lstat(path.c_str(), &status) == 0); + return status.st_mode & 07777; +} + +/// Runs @p command (an argument vector, found on PATH) with its output discarded, and waits for it. +/// @return Whether it ran and exited 0. +[[nodiscard]] bool ranSuccessfully(std::vector const& command) +{ + auto arguments = std::vector {}; + for (auto const& argument: command) + arguments.push_back(const_cast(argument.c_str())); + arguments.push_back(nullptr); + auto actions = ::posix_spawn_file_actions_t {}; + ::posix_spawn_file_actions_init(&actions); + ::posix_spawn_file_actions_addopen(&actions, 1, "/dev/null", O_WRONLY, 0); + ::posix_spawn_file_actions_addopen(&actions, 2, "/dev/null", O_WRONLY, 0); + // An empty environment: the tools need none, and PATH is searched in this process's. + auto noEnvironment = std::array { nullptr }; + auto child = ::pid_t {}; + auto const spawned = + ::posix_spawnp(&child, arguments.front(), &actions, nullptr, arguments.data(), noEnvironment.data()); + ::posix_spawn_file_actions_destroy(&actions); + if (spawned != 0) + return false; + auto status = 0; + while (::waitpid(child, &status, 0) < 0) + if (errno != EINTR) + return false; + return WIFEXITED(status) && WEXITSTATUS(status) == 0; +} + +/// @return The access @p descriptor's own handle reports. +[[nodiscard]] std::optional accessOf(DescriptorFixture const& fixture, + core::fs::IDescriptor& descriptor) +{ + auto const status = fixture.run(descriptor.stat()); + REQUIRE(status.has_value()); + return status->access; +} + +} // namespace + +TEST_CASE("posix: an OwnerOnly file is created 0600 whatever the umask", "[fs][native][access]") +{ + // Even a umask that takes nothing away leaves the group and others without a bit. + auto const mask = ScopedUmask { 0 }; + auto fixture = DescriptorFixture::createNative(); + auto file = + fixture.run(fixture.root().openAt(SymlinkPolicy::NoFollow, + "secret", + OpenFlags::Create | OpenFlags::Exclusive | OpenFlags::OwnerOnly, + DescriptorFlags::Write)); + REQUIRE(file.has_value()); + CHECK(modeOf(fixture.hostDirectory() / "secret") == 0600); + CHECK(accessOf(fixture, **file) == AccessScope::OwnerOnly); +} + +TEST_CASE("posix: an OwnerOnly directory is created 0700 whatever the umask", "[fs][native][access]") +{ + auto const mask = ScopedUmask { 0 }; + auto fixture = DescriptorFixture::createNative(); + REQUIRE(fixture.run(fixture.root().createDirectoryAt("keys", CreationAccess::OwnerOnly)).has_value()); + CHECK(modeOf(fixture.hostDirectory() / "keys") == 0700); +} + +TEST_CASE("posix: a Default file under umask 022 is shared", "[fs][native][access]") +{ + auto const mask = ScopedUmask { 022 }; + auto fixture = DescriptorFixture::createNative(); + auto file = fixture.run(fixture.root().openAt( + SymlinkPolicy::NoFollow, "plain", OpenFlags::Create | OpenFlags::Exclusive, DescriptorFlags::Write)); + REQUIRE(file.has_value()); + CHECK(modeOf(fixture.hostDirectory() / "plain") == 0644); + CHECK(accessOf(fixture, **file) == AccessScope::Shared); + REQUIRE(fixture.run(fixture.root().createDirectoryAt("dir", CreationAccess::Default)).has_value()); + CHECK(modeOf(fixture.hostDirectory() / "dir") == 0755); +} + +TEST_CASE("posix: a group- or world-writable owner-only file is Shared", "[fs][native][access]") +{ + auto fixture = DescriptorFixture::createNative(); + auto file = + fixture.run(fixture.root().openAt(SymlinkPolicy::NoFollow, + "widened", + OpenFlags::Create | OpenFlags::Exclusive | OpenFlags::OwnerOnly, + DescriptorFlags::Write)); + REQUIRE(file.has_value()); + for (auto const mode: { ::mode_t { 0620 }, ::mode_t { 0602 }, ::mode_t { 0640 } }) + { + INFO("mode " << mode); + REQUIRE(::chmod((fixture.hostDirectory() / "widened").c_str(), mode) == 0); + CHECK(accessOf(fixture, **file) == AccessScope::Shared); + } +} + +TEST_CASE("posix: access is read on the open handle, not the name", "[fs][native][access]") +{ + auto const mask = ScopedUmask { 022 }; + auto fixture = DescriptorFixture::createNative(); + auto& root = fixture.root(); + auto file = fixture.run(root.openAt(SymlinkPolicy::NoFollow, + "key", + OpenFlags::Create | OpenFlags::Exclusive | OpenFlags::OwnerOnly, + DescriptorFlags::Read)); + REQUIRE(file.has_value()); + fixture.createFile("planted", "attacker"); + REQUIRE(modeOf(fixture.hostDirectory() / "planted") == 0644); + std::filesystem::rename(fixture.hostDirectory() / "planted", fixture.hostDirectory() / "key"); + CHECK(accessOf(fixture, **file) == AccessScope::OwnerOnly); + auto const byName = fixture.run(root.statAt(SymlinkPolicy::NoFollow, "key")); + REQUIRE(byName.has_value()); + CHECK((!byName->access.has_value() || *byName->access == AccessScope::Shared)); +} + +TEST_CASE("posix: a foreign owner is ForeignOwner", "[fs][native][access]") +{ + auto fixture = DescriptorFixture::createNative(); + if (::geteuid() != 0) + { + // Without root nothing can be given away, but root owns `/` and lets everyone read it. + auto slash = fixture.run(fixture.fileSystem().openPreopen("/", DescriptorFlags::Read)); + REQUIRE(slash.has_value()); + struct ::stat status {}; + REQUIRE(::stat("/", &status) == 0); + if (status.st_uid == ::geteuid()) + SKIP("this process owns `/` (a user namespace mapped to it), so nothing here is another's"); + CHECK(accessOf(fixture, **slash) == AccessScope::ForeignOwner); + return; + } + auto file = + fixture.run(fixture.root().openAt(SymlinkPolicy::NoFollow, + "theirs", + OpenFlags::Create | OpenFlags::Exclusive | OpenFlags::OwnerOnly, + DescriptorFlags::Read)); + REQUIRE(file.has_value()); + constexpr auto Nobody = ::uid_t { 65534 }; + REQUIRE(::lchown((fixture.hostDirectory() / "theirs").c_str(), Nobody, static_cast<::gid_t>(-1)) == 0); + CHECK(accessOf(fixture, **file) == AccessScope::ForeignOwner); +} + +TEST_CASE("posix: an inherited ACL never widens an OwnerOnly creation", "[fs][native][access]") +{ + auto const mask = ScopedUmask { 022 }; + auto fixture = DescriptorFixture::createNative(); + auto& root = fixture.root(); + REQUIRE(fixture.run(root.createDirectoryAt("inherits", CreationAccess::Default)).has_value()); + auto const command = core::fs::test::inheritableAclCommand(fixture.hostDirectory() / "inherits"); + INFO(command.front() << " " << command[command.size() - 2]); + if (!ranSuccessfully(command)) + SKIP("no inheritable ACL here: the tool is missing, or the file system keeps no such ACL"); + // The ACL bites: what is created inside by default is reachable by others. + auto plain = fixture.run(root.openAt(SymlinkPolicy::NoFollow, + "inherits/plain", + OpenFlags::Create | OpenFlags::Exclusive, + DescriptorFlags::Write)); + REQUIRE(plain.has_value()); + if (accessOf(fixture, **plain) != AccessScope::Shared) + SKIP("the ACL did not reach a new file, so nothing here could widen one"); + + auto secret = fixture.run(root.openAt(SymlinkPolicy::NoFollow, + "inherits/secret", + OpenFlags::Create | OpenFlags::Exclusive | OpenFlags::OwnerOnly, + DescriptorFlags::Write)); + REQUIRE(secret.has_value()); + CHECK(accessOf(fixture, **secret) == AccessScope::OwnerOnly); + CHECK(modeOf(fixture.hostDirectory() / "inherits" / "secret") == 0600); + REQUIRE(fixture.run(root.createDirectoryAt("inherits/keys", CreationAccess::OwnerOnly)).has_value()); + auto keys = fixture.run( + root.openAt(SymlinkPolicy::NoFollow, "inherits/keys", OpenFlags::Directory, DescriptorFlags::Read)); + REQUIRE(keys.has_value()); + CHECK(accessOf(fixture, **keys) == AccessScope::OwnerOnly); + CHECK(modeOf(fixture.hostDirectory() / "inherits" / "keys") == 0700); +} + +namespace +{ + +using core::fs::detail::OwnerOnlyCreation; +using core::fs::detail::OwnerOnlyCreator; +using core::fs::test::FixedRandom; + +/// The seed the creators of these cases draw their staging key from. +constexpr auto StagingSeed = std::uint64_t { 18 }; + +/// @return A creator as @p how says, its staging key drawn from @p seed. +[[nodiscard]] OwnerOnlyCreator creatorOf( + OwnerOnlyCreation how, + std::uint64_t seed = StagingSeed, + core::fs::detail::StatHandle statHandle = &core::fs::detail::systemStatHandle) +{ + auto random = FixedRandom { seed }; + return OwnerOnlyCreator { random, how, std::move(statHandle) }; +} + +/// A stat of a file system that ignores the mode it was given, as vfat or exfat under `fmask` and +/// cifs under `noperm` do: everything reads 0755 (0644 for a file is as wide). +int modeIgnoringStat(int handle, struct ::stat* status) +{ + if (::fstat(handle, status) != 0) + return -1; + status->st_mode = (status->st_mode & ~::mode_t { 07777 }) | 0755; + return 0; +} + +/// A host directory and a handle on it, as a descriptor holds one. +struct HeldDirectory +{ + core::testing::ScopedTempDir directory { "core-cpp-fs-owner-only" }; + core::fs::detail::UniqueHandle handle { ::open(directory.path().c_str(), + O_RDONLY | O_DIRECTORY | O_CLOEXEC) }; + + /// @return The names in it, sorted. + [[nodiscard]] std::vector names() const + { + auto listed = std::vector {}; + for (auto const& entry: std::filesystem::directory_iterator { directory.path() }) + listed.push_back(entry.path().filename().string()); + std::ranges::sort(listed); + return listed; + } +}; + +constexpr auto CreateFlags = O_CREAT | O_EXCL | O_RDWR | O_NOFOLLOW | O_CLOEXEC; + +[[nodiscard]] AccessScope scopeOf(int handle) +{ + struct ::stat status {}; + REQUIRE(::fstat(handle, &status) == 0); + auto const facts = core::fs::detail::accessFactsOf(handle, status); + REQUIRE(facts.has_value()); + return core::fs::classifyAccess(*facts); +} + +} // namespace + +TEST_CASE("posix: an owner-only creation, direct or staged, leaves the object and nothing else", + "[fs][native][access]") +{ + auto const how = GENERATE(OwnerOnlyCreation::Direct, OwnerOnlyCreation::Staged); + auto const mask = ScopedUmask { 0 }; + auto const held = HeldDirectory {}; + auto const creator = creatorOf(how); + auto file = creator.createFile(held.handle.get(), "secret", CreateFlags); + REQUIRE(file.has_value()); + REQUIRE(creator.createDirectory(held.handle.get(), "keys").has_value()); + CHECK(held.names() == std::vector { "keys", "secret" }); + CHECK(modeOf(held.directory.path() / "secret") == 0600); + CHECK(modeOf(held.directory.path() / "keys") == 0700); + CHECK(scopeOf(file->get()) == AccessScope::OwnerOnly); + // The handle is the file under its final name, its only link. + struct ::stat byHandle {}; + struct ::stat byName {}; + REQUIRE(::fstat(file->get(), &byHandle) == 0); + REQUIRE(::lstat((held.directory.path() / "secret").c_str(), &byName) == 0); + CHECK(byHandle.st_ino == byName.st_ino); + CHECK(byHandle.st_nlink == 1); +} + +TEST_CASE("posix: an owner-only creation over an existing name is Exist and leaves nothing behind", + "[fs][native][access]") +{ + auto const how = GENERATE(OwnerOnlyCreation::Direct, OwnerOnlyCreation::Staged); + auto const held = HeldDirectory {}; + std::ofstream { held.directory.path() / "taken" } << "theirs"; + std::filesystem::create_directory(held.directory.path() / "takendir"); + auto const creator = creatorOf(how); + auto const file = creator.createFile(held.handle.get(), "taken", CreateFlags); + REQUIRE_FALSE(file.has_value()); + CHECK(file.error().code == FsErrorCode::Exist); + auto const directory = creator.createDirectory(held.handle.get(), "takendir"); + REQUIRE_FALSE(directory.has_value()); + CHECK(directory.error().code == FsErrorCode::Exist); + CHECK(held.names() == std::vector { "taken", "takendir" }); + auto content = std::string {}; + std::getline(std::ifstream { held.directory.path() / "taken" }, content); + CHECK(content == "theirs"); +} + +TEST_CASE("posix: a staging name already taken is passed over, never used", "[fs][native][access]") +{ + auto const held = HeldDirectory {}; + // A twin with the same key names what the creator will try first: only a holder of the key can. + auto const planted = creatorOf(OwnerOnlyCreation::Staged).nextStagingName(); + std::filesystem::create_directory(held.directory.path() / planted); + std::ofstream { held.directory.path() / planted / ".object" } << "decoy"; + auto const file = + creatorOf(OwnerOnlyCreation::Staged).createFile(held.handle.get(), "secret", CreateFlags); + REQUIRE(file.has_value()); + CHECK(held.names() == std::vector { planted, "secret" }); + CHECK(std::filesystem::file_size(held.directory.path() / planted / ".object") == 5); +} + +TEST_CASE("posix: staging names cannot be told in advance", "[fs][native][access]") +{ + // Every name a process id and an attempt number could spell is taken, as by a user who saw one. + auto const held = HeldDirectory {}; + for (auto const attempt: std::views::iota(0, 64)) + std::filesystem::create_directory( + held.directory.path() + / (".core-cpp-owner-only." + std::to_string(::getpid()) + "." + std::to_string(attempt))); + auto const creator = creatorOf(OwnerOnlyCreation::Staged); + CHECK(creator.createFile(held.handle.get(), "secret", CreateFlags).has_value()); + CHECK(creator.createDirectory(held.handle.get(), "keys").has_value()); + // Each creation draws a name of its own, and another key draws others. + auto const first = creatorOf(OwnerOnlyCreation::Staged); + auto const other = creatorOf(OwnerOnlyCreation::Staged, StagingSeed + 1); + auto const name = first.nextStagingName(); + CHECK(name != first.nextStagingName()); + CHECK(name != other.nextStagingName()); +} + +TEST_CASE("posix: a creation the file system will not hold owner-only leaves nothing behind", + "[fs][native][access]") +{ + // A mode-ignoring file system (vfat or exfat under fmask, cifs under noperm) reads the new + // object back wider than it was made: the creation is refused and what it made removed. + auto const how = GENERATE(OwnerOnlyCreation::Direct, OwnerOnlyCreation::Staged); + auto const held = HeldDirectory {}; + auto const creator = creatorOf(how, StagingSeed, &modeIgnoringStat); + auto const file = creator.createFile(held.handle.get(), "secret", CreateFlags); + REQUIRE_FALSE(file.has_value()); + CHECK(file.error().code == FsErrorCode::NotPermitted); + auto const directory = creator.createDirectory(held.handle.get(), "keys"); + REQUIRE_FALSE(directory.has_value()); + CHECK(directory.error().code == FsErrorCode::NotPermitted); + CHECK(held.names().empty()); +} + +TEST_CASE("posix: a placeholder the file system will not hold owner-only is removed", "[fs][native][access]") +{ + // A staged directory reads back its staging directory, itself, then the placeholder under the + // final name: only the third is wider than it was made. + auto const held = HeldDirectory {}; + auto reads = 0; + auto const creator = + creatorOf(OwnerOnlyCreation::Staged, StagingSeed, [&reads](int handle, struct ::stat* status) { + ++reads; + return reads == 3 ? modeIgnoringStat(handle, status) : ::fstat(handle, status); + }); + auto const directory = creator.createDirectory(held.handle.get(), "keys"); + REQUIRE_FALSE(directory.has_value()); + CHECK(directory.error().code == FsErrorCode::NotPermitted); + CHECK(reads == 3); + CHECK(held.names().empty()); +} + +TEST_CASE("posix: a staged creation under an inheritable ACL is owner-only", "[fs][native][access]") +{ + auto const held = HeldDirectory {}; + auto const command = core::fs::test::inheritableAclCommand(held.directory.path()); + if (!ranSuccessfully(command)) + SKIP("no inheritable ACL here: the tool is missing, or the file system keeps no such ACL"); + auto const creator = creatorOf(OwnerOnlyCreation::Staged); + auto const file = creator.createFile(held.handle.get(), "secret", CreateFlags); + REQUIRE(file.has_value()); + CHECK(scopeOf(file->get()) == AccessScope::OwnerOnly); + REQUIRE(creator.createDirectory(held.handle.get(), "keys").has_value()); + CHECK(modeOf(held.directory.path() / "keys") == 0700); + CHECK(held.names() == std::vector { "keys", "secret" }); +} diff --git a/src/core/fs/posix/PosixDescriptor.cpp b/src/core/fs/posix/PosixDescriptor.cpp index f8f89189..c7e2b1d1 100644 --- a/src/core/fs/posix/PosixDescriptor.cpp +++ b/src/core/fs/posix/PosixDescriptor.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -23,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -80,13 +82,32 @@ namespace /// some systems and two on others. constexpr auto WouldBlockErrnos = std::to_array({ EAGAIN, EWOULDBLOCK }); - /// The mode a new file or directory is created with, before the process's umask. - constexpr ::mode_t NewFileMode = 0666; - constexpr ::mode_t NewDirectoryMode = 0777; + /// The modes a new file and a new directory are created with, given to `openat` and `mkdirat` + /// themselves: the umask can only take bits away, so an owner-only object is never anyone + /// else's, not even between its creation and a `chmod`. + struct CreationModeRow + { + CreationAccess access; + ::mode_t file; + ::mode_t directory; + }; + + constexpr auto CreationModes = std::to_array({ + { .access = CreationAccess::Default, .file = 0666, .directory = 0777 }, + { .access = CreationAccess::OwnerOnly, .file = 0600, .directory = 0700 }, + }); + + /// @return The row of @p access; the owner-only one for a value no row names, which fails closed. + [[nodiscard]] constexpr CreationModeRow const& creationModesOf(CreationAccess access) noexcept + { + auto const row = std::ranges::find(CreationModes, access, &CreationModeRow::access); + return row != CreationModes.end() ? *row : CreationModes.back(); + } using detail::typeOfMode; - DescriptorStat statOf(struct ::stat const& status) noexcept + /// @param handle What @p status was read through, or @c platform::InvalidHandle for a stat by name. + DescriptorStat statOf(int handle, struct ::stat const& status) { auto const times = detail::timesOf(status); return DescriptorStat { .type = typeOfMode(status.st_mode), @@ -94,7 +115,8 @@ namespace .size = static_cast(status.st_size), .accessed = times.accessed, .modified = times.modified, - .statusChanged = times.statusChanged }; + .statusChanged = times.statusChanged, + .access = detail::accessFactsOf(handle, status).transform(classifyAccess) }; } MetadataHash hashOf(NativeContext const& context, struct ::stat const& status) noexcept @@ -227,11 +249,11 @@ namespace /// flag cleared once open. A regular file under a lease answers EWOULDBLOCK then; it is opened /// again, waiting for the lease, through @c detail::openAfterWouldBlock, which never opens /// anything but a regular file blocking. - FsResult openEntry(int directory, std::string const& name, int flags) + FsResult openEntry(int directory, std::string const& name, int flags, ::mode_t mode) { auto const* const path = name.empty() ? "." : name.c_str(); - auto const opened = detail::retryOnInterrupt( - [&] { return ::openat(directory, path, flags | O_NONBLOCK, NewFileMode); }); + auto const opened = + detail::retryOnInterrupt([&] { return ::openat(directory, path, flags | O_NONBLOCK, mode); }); if (opened >= 0) { auto handle = UniqueHandle { opened }; @@ -418,7 +440,7 @@ namespace return submit([handle = handle(), flags = flags()]() { return checkRights(flags, Operation::Stat) .and_then([&] { return statHandle(handle->get()); }) - .transform([](struct ::stat const& status) { return statOf(status); }); + .transform([&](struct ::stat const& status) { return statOf(handle->get(), status); }); }); } @@ -490,7 +512,12 @@ namespace } auto const directory = resolved->directory(); auto const& name = resolved->name; - auto child = openEntry(directory, name, *openFlags); + auto const creating = + hasFlag(open, OpenFlags::OwnerOnly) ? CreationAccess::OwnerOnly : CreationAccess::Default; + // OwnerOnly comes with Create | Exclusive (checkOpenRights): this call makes the file. + auto child = creating == CreationAccess::OwnerOnly + ? context->ownerOnlyCreator->createFile(directory, name, *openFlags) + : openEntry(directory, name, *openFlags, creationModesOf(creating).file); if (!child) return std::unexpected { child.error() }; auto const opened = child->get(); @@ -526,13 +553,14 @@ namespace }); } - async::Task> createDirectoryAt(std::string path) override + async::Task> createDirectoryAt(std::string path, CreationAccess access) override { return submit([context = context(), handle = handle(), flags = flags(), type = objectType(), - path = std::move(path)]() { + path = std::move(path), + access]() { return checkRights(flags, Operation::CreateDirectoryAt) .and_then([&] { return detail::requireDirectory(type); }) .and_then([&] { @@ -545,10 +573,14 @@ namespace .and_then([](Resolved resolved) { return vacant(std::move(resolved), DescriptorType::Directory); }) - .and_then([](Resolved const& resolved) { - return succeededOr( - ::mkdirat(resolved.directory(), resolved.name.c_str(), NewDirectoryMode), - "mkdirat"); + .and_then([&context, access](Resolved const& resolved) -> FsResult { + if (access == CreationAccess::OwnerOnly) + return context->ownerOnlyCreator->createDirectory(resolved.directory(), + resolved.name); + return succeededOr(::mkdirat(resolved.directory(), + resolved.name.c_str(), + creationModesOf(access).directory), + "mkdirat"); }); }); } @@ -567,9 +599,13 @@ namespace return resolve(handle->get(), path, *context, policy, TrailingSlashOnLink::Follow); }) .and_then([](Resolved const& resolved) { - return statEntry(resolved.directory(), resolved.name); - }) - .transform([](struct ::stat const& status) { return statOf(status); }); + // The directory itself is stat'ed through its handle; a name, by name. + auto const through = + resolved.name.empty() ? resolved.directory() : platform::InvalidHandle; + return statEntry(resolved.directory(), resolved.name) + .transform( + [through](struct ::stat const& status) { return statOf(through, status); }); + }); }); } @@ -897,7 +933,15 @@ FsResult> makeNativeDescriptorFileSystem( { return detail::checkOptions(options).transform([&] -> std::unique_ptr { return std::make_unique(std::make_shared( - home, blocking, wallClock, random, options, KernelSeparators, nullptr)); + home, + blocking, + wallClock, + random, + options, + KernelSeparators, + nullptr, + nullptr, + std::make_shared(random, detail::nativeOwnerOnlyCreation()))); }); } diff --git a/src/core/fs/posix/PosixSystem.hpp b/src/core/fs/posix/PosixSystem.hpp index 1631654b..cc59765c 100644 --- a/src/core/fs/posix/PosixSystem.hpp +++ b/src/core/fs/posix/PosixSystem.hpp @@ -6,6 +6,7 @@ /// chooses (`posix/PosixSystem.cpp` or `bsd/PosixSystem.cpp`; `linux/Append.cpp` or /// `posix/Append.cpp`), so the descriptor itself names no system. Private to the fs module. +#include #include #include #include @@ -18,9 +19,12 @@ #include #include #include +#include #include #include +#include + namespace core::fs::detail { @@ -130,4 +134,37 @@ struct StatTimes std::mutex& appendLock, std::span bytes); +/// @param status An `fstat`. +/// @return Its owner, against the effective uid, and its mode, with no ACL beyond it. +[[nodiscard]] inline AccessFacts modeFactsOf(struct ::stat const& status) +{ + return AccessFacts { .owner = status.st_uid == ::geteuid() ? AccessFacts::Owner::CurrentUser + : AccessFacts::Owner::Other, + .posixMode = static_cast(status.st_mode & 07777), + .acl = AccessFacts::AclState::Absent, + .entries = {} }; +} + +/// What the open object tells about who may reach it: its owner and mode, and where the system has +/// ACLs beyond the mode, its ACL read from the very handle (`posix/AccessFacts.cpp` on Linux, which +/// has none beyond the mode; `bsd/AccessFacts.cpp` on FreeBSD, NFSv4; `darwin/AccessFacts.cpp` on +/// macOS, extended). Never by name. +/// @param handle The open object, or @c platform::InvalidHandle where only @p status is at hand (a +/// `statAt`, made by name with `fstatat`). +/// @param status Its `fstat` (or `fstatat` without following). +/// @return The facts; nullopt where an ACL cannot be read, or no @p handle is given on a system +/// whose ACL needs one. +[[nodiscard]] CORE_FS_API std::optional accessFactsOf(int handle, struct ::stat const& status); + +/// Removes, on the handle of an object this process has just created owner-only, any ACL the +/// system let it inherit from its directory, which could grant others more than @p mode does: an +/// extended ACL on macOS (`darwin/AccessFacts.cpp`: set empty), a non-trivial NFSv4 ACL on FreeBSD +/// (`bsd/AccessFacts.cpp`: stripped to the trivial one, then the mode set again). Nothing on Linux +/// (`posix/AccessFacts.cpp`): a default ACL's entries are capped by the mask, which the mode given +/// to `openat`/`mkdirat` bounds. The caller reads the access back afterwards. +/// @param handle The new object. +/// @param mode The mode it was created with. +/// @return Nothing, or what refused the change. +[[nodiscard]] CORE_FS_API FsResult stripInheritedAcl(int handle, ::mode_t mode); + } // namespace core::fs::detail diff --git a/src/core/fs/testing/InMemoryDescriptorFileSystem.cpp b/src/core/fs/testing/InMemoryDescriptorFileSystem.cpp index 577ebe20..5b317b34 100644 --- a/src/core/fs/testing/InMemoryDescriptorFileSystem.cpp +++ b/src/core/fs/testing/InMemoryDescriptorFileSystem.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -78,6 +79,7 @@ struct InMemoryState FileTime modified; FileTime statusChanged; DescriptorType type = DescriptorType::Unknown; + AccessFacts access; ///< Who may reach it, as a native reader would have found it. }; /// Where a path resolved to: the directories walked from the descriptor down to the one holding @@ -198,7 +200,19 @@ struct InMemoryState ++node.changes; } - [[nodiscard]] std::uint64_t createNode(DescriptorType type) + /// The mode a new node gets: a umask of 022 for @c CreationAccess::Default, as most systems have. + [[nodiscard]] static std::uint32_t modeOf(DescriptorType type, CreationAccess access) noexcept + { + if (type == DescriptorType::SymbolicLink) + return 0777; + auto const searchable = type == DescriptorType::Directory; + if (access == CreationAccess::OwnerOnly) + return searchable ? 0700 : 0600; + return searchable ? 0755 : 0644; + } + + [[nodiscard]] std::uint64_t createNode(DescriptorType type, + CreationAccess access = CreationAccess::Default) { auto const inode = nextInode++; auto const when = now(); @@ -211,7 +225,11 @@ struct InMemoryState .accessed = when, .modified = when, .statusChanged = when, - .type = type }); + .type = type, + .access = AccessFacts { .owner = AccessFacts::Owner::CurrentUser, + .posixMode = modeOf(type, access), + .acl = AccessFacts::AclState::Absent, + .entries = {} } }); return inode; } @@ -350,7 +368,8 @@ struct InMemoryState .size = size, .accessed = node.accessed, .modified = node.modified, - .statusChanged = node.statusChanged }; + .statusChanged = node.statusChanged, + .access = classifyAccess(node.access) }; } void applyTimes(std::uint64_t inode, NewTimestamp const& accessed, NewTimestamp const& modified) @@ -662,16 +681,18 @@ namespace }); } - async::Task> createDirectoryAt(std::string path) override + async::Task> createDirectoryAt(std::string path, CreationAccess access) override { - return submit([inode = _inode, flags = _flags, path = std::move(path)](InMemoryState& state) { - return checkRights(flags, Operation::CreateDirectoryAt) - .and_then([&] { return state.vacant(inode, path, DescriptorType::Directory); }) - .transform([&](Location const& location) { - state.insert( - location.parent(), location.name, state.createNode(DescriptorType::Directory)); - }); - }); + return submit( + [inode = _inode, flags = _flags, path = std::move(path), access](InMemoryState& state) { + return checkRights(flags, Operation::CreateDirectoryAt) + .and_then([&] { return state.vacant(inode, path, DescriptorType::Directory); }) + .transform([&](Location const& location) { + state.insert(location.parent(), + location.name, + state.createNode(DescriptorType::Directory, access)); + }); + }); } async::Task> statAt(SymlinkPolicy policy, std::string path) override @@ -899,7 +920,10 @@ namespace return refuse(FsErrorCode::NoEntry); if (location.finalComponent == fs::detail::FinalComponent::Directory) return refuse(FsErrorCode::NotDirectory); - auto const file = state.createNode(DescriptorType::RegularFile); + auto const file = + state.createNode(DescriptorType::RegularFile, + hasFlag(open, OpenFlags::OwnerOnly) ? CreationAccess::OwnerOnly + : CreationAccess::Default); state.insert(location.parent(), location.name, file); return file; } @@ -988,6 +1012,24 @@ void InMemoryDescriptorFileSystem::addFile(std::string_view path, std::string_vi std::ranges::transform(content, node.data.begin(), [](char c) { return static_cast(c); }); } +void InMemoryDescriptorFileSystem::setAccessFacts(std::string_view path, AccessFacts facts) +{ + auto const lock = std::scoped_lock { _state->mutex }; + auto node = RootInode; + for (auto const piece: path | std::views::split('/')) + { + auto const name = std::string_view { piece }; + if (name.empty() || name == ".") + continue; + auto const found = _state->lookup(node, name); + if (!found) + throw std::invalid_argument { "InMemoryDescriptorFileSystem::setAccessFacts: no '" + + std::string { path } + "'" }; + node = *found; + } + _state->nodes.at(node).access = std::move(facts); +} + void InMemoryDescriptorFileSystem::addSymlink(std::string_view path, std::string target) { auto const lock = std::scoped_lock { _state->mutex }; diff --git a/src/core/fs/testing/InMemoryDescriptorFileSystem.hpp b/src/core/fs/testing/InMemoryDescriptorFileSystem.hpp index 20bef02d..1dcdedff 100644 --- a/src/core/fs/testing/InMemoryDescriptorFileSystem.hpp +++ b/src/core/fs/testing/InMemoryDescriptorFileSystem.hpp @@ -6,6 +6,7 @@ #include #include +#include #include #include #include @@ -80,6 +81,15 @@ class CORE_FS_API InMemoryDescriptorFileSystem final: public IDescriptorFileSyst /// @throws std::invalid_argument Where something is in the way. void addSymlink(std::string_view path, std::string target); + /// Replaces what a native reader would have found on the handle of @p path, so a case can model + /// any OS's owner and ACL: a stat of it reports @c classifyAccess of @p facts. A new node has the + /// current user as owner, no ACL, and mode 0644 or 0755 (0600 or 0700 where it was created + /// owner-only); a link 0777. + /// @param path Relative to the root, `/`-separated; links on the way are not followed. + /// @param facts What its handle would tell. + /// @throws std::invalid_argument Where nothing has that path. + void setAccessFacts(std::string_view path, AccessFacts facts); + /// Opens the directory @p hostDirectory of the model: `/`, `.` and the empty path are its root. /// @param hostDirectory A `/`-separated path from the root. /// @param flags The rights the root carries; `Write` is `IsDirectory`. diff --git a/src/core/fs/windows/AccessFacts.cpp b/src/core/fs/windows/AccessFacts.cpp new file mode 100644 index 00000000..372c616f --- /dev/null +++ b/src/core/fs/windows/AccessFacts.cpp @@ -0,0 +1,133 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// Who may reach an object on Windows: the owner and DACL of the very handle, read with +// GetSecurityInfo on a handle opened with READ_CONTROL, judged against the process token's user. +#include + +#include + +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace core::fs::detail +{ + +namespace +{ + + using Kind = AccessEntry::Kind; + using Principal = AccessEntry::Principal; + + struct LocalFreeDeleter + { + void operator()(void* memory) const noexcept { ::LocalFree(memory); } + }; + + /// The entry types whose rights are judged; every other type is `Unknown`. + struct EntryTypeRow + { + BYTE type; + Kind kind; + }; + + constexpr auto EntryTypes = std::to_array({ + { .type = ACCESS_ALLOWED_ACE_TYPE, .kind = Kind::Allow }, + { .type = ACCESS_DENIED_ACE_TYPE, .kind = Kind::Deny }, + }); + + /// The well-known principals that can reach every object anyway. + struct WellKnownRow + { + WELL_KNOWN_SID_TYPE sid; + Principal principal; + }; + + constexpr auto WellKnownPrincipals = std::to_array({ + { .sid = WinLocalSystemSid, .principal = Principal::System }, + { .sid = WinBuiltinAdministratorsSid, .principal = Principal::Administrators }, + }); + + [[nodiscard]] Principal principalOf(PSID sid, PSID user) noexcept + { + if (::EqualSid(sid, user) != FALSE) + return Principal::Owner; + auto const found = std::ranges::find_if(WellKnownPrincipals, [sid](WellKnownRow const& row) { + return ::IsWellKnownSid(sid, row.sid) != FALSE; + }); + return found != WellKnownPrincipals.end() ? found->principal : Principal::Other; + } + + /// @return What @p header's entry is; its SID and mask are read only for the two judged types, + /// which share ACCESS_ALLOWED_ACE's layout. + [[nodiscard]] AccessEntry entryOf(ACE_HEADER const* header, PSID user) noexcept + { + auto const origin = (header->AceFlags & INHERITED_ACE) != 0 ? AccessEntry::Origin::Inherited + : AccessEntry::Origin::Explicit; + auto const type = std::ranges::find(EntryTypes, header->AceType, &EntryTypeRow::type); + if (type == EntryTypes.end()) + return AccessEntry { .kind = Kind::Unknown, + .principal = Principal::Other, + .rights = AccessEntry::Rights::ReadOrWrite, + .origin = origin }; + auto const* const entry = reinterpret_cast(header); + auto* const sid = const_cast(&entry->SidStart); + return AccessEntry { .kind = type->kind, + .principal = principalOf(sid, user), + .rights = entry->Mask != 0 ? AccessEntry::Rights::ReadOrWrite + : AccessEntry::Rights::None, + .origin = origin }; + } + +} // namespace + +std::optional accessFactsOf(HANDLE handle, PSID user) +{ + auto owner = PSID {}; + auto dacl = PACL {}; + auto descriptor = PSECURITY_DESCRIPTOR {}; + if (::GetSecurityInfo(handle, + SE_FILE_OBJECT, + OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, + &owner, + nullptr, + &dacl, + nullptr, + &descriptor) + != ERROR_SUCCESS) + return std::nullopt; + auto const release = std::unique_ptr { descriptor }; + auto facts = AccessFacts { .owner = owner != nullptr && ::EqualSid(owner, user) != FALSE + ? AccessFacts::Owner::CurrentUser + : AccessFacts::Owner::Other, + .posixMode = 0, + .acl = AccessFacts::AclState::Null, + .entries = {} }; + if (dacl == nullptr) + return facts; + auto information = ACL_SIZE_INFORMATION {}; + if (::GetAclInformation(dacl, &information, sizeof(information), AclSizeInformation) == FALSE) + return std::nullopt; + facts.acl = AccessFacts::AclState::Present; + facts.entries.reserve(information.AceCount); + for (auto const index: std::views::iota(DWORD { 0 }, information.AceCount)) + { + auto* entry = LPVOID {}; + if (::GetAce(dacl, index, &entry) == FALSE) + return std::nullopt; + auto const* const header = static_cast(entry); + // An inherit-only entry grants nothing on this object, only on what is created inside it. + if ((header->AceFlags & INHERIT_ONLY_ACE) != 0) + continue; + facts.entries.push_back(entryOf(header, user)); + } + return facts; +} + +} // namespace core::fs::detail diff --git a/src/core/fs/windows/AccessFacts.hpp b/src/core/fs/windows/AccessFacts.hpp new file mode 100644 index 00000000..ad7485b8 --- /dev/null +++ b/src/core/fs/windows/AccessFacts.hpp @@ -0,0 +1,34 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// The Windows reader of who may reach an object: the owner and DACL of an open handle, as +/// @c AccessFacts. Private to the fs module. + +#include +#include + +#include + +// As NtFile.hpp includes it: defines every STATUS_ code, which defines some +// of again unless told not to, so a source that includes this header before NtFile.hpp would see +// them defined twice (MSVC's C4005). +#define WIN32_NO_STATUS +#include +#undef WIN32_NO_STATUS +#include + +namespace core::fs::detail +{ + +/// Reads the owner and the DACL of @p handle (`GetSecurityInfo`), every entry of it, inherited ones +/// included. An ALLOW or DENY entry is judged by the principal it names: @p user, LocalSystem, +/// BUILTIN\Administrators, or anyone else; any other entry type is `Unknown`. An inherit-only entry +/// (`INHERIT_ONLY_ACE`) is skipped: it grants nothing on this object, only on what is created +/// inside it, which carries the entry, and is judged, itself. +/// @param handle An open object, with `READ_CONTROL`. +/// @param user The process token's user. +/// @return The facts; nullopt where the handle's security cannot be read. +[[nodiscard]] CORE_FS_API std::optional accessFactsOf(HANDLE handle, PSID user); + +} // namespace core::fs::detail diff --git a/src/core/fs/windows/DescriptorEscape_test.cpp b/src/core/fs/windows/DescriptorEscape_test.cpp index 3a259b63..8aa74730 100644 --- a/src/core/fs/windows/DescriptorEscape_test.cpp +++ b/src/core/fs/windows/DescriptorEscape_test.cpp @@ -142,7 +142,7 @@ TEST_CASE("windows: a junction or a mount point beneath the preopen is never tra { auto fixture = DescriptorFixture::createNative(); auto& root = fixture.root(); - REQUIRE(fixture.run(root.createDirectoryAt("inside")).has_value()); + REQUIRE(fixture.run(root.createDirectoryAt("inside", core::fs::CreationAccess::Default)).has_value()); fixture.createFile("inside/decoy", "inside"); fixture.writeOutsideFile("decoy", "outside"); @@ -178,7 +178,8 @@ TEST_CASE("windows: a junction or a mount point beneath the preopen is never tra CHECK(outcomeOf(fixture.run(root.metadataHashAt(policy, name + "/."))) == notPermitted); } CHECK(outcomeOf(fixture.run(root.statAt(SymlinkPolicy::Follow, name))) == notPermitted); - CHECK(outcomeOf(fixture.run(root.createDirectoryAt(name + "/new"))) == notPermitted); + CHECK(outcomeOf(fixture.run(root.createDirectoryAt(name + "/new", core::fs::CreationAccess::Default))) + == notPermitted); CHECK(outcomeOf(fixture.run(root.unlinkFileAt(name + "/decoy"))) == notPermitted); CHECK(outcomeOf(fixture.run(root.readlinkAt(name))) == notPermitted); // Unfollowed, it is a link like any other, inside the root. diff --git a/src/core/fs/windows/DescriptorTestSupport.cpp b/src/core/fs/windows/DescriptorTestSupport.cpp new file mode 100644 index 00000000..84a4a724 --- /dev/null +++ b/src/core/fs/windows/DescriptorTestSupport.cpp @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The Windows half of DescriptorTestSupport.hpp's platform questions. Wine's ntdll exports +// `wine_get_version`, and no Windows ntdll does: that export is wine's own documented way for a +// program to tell, and the one a case uses before it accepts a behaviour only wine has. +#include + +#include + +namespace core::fs::test +{ + +bool runsUnderWine() noexcept +{ + auto* const ntdll = GetModuleHandleW(L"ntdll.dll"); + return ntdll != nullptr && GetProcAddress(ntdll, "wine_get_version") != nullptr; +} + +} // namespace core::fs::test diff --git a/src/core/fs/windows/NtFile.hpp b/src/core/fs/windows/NtFile.hpp index 6a54293a..0b82d48b 100644 --- a/src/core/fs/windows/NtFile.hpp +++ b/src/core/fs/windows/NtFile.hpp @@ -72,6 +72,10 @@ struct NtOpenRequest ULONG disposition = 0; ///< `FILE_OPEN`, `FILE_CREATE`, ... ULONG options = 0; ///< `FILE_DIRECTORY_FILE`, ...; synchronous I/O is always added. ReparseHandling reparse = ReparseHandling::OpenThePoint; ///< What a reparse point it names is. + /// What an object this open creates is given as its owner and DACL, by `NtCreateFile` itself + /// (`OBJECT_ATTRIBUTES::SecurityDescriptor`), so it is never anyone else's for a moment; null for + /// what the system gives (the inherited DACL). An object that already exists keeps its own. + PSECURITY_DESCRIPTOR security = nullptr; }; /// How every open identifies this process to a server it reaches (a named pipe, a share): never @@ -116,7 +120,7 @@ inline constexpr auto IdentificationOnly = SECURITY_QUALITY_OF_SERVICE { .RootDirectory = directory, .ObjectName = &unicodeName, .Attributes = OBJ_CASE_INSENSITIVE | attributeFlags, - .SecurityDescriptor = nullptr, + .SecurityDescriptor = request.security, .SecurityQualityOfService = &qualityOfService }; auto status = IO_STATUS_BLOCK {}; auto handle = HANDLE {}; diff --git a/src/core/fs/windows/OwnerOnly_test.cpp b/src/core/fs/windows/OwnerOnly_test.cpp new file mode 100644 index 00000000..32616bf4 --- /dev/null +++ b/src/core/fs/windows/OwnerOnly_test.cpp @@ -0,0 +1,426 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// What the Windows descriptors owe an owner-only creation: the security descriptor is handed to +// NtCreateFile itself, its owner the process token's user and its DACL protected, with one entry for +// that user, so nothing is inherited and no other account ever holds the object. And what they read +// back: the owner and the DACL of the handle, which every stat open now asks READ_CONTROL for. +// +// Wine is not Windows: it keeps a security descriptor, but its process is neither elevated nor an +// account whose new objects Administrators own, so the elevated case needs native Windows CI. +#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 + +using core::fs::AccessScope; +using core::fs::CreationAccess; +using core::fs::DescriptorFlags; +using core::fs::OpenFlags; +using core::fs::SymlinkPolicy; +using core::fs::test::DescriptorFixture; + +namespace +{ + +/// Frees what a security call allocated with LocalAlloc. +struct LocalFreeDeleter +{ + void operator()(void* memory) const noexcept { ::LocalFree(memory); } +}; + +/// Closes a handle. +struct HandleCloser +{ + void operator()(void* handle) const noexcept { ::CloseHandle(handle); } +}; + +using UniqueLocal = std::unique_ptr; +using UniqueWinHandle = std::unique_ptr; + +/// @return The process token, for reading. +[[nodiscard]] UniqueWinHandle processToken() +{ + auto token = HANDLE {}; + REQUIRE(::OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY, &token) != FALSE); + return UniqueWinHandle { token }; +} + +/// @return The process token's user SID, as bytes. +[[nodiscard]] std::vector tokenUser() +{ + auto const token = processToken(); + auto size = DWORD { 0 }; + ::GetTokenInformation(token.get(), TokenUser, nullptr, 0, &size); + auto buffer = std::vector(size); + REQUIRE(::GetTokenInformation(token.get(), TokenUser, buffer.data(), size, &size) != FALSE); + auto const* const user = reinterpret_cast(buffer.data()); + auto sid = std::vector(::GetLengthSid(user->User.Sid)); + REQUIRE(::CopySid(static_cast(sid.size()), sid.data(), user->User.Sid) != FALSE); + return sid; +} + +/// @return Whether the process token is elevated. +[[nodiscard]] bool elevated() +{ + auto const token = processToken(); + auto elevation = TOKEN_ELEVATION {}; + auto size = DWORD { sizeof(elevation) }; + return ::GetTokenInformation(token.get(), TokenElevation, &elevation, size, &size) != FALSE + && elevation.TokenIsElevated != 0; +} + +/// Opens @p path through the host with @p access, as another program would. +[[nodiscard]] UniqueWinHandle hostOpen(std::filesystem::path const& path, DWORD access) +{ + auto const handle = ::CreateFileW(path.c_str(), + access, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + nullptr, + OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS, + nullptr); + REQUIRE(handle != INVALID_HANDLE_VALUE); + return UniqueWinHandle { handle }; +} + +/// The owner and DACL of an object, as the host reads them. +struct Security +{ + UniqueLocal descriptor; + PSID owner = nullptr; + PACL dacl = nullptr; +}; + +[[nodiscard]] Security securityOf(std::filesystem::path const& path) +{ + auto const handle = hostOpen(path, READ_CONTROL); + auto security = Security {}; + auto* descriptor = PSECURITY_DESCRIPTOR {}; + REQUIRE(::GetSecurityInfo(handle.get(), + SE_FILE_OBJECT, + OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, + &security.owner, + nullptr, + &security.dacl, + nullptr, + &descriptor) + == ERROR_SUCCESS); + security.descriptor.reset(descriptor); + return security; +} + +/// Adds an entry granting Everyone read and write to the DACL of @p path, through the host. +void grantEveryone(std::filesystem::path const& path, DWORD inheritance = NO_INHERITANCE) +{ + auto const current = securityOf(path); + auto everyone = EXPLICIT_ACCESS_W {}; + everyone.grfAccessPermissions = GENERIC_READ | GENERIC_WRITE; + everyone.grfAccessMode = GRANT_ACCESS; + everyone.grfInheritance = inheritance; + everyone.Trustee.TrusteeForm = TRUSTEE_IS_NAME; + everyone.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP; + everyone.Trustee.ptstrName = const_cast(L"EVERYONE"); + auto* widened = PACL {}; + REQUIRE(::SetEntriesInAclW(1, &everyone, current.dacl, &widened) == ERROR_SUCCESS); + auto const owned = UniqueLocal { widened }; + auto const handle = hostOpen(path, READ_CONTROL | WRITE_DAC); + REQUIRE(::SetSecurityInfo( + handle.get(), SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, nullptr, nullptr, widened, nullptr) + == ERROR_SUCCESS); +} + +/// Skips a case that needs elevation, or fails it where `CORE_TEST_REQUIRE_ELEVATED=1` says the +/// runner is elevated (Windows CI), so a lost privilege fails rather than skips there. +void requireElevationOrSkip(char const* why) +{ + if (core::LiveEnvironment {}.get("CORE_TEST_REQUIRE_ELEVATED") == "1") + FAIL("CORE_TEST_REQUIRE_ELEVATED=1, but " << why); + SKIP(why); +} + +/// @return The access @p descriptor's own handle reports. +[[nodiscard]] std::optional accessOf(DescriptorFixture const& fixture, + core::fs::IDescriptor& descriptor) +{ + auto const status = fixture.run(descriptor.stat()); + REQUIRE(status.has_value()); + return status->access; +} + +[[nodiscard]] std::unique_ptr createOwnerOnly(DescriptorFixture const& fixture, + std::string name) +{ + auto file = + fixture.run(fixture.root().openAt(SymlinkPolicy::NoFollow, + std::move(name), + OpenFlags::Create | OpenFlags::Exclusive | OpenFlags::OwnerOnly, + DescriptorFlags::Read | DescriptorFlags::Write)); + REQUIRE(file.has_value()); + return std::move(*file); +} + +} // namespace + +TEST_CASE("windows: stat opens can read the security descriptor", "[fs][native][access]") +{ + auto fixture = DescriptorFixture::createNative(); + auto& root = fixture.root(); + fixture.createFile("plain", "x"); + REQUIRE(fixture.run(root.createDirectoryAt("dir", CreationAccess::Default)).has_value()); + for (auto const* const name: { "plain", "dir" }) + { + INFO(name); + auto const byName = fixture.run(root.statAt(SymlinkPolicy::NoFollow, name)); + REQUIRE(byName.has_value()); + CHECK(byName->access.has_value()); + // A descriptor with no right at all still holds READ_CONTROL for its own stat. + auto bare = + fixture.run(root.openAt(SymlinkPolicy::NoFollow, name, OpenFlags::None, DescriptorFlags::None)); + REQUIRE(bare.has_value()); + CHECK(accessOf(fixture, **bare).has_value()); + } + CHECK(accessOf(fixture, root).has_value()); +} + +TEST_CASE("windows: an OwnerOnly file is owned by the user, with a protected DACL for the user alone", + "[fs][native][access]") +{ + auto fixture = DescriptorFixture::createNative(); + auto const file = createOwnerOnly(fixture, "secret"); + REQUIRE(fixture.run(fixture.root().createDirectoryAt("keys", CreationAccess::OwnerOnly)).has_value()); + auto user = tokenUser(); + for (auto const* const name: { "secret", "keys" }) + { + INFO(name); + auto const security = securityOf(fixture.hostDirectory() / name); + REQUIRE(security.owner != nullptr); + CHECK(::EqualSid(security.owner, user.data()) != FALSE); + REQUIRE(security.dacl != nullptr); + auto control = SECURITY_DESCRIPTOR_CONTROL {}; + auto revision = DWORD {}; + REQUIRE(::GetSecurityDescriptorControl(security.descriptor.get(), &control, &revision) != FALSE); + CHECK((control & SE_DACL_PROTECTED) != 0); + auto information = ACL_SIZE_INFORMATION {}; + REQUIRE(::GetAclInformation(security.dacl, &information, sizeof(information), AclSizeInformation) + != FALSE); + REQUIRE(information.AceCount == 1); + auto* entry = LPVOID {}; + REQUIRE(::GetAce(security.dacl, 0, &entry) != FALSE); + auto const* const allowed = static_cast(entry); + CHECK(allowed->Header.AceType == ACCESS_ALLOWED_ACE_TYPE); + CHECK(::EqualSid(const_cast(&allowed->SidStart), user.data()) != FALSE); + } + CHECK(accessOf(fixture, *file) == AccessScope::OwnerOnly); +} + +TEST_CASE("windows: an Everyone entry is Shared, read on the handle, not the name", "[fs][native][access]") +{ + auto fixture = DescriptorFixture::createNative(); + auto& root = fixture.root(); + auto const key = createOwnerOnly(fixture, "key"); + auto const planted = createOwnerOnly(fixture, "planted"); + grantEveryone(fixture.hostDirectory() / "planted"); + CHECK(accessOf(fixture, *planted) == AccessScope::Shared); + auto const renamed = fixture.run(root.renameAt("planted", &root, "key")); + if (!renamed && core::fs::test::runsUnderWine()) + SKIP("wine refuses to replace a file that is open (" + << renamed.error().toString() << "); native Windows replaces it with POSIX semantics"); + REQUIRE(renamed.has_value()); + CHECK(accessOf(fixture, *key) == AccessScope::OwnerOnly); + CHECK(fixture.run(root.statAt(SymlinkPolicy::NoFollow, "key"))->access == AccessScope::Shared); +} + +TEST_CASE("windows: an OwnerOnly file created elevated is owned by the token user", "[fs][native][access]") +{ + // An elevated administrator's new objects are owned by BUILTIN\Administrators by default; the + // explicit owner keeps the file the user's, so it stays usable unelevated. + if (core::fs::test::runsUnderWine()) + SKIP("wine runs no elevated process: needs native Windows (the CI runner)"); + if (!elevated()) + requireElevationOrSkip("the process is not elevated"); + auto fixture = DescriptorFixture::createNative(); + auto const file = createOwnerOnly(fixture, "elevated"); + auto user = tokenUser(); + auto const security = securityOf(fixture.hostDirectory() / "elevated"); + REQUIRE(security.owner != nullptr); + CHECK(::EqualSid(security.owner, user.data()) != FALSE); + CHECK(accessOf(fixture, *file) == AccessScope::OwnerOnly); +} + +TEST_CASE("windows: a foreign owner is ForeignOwner", "[fs][native][access]") +{ + auto fixture = DescriptorFixture::createNative(); + createOwnerOnly(fixture, "theirs").reset(); + auto administrators = std::vector(SECURITY_MAX_SID_SIZE); + auto size = static_cast(administrators.size()); + REQUIRE(::CreateWellKnownSid(WinBuiltinAdministratorsSid, nullptr, administrators.data(), &size) + != FALSE); + { + auto const handle = hostOpen(fixture.hostDirectory() / "theirs", READ_CONTROL | WRITE_OWNER); + if (::SetSecurityInfo(handle.get(), + SE_FILE_OBJECT, + OWNER_SECURITY_INFORMATION, + administrators.data(), + nullptr, + nullptr, + nullptr) + != ERROR_SUCCESS) + requireElevationOrSkip( + "this account may not give a file to BUILTIN\\Administrators (needs elevation)"); + } + // Opened after the change: wine keeps a security descriptor per open file object, so a handle + // open before it would still report the old owner there (NTFS keeps one per file). + auto file = fixture.run( + fixture.root().openAt(SymlinkPolicy::NoFollow, "theirs", OpenFlags::None, DescriptorFlags::Read)); + REQUIRE(file.has_value()); + CHECK(accessOf(fixture, **file) == AccessScope::ForeignOwner); + CHECK(fixture.run(fixture.root().statAt(SymlinkPolicy::NoFollow, "theirs"))->access + == AccessScope::ForeignOwner); +} + +TEST_CASE("windows: a NULL DACL is Shared", "[fs][native][access]") +{ + auto fixture = DescriptorFixture::createNative(); + createOwnerOnly(fixture, "open").reset(); + { + auto const handle = hostOpen(fixture.hostDirectory() / "open", READ_CONTROL | WRITE_DAC); + REQUIRE( + ::SetSecurityInfo( + handle.get(), SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, nullptr, nullptr, nullptr, nullptr) + == ERROR_SUCCESS); + } + auto const security = securityOf(fixture.hostDirectory() / "open"); + if (security.dacl != nullptr) + SKIP("this file system keeps no NULL DACL (it stored an empty or default one)"); + auto file = fixture.run( + fixture.root().openAt(SymlinkPolicy::NoFollow, "open", OpenFlags::None, DescriptorFlags::Read)); + REQUIRE(file.has_value()); + CHECK(accessOf(fixture, **file) == AccessScope::Shared); +} + +TEST_CASE("windows: an inherit-only entry grants nothing on the directory itself", "[fs][native][access]") +{ + auto fixture = DescriptorFixture::createNative(); + REQUIRE(fixture.run(fixture.root().createDirectoryAt("keys", CreationAccess::OwnerOnly)).has_value()); + // Everyone, for what is created inside only: the directory itself stays the user's. + grantEveryone(fixture.hostDirectory() / "keys", INHERIT_ONLY | SUB_CONTAINERS_AND_OBJECTS_INHERIT); + auto directory = fixture.run( + fixture.root().openAt(SymlinkPolicy::NoFollow, "keys", OpenFlags::Directory, DescriptorFlags::Read)); + REQUIRE(directory.has_value()); + CHECK(accessOf(fixture, **directory) == AccessScope::OwnerOnly); +} + +namespace +{ + +/// The system's NT calls, except that an open of `guarded` asking for READ_CONTROL is refused, as a +/// DACL that withholds it refuses one. +class ReadControlWithheld final: public core::fs::detail::INtFiles +{ + public: + core::fs::FsResult open( + HANDLE directory, + std::wstring const& name, + core::fs::detail::NtOpenRequest const& request) const override + { + if (name == L"guarded" && (request.access & READ_CONTROL) != 0) + return std::unexpected { core::fs::FsError { + .code = core::fs::FsErrorCode::Access, .systemCode = 0, .context = "NtCreateFile" } }; + return core::fs::detail::systemNtFiles().open(directory, name, request); + } + + core::fs::FsResult attributes(HANDLE handle) const override + { + return core::fs::detail::systemNtFiles().attributes(handle); + } + + core::fs::FsResult identity(HANDLE handle) const override + { + return core::fs::detail::systemNtFiles().identity(handle); + } + + core::fs::FsResult queryDirectory(HANDLE directory, std::span records) const override + { + return core::fs::detail::systemNtFiles().queryDirectory(directory, records); + } +}; + +/// Drives @p task to its end over the two executors, bounded. +template +T drive(core::async::testing::ManualExecutor& home, + core::async::testing::ManualExecutor& blocking, + core::async::Task task) +{ + task.handle().resume(); + for ([[maybe_unused]] auto const round: std::views::iota(0, 10'000)) + if (task.done() || home.drain() + blocking.drain() == 0) + break; + REQUIRE(task.done()); + return task.result(); +} + +} // namespace + +TEST_CASE("windows: a DACL that withholds READ_CONTROL still stats, with access unknown", + "[fs][native][access]") +{ + auto home = core::async::testing::ManualExecutor {}; + auto blocking = core::async::testing::ManualExecutor {}; + auto const clock = core::platform::ManualWallClock {}; + auto random = core::fs::test::FixedRandom { 1 }; + auto const directory = core::testing::ScopedTempDir { "core-cpp-fs-read-control" }; + std::filesystem::create_directory(directory.path() / "root"); + std::ofstream { directory.path() / "root" / "guarded" } << "x"; + auto const files = ReadControlWithheld {}; + auto fileSystem = + core::fs::detail::makeWindowsDescriptorFileSystem(home, blocking, clock, random, {}, files); + REQUIRE(fileSystem.has_value()); + { + auto root = drive(home, + blocking, + (*fileSystem) + ->openPreopen(directory.path() / "root", + DescriptorFlags::Read | DescriptorFlags::MutateDirectory)); + REQUIRE(root.has_value()); + auto const byName = drive(home, blocking, (*root)->statAt(SymlinkPolicy::NoFollow, "guarded")); + REQUIRE(byName.has_value()); + CHECK(byName->size == 1); + CHECK_FALSE(byName->access.has_value()); + auto bare = drive( + home, + blocking, + (*root)->openAt(SymlinkPolicy::NoFollow, "guarded", OpenFlags::None, DescriptorFlags::None)); + REQUIRE(bare.has_value()); + auto const status = drive(home, blocking, (*bare)->stat()); + REQUIRE(status.has_value()); + CHECK_FALSE(status->access.has_value()); + } + fileSystem->reset(); + std::ignore = home.drain() + blocking.drain(); +} diff --git a/src/core/fs/windows/OwnerSecurity.cpp b/src/core/fs/windows/OwnerSecurity.cpp new file mode 100644 index 00000000..c663e36b --- /dev/null +++ b/src/core/fs/windows/OwnerSecurity.cpp @@ -0,0 +1,116 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The process token's user, and the absolute security descriptors an owner-only creation is made +// with: owner that user, a protected DACL with one ALLOW entry for that user alone. +#include + +#include + +#include +#include +#include +#include +#include +#include + +#include + +namespace core::fs::detail +{ + +namespace +{ + + std::unexpected lastError(char const* call) + { + return std::unexpected { fsErrorFromSystemCode(std::int64_t { ::GetLastError() }, call) }; + } + + struct HandleCloser + { + void operator()(void* handle) const noexcept { ::CloseHandle(handle); } + }; + + /// @return The user SID of the process token, copied out of it. + FsResult> tokenUser() + { + auto token = HANDLE {}; + if (::OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY, &token) == FALSE) + return lastError("OpenProcessToken"); + auto const closer = std::unique_ptr { token }; + auto size = DWORD { 0 }; + ::GetTokenInformation(token, TokenUser, nullptr, 0, &size); + if (size == 0) + return lastError("GetTokenInformation(TokenUser)"); + auto buffer = std::vector(size); + if (::GetTokenInformation(token, TokenUser, buffer.data(), size, &size) == FALSE) + return lastError("GetTokenInformation(TokenUser)"); + auto const* const user = reinterpret_cast(buffer.data()); + auto sid = std::vector(::GetLengthSid(user->User.Sid)); + if (::CopySid(static_cast(sid.size()), sid.data(), user->User.Sid) == FALSE) + return lastError("CopySid"); + return sid; + } + +} // namespace + +OwnerSecurity::OwnerSecurity(std::vector user): _user { std::move(user) } +{ +} + +FsResult> OwnerSecurity::ofProcess() +{ + return tokenUser().and_then( + [](std::vector user) -> FsResult> { + // The constructor is private, so make_shared cannot reach it; the pointer is owned at once. + auto security = std::shared_ptr { new OwnerSecurity { std::move(user) } }; + return security->build(security->_file, 0) + .and_then([&] { + return security->build(security->_directory, OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE); + }) + .transform([&] { return std::shared_ptr { std::move(security) }; }); + }); +} + +FsResult OwnerSecurity::build(Descriptor& into, BYTE inheritance) +{ + // One ACCESS_ALLOWED_ACE, whose SID starts at its SidStart member, rounded up to a DWORD. + auto const entrySize = sizeof(ACCESS_ALLOWED_ACE) - sizeof(DWORD) + _user.size(); + auto const aclSize = (sizeof(ACL) + entrySize + sizeof(DWORD) - 1) & ~(sizeof(DWORD) - 1); + into.acl.assign(aclSize, std::byte { 0 }); + auto* const acl = reinterpret_cast(into.acl.data()); + auto* const user = static_cast(_user.data()); + if (::InitializeAcl(acl, static_cast(aclSize), ACL_REVISION) == FALSE) + return lastError("InitializeAcl"); + if (::AddAccessAllowedAceEx(acl, ACL_REVISION, inheritance, FILE_ALL_ACCESS, user) == FALSE) + return lastError("AddAccessAllowedAceEx"); + if (::InitializeSecurityDescriptor(&into.descriptor, SECURITY_DESCRIPTOR_REVISION) == FALSE) + return lastError("InitializeSecurityDescriptor"); + if (::SetSecurityDescriptorOwner(&into.descriptor, user, FALSE) == FALSE) + return lastError("SetSecurityDescriptorOwner"); + if (::SetSecurityDescriptorDacl(&into.descriptor, TRUE, acl, FALSE) == FALSE) + return lastError("SetSecurityDescriptorDacl"); + // Protected: nothing the parent directory would hand down is added to it. + if (::SetSecurityDescriptorControl(&into.descriptor, SE_DACL_PROTECTED, SE_DACL_PROTECTED) == FALSE) + return lastError("SetSecurityDescriptorControl"); + return {}; +} + +PSID OwnerSecurity::user() const noexcept +{ + // The Win32 calls take a SID by non-const pointer and read it only. + return const_cast(_user.data()); +} + +PSECURITY_DESCRIPTOR OwnerSecurity::forFile() const noexcept +{ + // NtCreateFile takes the descriptor by non-const pointer and reads it only. + return const_cast(&_file.descriptor); +} + +PSECURITY_DESCRIPTOR OwnerSecurity::forDirectory() const noexcept +{ + return const_cast(&_directory.descriptor); +} + +} // namespace core::fs::detail diff --git a/src/core/fs/windows/OwnerSecurity.hpp b/src/core/fs/windows/OwnerSecurity.hpp new file mode 100644 index 00000000..7f67a40e --- /dev/null +++ b/src/core/fs/windows/OwnerSecurity.hpp @@ -0,0 +1,68 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// Who "the owner" is on Windows, read once per file system from the process token, and the +/// security descriptors an owner-only creation hands to `NtCreateFile`. Private to the fs module. + +#include +#include + +#include +#include +#include + +#include + +namespace core::fs::detail +{ + +/// The process token's user (`TokenUser`), and two absolute security descriptors made for it: owner +/// that user, and a protected DACL (`SE_DACL_PROTECTED`, nothing inherited) with one ALLOW entry +/// granting that user every right, inheritable on the directory's so what is created inside stays +/// the user's too. The owner is set explicitly: an elevated administrator's new objects are owned by +/// BUILTIN\Administrators by default, which would leave a file the user cannot reach unelevated. +/// +/// The descriptors point into the object's own buffers, so it is neither copied nor moved; it is +/// built by @c ofProcess and shared. +class CORE_FS_API OwnerSecurity +{ + public: + /// Reads the process token's user and builds both descriptors. + /// @return The owner's security; the Win32 error, classified, where the token cannot be read. + [[nodiscard]] static FsResult> ofProcess(); + + OwnerSecurity(OwnerSecurity const&) = delete; + OwnerSecurity(OwnerSecurity&&) = delete; + OwnerSecurity& operator=(OwnerSecurity const&) = delete; + OwnerSecurity& operator=(OwnerSecurity&&) = delete; + ~OwnerSecurity() = default; + + /// @return The token's user SID, for as long as this object lives. + [[nodiscard]] PSID user() const noexcept; + + /// @return The descriptor an owner-only file is created with. + [[nodiscard]] PSECURITY_DESCRIPTOR forFile() const noexcept; + + /// @return The descriptor an owner-only directory is created with. + [[nodiscard]] PSECURITY_DESCRIPTOR forDirectory() const noexcept; + + private: + /// A protected DACL with its one entry, and the descriptor naming it. + struct Descriptor + { + std::vector acl; + SECURITY_DESCRIPTOR descriptor {}; + }; + + explicit OwnerSecurity(std::vector user); + + /// Builds @p into for @c _user with @p inheritance on its entry. + [[nodiscard]] FsResult build(Descriptor& into, BYTE inheritance); + + std::vector _user; + Descriptor _file; + Descriptor _directory; +}; + +} // namespace core::fs::detail diff --git a/src/core/fs/windows/WindowsDescriptor.cpp b/src/core/fs/windows/WindowsDescriptor.cpp index 9d8d125a..73da1c7d 100644 --- a/src/core/fs/windows/WindowsDescriptor.cpp +++ b/src/core/fs/windows/WindowsDescriptor.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -27,8 +28,10 @@ #include #include #include +#include #include #include +#include #include #include #include @@ -190,14 +193,22 @@ namespace return DescriptorType::RegularFile; } - DescriptorStat statOf(Information const& information) noexcept + /// What @p handle tells: its attributes, times and, read from its security descriptor, who may + /// reach it. The handle carries `READ_CONTROL`: every open a stat is made through asks for it. + FsResult statOf(NativeContext const& context, HANDLE handle) { - return DescriptorStat { .type = typeOf(information), - .linkCount = information.standard.NumberOfLinks, - .size = static_cast(information.standard.EndOfFile.QuadPart), - .accessed = fileTimeOf(information.basic.LastAccessTime), - .modified = fileTimeOf(information.basic.LastWriteTime), - .statusChanged = fileTimeOf(information.basic.ChangeTime) }; + return informationOf(handle).transform([&](Information const& information) { + return DescriptorStat { + .type = typeOf(information), + .linkCount = information.standard.NumberOfLinks, + .size = static_cast(information.standard.EndOfFile.QuadPart), + .accessed = fileTimeOf(information.basic.LastAccessTime), + .modified = fileTimeOf(information.basic.LastWriteTime), + .statusChanged = fileTimeOf(information.basic.ChangeTime), + .access = + detail::accessFactsOf(handle, context.ownerSecurity->user()).transform(classifyAccess), + }; + }); } FsResult hashOf(NativeContext const& context, HANDLE handle) @@ -352,7 +363,8 @@ namespace }); } - /// @return The request that opens an entry to read its attributes and, with @p access, more. + /// @return The request that opens an entry to read its attributes and, with @p access, more; a + /// stat asks for `READ_CONTROL` too (@c statRequest), so it can read who may reach it. detail::NtOpenRequest attributesRequest(ACCESS_MASK access) noexcept { return detail::NtOpenRequest { .access = access | FILE_READ_ATTRIBUTES, @@ -361,6 +373,23 @@ namespace .reparse = detail::ReparseHandling::OpenThePoint }; } + /// @return The request a stat by name opens its entry with: attributes and the security descriptor. + detail::NtOpenRequest statRequest() noexcept + { + return attributesRequest(READ_CONTROL); + } + + /// Opens the final name of @p resolved for a stat: with `READ_CONTROL`, and where the object's + /// DACL withholds that (`Access`), again without it, so a stat that succeeded before access was + /// read still does; its access is then unknown (nullopt), never guessed. + FsResult openForStat(NativeContext const& context, Resolved const& resolved) + { + auto opened = openFinal(context, resolved, statRequest()); + if (opened || opened.error().code != FsErrorCode::Access) + return opened; + return openFinal(context, resolved, attributesRequest(0)); + } + struct SyncFlagRow { DescriptorFlags flag; @@ -376,8 +405,10 @@ namespace /// The `NtCreateFile` request for @p open and @p flags. FsResult openRequestOf(OpenFlags open, DescriptorFlags flags) { - auto request = - detail::NtOpenRequest { .access = FILE_READ_ATTRIBUTES, .disposition = FILE_OPEN, .options = 0 }; + // READ_CONTROL: the descriptor's stat reads who may reach the object from this very handle. + auto request = detail::NtOpenRequest { .access = FILE_READ_ATTRIBUTES | READ_CONTROL, + .disposition = FILE_OPEN, + .options = 0 }; if (hasFlag(flags, DescriptorFlags::Read)) request.access |= FILE_GENERIC_READ; if (hasFlag(flags, DescriptorFlags::Write)) @@ -744,10 +775,10 @@ namespace async::Task> stat() override { - return submit([handle = handle(), flags = flags()]() { - return checkRights(flags, Operation::Stat) - .and_then([&] { return informationOf(handle->get()); }) - .transform([](Information const& information) { return statOf(information); }); + return submit([context = context(), handle = handle(), flags = flags()]() { + return checkRights(flags, Operation::Stat).and_then([&] { + return statOf(*context, handle->get()); + }); }); } @@ -822,10 +853,23 @@ namespace return refuse(FsErrorCode::NotDirectory); request->options |= FILE_DIRECTORY_FILE; } + // Owner-only from the moment NtCreateFile makes it; an existing file keeps its own. + if (hasFlag(open, OpenFlags::OwnerOnly)) + request->security = context->ownerSecurity->forFile(); auto const name = detail::utf16Of(resolved->name); if (!name) return std::unexpected { name.error() }; auto child = detail::openEntry(*context->ntFiles, resolved->directory(), *name, *request); + // READ_CONTROL is asked only so stat() can read access; where a descriptor with no + // right of its own meets a DACL that withholds it, the open is made without it, and + // the descriptor's access is unknown. Never on a creation: the creator is granted it. + if (!child && child.error().code == FsErrorCode::Access && !hasFlag(open, OpenFlags::Create) + && !hasFlag(childFlags, DescriptorFlags::Read) + && !hasFlag(childFlags, DescriptorFlags::Write)) + { + request->access &= ~ACCESS_MASK { READ_CONTROL }; + child = detail::openEntry(*context->ntFiles, resolved->directory(), *name, *request); + } if (!child) return std::unexpected { child.error() }; auto const opened = child->handle.get(); @@ -868,13 +912,14 @@ namespace }); } - async::Task> createDirectoryAt(std::string path) override + async::Task> createDirectoryAt(std::string path, CreationAccess access) override { return submit([context = context(), handle = handle(), flags = flags(), type = objectType(), - path = std::move(path)]() { + path = std::move(path), + access]() { return checkRights(flags, Operation::CreateDirectoryAt) .and_then([&] { return detail::requireDirectory(type); }) .and_then([&] { @@ -888,13 +933,16 @@ namespace return vacant(std::move(resolved), DescriptorType::Directory); }) .and_then([&](Resolved const& resolved) { - return openFinal( - *context, - resolved, - detail::NtOpenRequest { .access = FILE_LIST_DIRECTORY, - .disposition = FILE_CREATE, - .options = FILE_DIRECTORY_FILE, - .reparse = detail::ReparseHandling::OpenThePoint }) + return openFinal(*context, + resolved, + detail::NtOpenRequest { + .access = FILE_LIST_DIRECTORY, + .disposition = FILE_CREATE, + .options = FILE_DIRECTORY_FILE, + .reparse = detail::ReparseHandling::OpenThePoint, + .security = access == CreationAccess::OwnerOnly + ? context->ownerSecurity->forDirectory() + : nullptr }) .transform([](UniqueHandle const&) {}); }); }); @@ -913,11 +961,8 @@ namespace .and_then([&] { return resolve(handle->get(), path, *context, policy, TrailingSlashOnLink::Follow); }) - .and_then([&](Resolved const& resolved) { - return openFinal(*context, resolved, attributesRequest(0)); - }) - .and_then([](UniqueHandle const& opened) { return informationOf(opened.get()); }) - .transform([](Information const& information) { return statOf(information); }); + .and_then([&](Resolved const& resolved) { return openForStat(*context, resolved); }) + .and_then([&](UniqueHandle const& opened) { return statOf(*context, opened.get()); }); }); } @@ -1246,19 +1291,26 @@ namespace flags]() -> FsResult> { if (hasFlag(flags, DescriptorFlags::Write)) return refuse(FsErrorCode::IsDirectory); - auto access = - DWORD { FILE_LIST_DIRECTORY | FILE_TRAVERSE | FILE_READ_ATTRIBUTES | SYNCHRONIZE }; + // READ_CONTROL: the root's stat reads who may reach it from this handle. + auto access = DWORD { FILE_LIST_DIRECTORY | FILE_TRAVERSE | FILE_READ_ATTRIBUTES + | READ_CONTROL | SYNCHRONIZE }; if (hasFlag(flags, DescriptorFlags::MutateDirectory)) access |= FILE_WRITE_ATTRIBUTES; // The host chose this directory, so the system resolves its path. - auto const opened = ::CreateFileW(path.c_str(), - access, - FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, - nullptr, - OPEN_EXISTING, - FILE_FLAG_BACKUP_SEMANTICS | SECURITY_SQOS_PRESENT - | SECURITY_IDENTIFICATION, - nullptr); + auto const openWith = [&](DWORD wanted) { + return ::CreateFileW(path.c_str(), + wanted, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + nullptr, + OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS | SECURITY_SQOS_PRESENT + | SECURITY_IDENTIFICATION, + nullptr); + }; + auto opened = openWith(access); + // A DACL that withholds READ_CONTROL opens the root without it: its access is unknown. + if (opened == INVALID_HANDLE_VALUE && ::GetLastError() == ERROR_ACCESS_DENIED) + opened = openWith(access & ~DWORD { READ_CONTROL }); if (opened == INVALID_HANDLE_VALUE) return lastError("CreateFileW"); auto handle = UniqueHandle { opened }; @@ -1289,10 +1341,21 @@ FsResult> makeNativeDescriptorFileSystem( IRandom& random, NativeFileSystemOptions options) { - return detail::checkOptions(options).transform([&] -> std::unique_ptr { - return std::make_unique(std::make_shared( - home, blocking, wallClock, random, options, KernelSeparators, &detail::systemNtFiles())); - }); + return detail::checkOptions(options) + .and_then([] { return detail::OwnerSecurity::ofProcess(); }) + .transform([&](std::shared_ptr security) + -> std::unique_ptr { + return std::make_unique( + std::make_shared(home, + blocking, + wallClock, + random, + options, + KernelSeparators, + &detail::systemNtFiles(), + std::move(security), + nullptr)); + }); } FsResult> detail::makeWindowsDescriptorFileSystem( @@ -1303,10 +1366,21 @@ FsResult> detail::makeWindowsDescriptorFi NativeFileSystemOptions options, INtFiles const& files) { - return detail::checkOptions(options).transform([&] -> std::unique_ptr { - return std::make_unique(std::make_shared( - home, blocking, wallClock, random, options, KernelSeparators, &files)); - }); + return detail::checkOptions(options) + .and_then([] { return detail::OwnerSecurity::ofProcess(); }) + .transform([&](std::shared_ptr security) + -> std::unique_ptr { + return std::make_unique( + std::make_shared(home, + blocking, + wallClock, + random, + options, + KernelSeparators, + &files, + std::move(security), + nullptr)); + }); } } // namespace core::fs From 534a7884a65fd96d1080ffe97412ff51cde1b606 Mon Sep 17 00:00:00 2001 From: Christian Parpart Date: Fri, 27 Nov 2026 07:08:08 +0100 Subject: [PATCH 18/19] feat(fs): directory containment decided on opened handles, and the rooted link-target rule The rooted link-target rule as a path-policy query. isRootedLinkTarget answers whether a symbolic link's target names a root under a PathPolicy: a leading target separator, or a first component holding a volume separator. The walk's splice asks it instead of a private check, so a WASI host refusing an absolute readlink-at target and the resolver refusing to follow one share one definition. Decide directory containment on opened handles. IDescriptorFileSystem::relation answers whether one directory is, contains or lies beneath another by walking each one's real parents to the root and comparing identities, never path text: a symlinked, junctioned or bind-mounted component of the opening path changes nothing, and nor does a rename after the open. POSIX walks the kernel's own .. (O_PATH where defined), so mounts and bind mounts are crossed upward as the kernel sees them. Windows reads the final path by volume GUID, opens each ancestor prefix and every folder its volume is mounted on for its FILE_ID_INFO, trusts identities only on the file systems of StableFileIdRows (NTFS, ReFS) and never a zero id, and answers Busy where the final paths changed during the walk. Every walk stops at NativeFileSystemOptions::maxAncestorDepth (4096) with Loop and grows its chain per step. The in-memory model keeps parent links and an IdentityModel row, Unavailable answering Unsupported, so consumers test their fail-closed path on every OS. Foreign descriptors are CrossDevice (D11). Under wine the native Windows cases skip: wine cannot open the volume GUID paths it hands out and names a renamed handle by its old path. Also in this commit: - fail closed past a mount of a subtree, and check every relation walk - rename only the opened directories in the relation races - name the first unexpected answer of a relation race - a Windows relation that loses a name to a rename is Busy - run diskpart as a child of its own, bounded - the swap race runs until its swapper has swapped enough - the move race asks for a decided parent, not for both - decide a relation past a mount of a subtree by the mounts' identities - a move between a relation's two passes is Busy - the move race must find a beneath y - run the Linux relation rows in their own user namespace - decide past a macOS firmlink or a re-exposing file system only on its own terms - a firmlink also skips its volume's mount point path - relation() refuses where a mount beneath either directory shows the other - the Windows volume cases fail rather than skip where the run is elevated - Windows owner-only creation reads its access back (with the volume support it shares with the relation cases) - access is not judged where the mode does not bound it (NFS, SMB, NFSv4 ACLs, NetBSD) - readlinkAt refuses a target that names a root Signed-off-by: Christian Parpart --- .agent/reference/provenance.md | 29 +- .github/workflows/build.yml | 36 + src/core/fs/CMakeLists.txt | 60 +- src/core/fs/Descriptor.hpp | 65 +- src/core/fs/DescriptorContract_test.cpp | 199 ++++ src/core/fs/DescriptorEscape_test.cpp | 6 +- src/core/fs/DescriptorTestSupport.hpp | 28 +- src/core/fs/NativeFileSystem.hpp | 11 + src/core/fs/PathPolicy.cpp | 10 + src/core/fs/PathPolicy.hpp | 12 + src/core/fs/PathPolicy_test.cpp | 82 ++ src/core/fs/RelationMemory_test.cpp | 92 ++ src/core/fs/Relation_test.cpp | 243 +++++ src/core/fs/bsd/MountBoundaries.cpp | 164 ++++ src/core/fs/bsd/MountExit.cpp | 21 + src/core/fs/bsd/MountExit.hpp | 24 + src/core/fs/bsd/Relation_test.cpp | 93 ++ src/core/fs/darwin/MountExit.cpp | 169 ++++ src/core/fs/darwin/Relation_test.cpp | 157 ++++ src/core/fs/detail/Ancestry.cpp | 39 + src/core/fs/detail/Ancestry.hpp | 53 ++ src/core/fs/detail/NativeSupport.cpp | 43 +- src/core/fs/detail/NativeSupport.hpp | 47 +- src/core/fs/detail/PathWalk.cpp | 14 +- src/core/fs/detail/PathWalk.hpp | 8 + src/core/fs/linux/AccessFacts.cpp | 68 ++ src/core/fs/linux/MountBoundaries.cpp | 282 ++++++ src/core/fs/linux/MountInfo.hpp | 55 ++ src/core/fs/linux/MountInfo_test.cpp | 99 ++ src/core/fs/linux/Relation_test.cpp | 266 ++++++ src/core/fs/posix/AccessFacts.cpp | 23 +- src/core/fs/posix/Ancestry.cpp | 452 +++++++++ src/core/fs/posix/ModeCappedCreation.cpp | 28 + src/core/fs/posix/MountBoundaries.cpp | 86 ++ src/core/fs/posix/MountBoundaries.hpp | 198 ++++ src/core/fs/posix/MountBoundaries_test.cpp | 854 ++++++++++++++++++ src/core/fs/posix/OwnerOnly_test.cpp | 12 + src/core/fs/posix/PosixDescriptor.cpp | 12 +- src/core/fs/posix/PosixSystem.hpp | 8 +- src/core/fs/posix/UnknownAccessFacts.cpp | 22 + .../testing/InMemoryDescriptorFileSystem.cpp | 104 ++- .../testing/InMemoryDescriptorFileSystem.hpp | 25 +- src/core/fs/windows/Ancestry.cpp | 328 +++++++ src/core/fs/windows/OwnerOnly_test.cpp | 46 +- src/core/fs/windows/Relation_test.cpp | 147 +++ src/core/fs/windows/StableFileIdRows.cpp | 71 ++ src/core/fs/windows/StableFileIdRows.hpp | 53 ++ .../fs/windows/VirtualVolumeTestSupport.hpp | 143 +++ src/core/fs/windows/WindowsDescriptor.cpp | 70 +- 49 files changed, 5063 insertions(+), 94 deletions(-) create mode 100644 src/core/fs/PathPolicy_test.cpp create mode 100644 src/core/fs/RelationMemory_test.cpp create mode 100644 src/core/fs/Relation_test.cpp create mode 100644 src/core/fs/bsd/MountBoundaries.cpp create mode 100644 src/core/fs/bsd/MountExit.cpp create mode 100644 src/core/fs/bsd/MountExit.hpp create mode 100644 src/core/fs/bsd/Relation_test.cpp create mode 100644 src/core/fs/darwin/MountExit.cpp create mode 100644 src/core/fs/darwin/Relation_test.cpp create mode 100644 src/core/fs/detail/Ancestry.cpp create mode 100644 src/core/fs/detail/Ancestry.hpp create mode 100644 src/core/fs/linux/AccessFacts.cpp create mode 100644 src/core/fs/linux/MountBoundaries.cpp create mode 100644 src/core/fs/linux/MountInfo.hpp create mode 100644 src/core/fs/linux/MountInfo_test.cpp create mode 100644 src/core/fs/linux/Relation_test.cpp create mode 100644 src/core/fs/posix/Ancestry.cpp create mode 100644 src/core/fs/posix/ModeCappedCreation.cpp create mode 100644 src/core/fs/posix/MountBoundaries.cpp create mode 100644 src/core/fs/posix/MountBoundaries.hpp create mode 100644 src/core/fs/posix/MountBoundaries_test.cpp create mode 100644 src/core/fs/posix/UnknownAccessFacts.cpp create mode 100644 src/core/fs/windows/Ancestry.cpp create mode 100644 src/core/fs/windows/Relation_test.cpp create mode 100644 src/core/fs/windows/StableFileIdRows.cpp create mode 100644 src/core/fs/windows/StableFileIdRows.hpp create mode 100644 src/core/fs/windows/VirtualVolumeTestSupport.hpp diff --git a/.agent/reference/provenance.md b/.agent/reference/provenance.md index 5ff281d3..350558d5 100644 --- a/.agent/reference/provenance.md +++ b/.agent/reference/provenance.md @@ -176,14 +176,21 @@ others in notes. | `src/core/fs/NativeFileSystem.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): `makeNativeDescriptorFileSystem` and its options | | `src/core/fs/PathPolicy.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the POSIX and Windows rows | | `src/core/fs/PathPolicy.hpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/fs/PathPolicy_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): `isRootedLinkTarget` over both policies | +| `src/core/fs/RelationMemory_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): what one relation holds while it walks, counted | +| `src/core/fs/Relation_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the native relation under a rename race, every OS | | `src/core/fs/Rights.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the rights table and `checkOpenRights`, after wasmtime's descriptor permissions | | `src/core/fs/Rights.hpp` | origin: core-cpp | - | - | 0.24.0 (P13) | | `src/core/fs/bsd/AccessFacts.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): FreeBSD's access reader, NFSv4 ACLs | | `src/core/fs/bsd/ErrnoTable.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): Apple and the BSDs; `EMLINK` for FreeBSD's `O_NOFOLLOW` | | `src/core/fs/bsd/InheritableAcl_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): an NFSv4 `setfacl`, FreeBSD | +| `src/core/fs/bsd/MountBoundaries.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): mount boundaries from fstatfs on macOS and the BSDs | +| `src/core/fs/bsd/Relation_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): a nullfs mount beneath a grant that shows the key, FreeBSD | | `src/core/fs/darwin/AccessFacts.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): macOS's access reader, extended ACLs | | `src/core/fs/darwin/InheritableAcl_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): `chmod +a`, macOS | | `src/core/fs/darwin/PosixSystem.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): Apple: `st_atimespec`, `F_RDADVISE`, `F_FULLFSYNC`, `EACCES` for `O_CREAT` on a directory | +| `src/core/fs/detail/Ancestry.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): `decideRelation`, shared by the walkers and the model | +| `src/core/fs/detail/Ancestry.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): `ObjectIdentity`, `decideRelation`, `nativeRelation` | | `src/core/fs/detail/DirectoryStream.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | | `src/core/fs/detail/DirectoryStream.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): the batched directory stream every implementation reads through | | `src/core/fs/detail/NativeSupport.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | @@ -196,6 +203,7 @@ others in notes. | `src/core/fs/linux/Append.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): `pwritev2(RWF_APPEND)`, and a write at the end `fstat` reports, under the descriptor's lock, where the flag is refused | | `src/core/fs/linux/Append.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): `appendAtEnd`, the append where `RWF_APPEND` is refused | | `src/core/fs/linux/Append_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/fs/linux/AccessFacts.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the access reader of Linux; nothing is judged on NFS, SMB or an NFSv4 ACL | | `src/core/fs/linux/BeneathDefault.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): `Best` on Linux is `openat2`, probed; the walk opens `O_PATH` | | `src/core/fs/linux/DirectoryRead.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): a directory stream's `getdents64` records, field by field, in one fixed buffer | | `src/core/fs/linux/DirectoryRead.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): `parseDirentRecords`, the `getdents64` record seam | @@ -203,10 +211,17 @@ others in notes. | `src/core/fs/linux/DescriptorEscape_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): no path goes through a `/proc` magic link | | `src/core/fs/linux/Lease.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): an open under a lease made again, waiting, through a path handle checked to be a regular file | | `src/core/fs/linux/Lease_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/fs/linux/MountBoundaries.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): mount boundaries from statx and mountinfo | +| `src/core/fs/linux/MountInfo.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): the root column of mountinfo | +| `src/core/fs/linux/MountInfo_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | | `src/core/fs/linux/Openat2.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): `openat2(RESOLVE_BENEATH | RESOLVE_NO_MAGICLINKS)`, the probe and the bounded `EAGAIN` retry | | `src/core/fs/linux/Openat2.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): the `openat2` system-call seam | | `src/core/fs/linux/Openat2_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | -| `src/core/fs/posix/AccessFacts.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the access reader of Linux and every POSIX system without an ACL of its own | +| `src/core/fs/linux/Relation_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): relation across a mount and a bind mount | +| `src/core/fs/posix/AccessFacts.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the access reader of OpenBSD and DragonFly, whose mode bounds every access | +| `src/core/fs/posix/ModeCappedCreation.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): owner-only creation where the creating mode caps what a directory hands down | +| `src/core/fs/posix/UnknownAccessFacts.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the access reader of NetBSD and every other POSIX system: nothing is judged | +| `src/core/fs/posix/Ancestry.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the POSIX walker, through the kernel's own `..` | | `src/core/fs/posix/Append.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the second, `O_APPEND` handle of every POSIX system but Linux | | `src/core/fs/posix/BeneathDefault.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): `Best` is the walk on every POSIX system but Linux; `#ifdef O_PATH` inside the data picks the walk's open flags | | `src/core/fs/posix/DescriptorTestSupport.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): `runsUnderWine` on POSIX | @@ -220,6 +235,13 @@ others in notes. | `src/core/fs/posix/InheritableAcl.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): how a test plants an inheritable ACL, per OS | | `src/core/fs/posix/InheritableAcl_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): `setfacl -d`, Linux | | `src/core/fs/posix/Lease.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): no leases off Linux: `WouldBlock` | +| `src/core/fs/posix/MountBoundaries.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): mount boundaries where nothing tells what a mount shows | +| `src/core/fs/posix/MountBoundaries.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): `IMountBoundaries` | +| `src/core/fs/posix/MountBoundaries_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): what a mount left may hide, and the relation walk under scripted boundaries | +| `src/core/fs/bsd/MountExit.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): whether a walk left a mount from its root, macOS and the BSDs | +| `src/core/fs/bsd/MountExit.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the BSDs leave a mount only at its root | +| `src/core/fs/darwin/MountExit.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): a macOS firmlink leaves the Data volume below its root | +| `src/core/fs/darwin/Relation_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the relation across a macOS firmlink | | `src/core/fs/posix/NativePathPolicy.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | | `src/core/fs/posix/OwnedHandleAllocation_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the last close when its frame cannot be allocated; replaces the global allocation functions | | `src/core/fs/posix/OwnerOnlyCreation.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): owner-only creation, direct or through a stripped staging directory | @@ -237,6 +259,7 @@ others in notes. | `src/core/fs/testing/InMemoryDescriptorFileSystem_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | | `src/core/fs/windows/AccessFacts.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the Windows access reader, owner and DACL by handle | | `src/core/fs/windows/AccessFacts.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): the Windows access reader | +| `src/core/fs/windows/Ancestry.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the Windows walker, by final path and file id | | `src/core/fs/windows/BeneathDefault.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): `Best` is the walk on Windows | | `src/core/fs/windows/DescriptorEscape_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): junctions, mount points, backslash targets, link flavour, private reparse tags | | `src/core/fs/windows/DescriptorTestSupport.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): `runsUnderWine` on Windows | @@ -249,8 +272,12 @@ others in notes. | `src/core/fs/windows/OwnerOnly_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | | `src/core/fs/windows/OwnerSecurity.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the token user and the owner-only security descriptors | | `src/core/fs/windows/OwnerSecurity.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): the token user and the owner-only security descriptors | +| `src/core/fs/windows/Relation_test.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/fs/windows/VirtualVolumeTestSupport.hpp` | origin: core-cpp | - | - | 0.24.0 (P13): the diskpart virtual disks the volume cases need, and their elevation rule | | `src/core/fs/windows/ReparsePoint.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): reparse data, field by field | | `src/core/fs/windows/ReparsePoint.hpp` | origin: core-cpp | - | - | 0.24.0 (P13) | +| `src/core/fs/windows/StableFileIdRows.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the file systems whose ids relation trusts | +| `src/core/fs/windows/StableFileIdRows.hpp` | origin: core-cpp | - | - | 0.24.0 (P13) | | `src/core/fs/windows/Win32ErrorTable.cpp` | origin: core-cpp | - | - | 0.24.0 (P13) | | `src/core/fs/windows/WindowsDescriptor.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the Windows native descriptors | | `src/core/fs/windows/WindowsPathWalk.cpp` | origin: core-cpp | - | - | 0.24.0 (P13): the Windows component walker and the NT seam | diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 29b7d3c5..aa3783eb 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -485,7 +485,15 @@ jobs: - name: Build run: cmake --build --preset ${{ matrix.preset }} + # Ubuntu 24.04's AppArmor refuses an unprivileged process its own user namespace, so the + # Linux relation rows across bind and tmpfs mounts (src/core/fs/linux/Relation_test.cpp) + # would skip; with the restriction lifted, CORE_TEST_REQUIRE_USERNS makes such a skip fail. + - name: Allow unprivileged user namespaces + run: sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 + - name: Test + env: + CORE_TEST_REQUIRE_USERNS: "1" run: ctest --preset ${{ matrix.preset }} -LE tree-level # --------------------------------------------------------------------------------------------- @@ -821,7 +829,18 @@ jobs: # # To exclude another label here, extend this regex -- `-LE 'tree-level|other'` -- and never # add a second flag. + + # Ubuntu 24.04's AppArmor refuses an unprivileged process its own user namespace, so the + # Linux relation rows across bind and tmpfs mounts (src/core/fs/linux/Relation_test.cpp) + # would skip; with the restriction lifted, CORE_TEST_REQUIRE_USERNS makes such a skip fail. + - name: Allow unprivileged user namespaces + run: sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 + + # Not under TSan: its runtime keeps a thread of its own in a forked child, and the kernel + # refuses a user namespace to a process with more than one thread (unshare: EINVAL). - name: Test + env: + CORE_TEST_REQUIRE_USERNS: ${{ matrix.preset == 'clang-tsan' && '0' || '1' }} run: ctest --preset ${{ matrix.preset }} -LE tree-level # --------------------------------------------------------------------------------------------- @@ -1249,7 +1268,16 @@ jobs: [ "${hits:-0}" -ge 1 ] || { echo "::error::pace-cc --show-stats shows no hits"; exit 1; } # A replayed object is only as good as what it runs: the tests run on the cache's objects. + + # Ubuntu 24.04's AppArmor refuses an unprivileged process its own user namespace, so the + # Linux relation rows across bind and tmpfs mounts (src/core/fs/linux/Relation_test.cpp) + # would skip; with the restriction lifted, CORE_TEST_REQUIRE_USERNS makes such a skip fail. + - name: Allow unprivileged user namespaces + run: sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 + - name: Test the replayed build + env: + CORE_TEST_REQUIRE_USERNS: "1" run: ctest --preset "$PRESET" -LE tree-level # --------------------------------------------------------------------------------------------- @@ -1495,7 +1523,15 @@ jobs: - name: Build run: cmake --build --preset clang-coverage + # Ubuntu 24.04's AppArmor refuses an unprivileged process its own user namespace, so the + # Linux relation rows across bind and tmpfs mounts (src/core/fs/linux/Relation_test.cpp) + # would skip; with the restriction lifted, CORE_TEST_REQUIRE_USERNS makes such a skip fail. + - name: Allow unprivileged user namespaces + run: sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 + - name: Test + env: + CORE_TEST_REQUIRE_USERNS: "1" run: | mkdir -p out/build/clang-coverage/profiles LLVM_PROFILE_FILE="$PWD/out/build/clang-coverage/profiles/%m-%p.profraw" ctest --preset clang-coverage -LE tree-level diff --git a/src/core/fs/CMakeLists.txt b/src/core/fs/CMakeLists.txt index 7da919c9..ce263868 100644 --- a/src/core/fs/CMakeLists.txt +++ b/src/core/fs/CMakeLists.txt @@ -27,28 +27,40 @@ # system has leases (posix/). # - DirectoryRead.cpp: a directory stream reads Linux's getdents64 records into a fixed buffer # (linux/); every other POSIX system reads through fdopendir and readdir (posix/). -# - AccessFacts.cpp: who may reach an object, read from its handle. Linux, and every POSIX system -# without an ACL of its own, needs only the fstat (posix/); FreeBSD reads an NFSv4 ACL +# - AccessFacts.cpp: who may reach an object, read from its handle. Linux reads the fstat and +# judges nothing on an NFS or SMB mount or an object with an NFSv4 ACL (linux/); OpenBSD and +# DragonFly need only the fstat (posix/); NetBSD, whose ACLs are not read, and any other POSIX +# system judge nothing (posix/UnknownAccessFacts.cpp); the mode caps what they inherit +# (posix/ModeCappedCreation.cpp). FreeBSD reads an NFSv4 ACL # (bsd/), macOS an extended one (darwin/), Windows the owner and DACL (windows/, beside # OwnerSecurity.cpp, the descriptor owner-only creations are made with). Each fills the same # AccessFacts, and AccessScope.cpp decides from them on every OS. +# - MountBoundaries.cpp: what a relation walk that leaves a mount reads of it. Linux reads the +# mount's device, root and type in mountinfo (linux/); macOS and the BSDs read the mount and its +# type from fstatfs (bsd/), and whether the step left from its root from MountExit.cpp: macOS's +# firmlinks leave below it (darwin/), the other BSDs only at it (bsd/); any other POSIX system +# knows the device alone (posix/). Windows +# walks by final path and needs none (windows/Ancestry.cpp). if(WIN32) set(_coreCppFsPlatform windows/Win32ErrorTable.cpp windows/NtStatusTable.cpp windows/BeneathDefault.cpp windows/AccessFacts.cpp) set(_coreCppFsPrivateLibs ntdll advapi32) elseif(APPLE) - set(_coreCppFsPlatform bsd/ErrnoTable.cpp darwin/PosixSystem.cpp posix/Append.cpp posix/BeneathDefault.cpp posix/DirectoryRead.cpp posix/Lease.cpp darwin/AccessFacts.cpp) + set(_coreCppFsPlatform bsd/ErrnoTable.cpp darwin/PosixSystem.cpp posix/Append.cpp posix/BeneathDefault.cpp posix/DirectoryRead.cpp posix/Lease.cpp darwin/AccessFacts.cpp bsd/MountBoundaries.cpp darwin/MountExit.cpp) elseif(CORE_CPP_PLATFORM_BSD) - set(_coreCppFsPlatform bsd/ErrnoTable.cpp posix/PosixSystem.cpp posix/Append.cpp posix/BeneathDefault.cpp posix/DirectoryRead.cpp posix/Lease.cpp) - # NFSv4 ACLs are FreeBSD's; the other BSDs have none beyond what the mode bounds. + set(_coreCppFsPlatform bsd/ErrnoTable.cpp posix/PosixSystem.cpp posix/Append.cpp posix/BeneathDefault.cpp posix/DirectoryRead.cpp posix/Lease.cpp bsd/MountBoundaries.cpp bsd/MountExit.cpp) + # FreeBSD's NFSv4 ACLs are read; NetBSD's are not, so nothing is judged there; OpenBSD and + # DragonFly have none beyond what the mode bounds. if(CMAKE_SYSTEM_NAME STREQUAL "FreeBSD") list(APPEND _coreCppFsPlatform bsd/AccessFacts.cpp) + elseif(CMAKE_SYSTEM_NAME STREQUAL "NetBSD") + list(APPEND _coreCppFsPlatform posix/UnknownAccessFacts.cpp posix/ModeCappedCreation.cpp) else() - list(APPEND _coreCppFsPlatform posix/AccessFacts.cpp) + list(APPEND _coreCppFsPlatform posix/AccessFacts.cpp posix/ModeCappedCreation.cpp) endif() elseif(LINUX) - set(_coreCppFsPlatform posix/ErrnoTable.cpp posix/PosixSystem.cpp linux/Append.cpp linux/BeneathDefault.cpp linux/DirectoryRead.cpp linux/Lease.cpp posix/AccessFacts.cpp) + set(_coreCppFsPlatform posix/ErrnoTable.cpp posix/PosixSystem.cpp linux/Append.cpp linux/BeneathDefault.cpp linux/DirectoryRead.cpp linux/Lease.cpp linux/AccessFacts.cpp posix/ModeCappedCreation.cpp linux/MountBoundaries.cpp) else() - set(_coreCppFsPlatform posix/ErrnoTable.cpp posix/PosixSystem.cpp posix/Append.cpp posix/BeneathDefault.cpp posix/DirectoryRead.cpp posix/Lease.cpp posix/AccessFacts.cpp) + set(_coreCppFsPlatform posix/ErrnoTable.cpp posix/PosixSystem.cpp posix/Append.cpp posix/BeneathDefault.cpp posix/DirectoryRead.cpp posix/Lease.cpp posix/UnknownAccessFacts.cpp posix/ModeCappedCreation.cpp posix/MountBoundaries.cpp) endif() # The openat2 path spells the call's ABI itself (linux/Openat2.hpp), so no UAPI 5.6 headers or glibc @@ -69,6 +81,8 @@ core_cpp_add_module(fs KIND STATIC FsError.cpp PathPolicy.cpp Rights.cpp + detail/Ancestry.cpp + detail/Ancestry.hpp detail/DirectoryStream.cpp detail/DirectoryStream.hpp detail/NativeSupport.cpp @@ -80,8 +94,10 @@ core_cpp_add_module(fs KIND STATIC testing/InMemoryDescriptorFileSystem.cpp ${_coreCppFsPlatform} SOURCES_POSIX + posix/Ancestry.cpp posix/DirectoryEntries.cpp posix/DirectoryRead.hpp + posix/MountBoundaries.hpp posix/ErrnoRows.hpp posix/NativePathPolicy.cpp posix/OwnerOnlyCreation.cpp @@ -93,9 +109,11 @@ core_cpp_add_module(fs KIND STATIC SOURCES_LINUX linux/Append.hpp linux/DirectoryRead.hpp + linux/MountInfo.hpp linux/Openat2.cpp linux/Openat2.hpp SOURCES_WINDOWS + windows/Ancestry.cpp windows/DirectoryRecords.cpp windows/DirectoryRecords.hpp windows/NativePathPolicy.cpp @@ -105,6 +123,8 @@ core_cpp_add_module(fs KIND STATIC windows/OwnerSecurity.hpp windows/ReparsePoint.cpp windows/ReparsePoint.hpp + windows/StableFileIdRows.cpp + windows/StableFileIdRows.hpp windows/WindowsDescriptor.cpp windows/WindowsPathWalk.cpp windows/WindowsPathWalk.hpp @@ -114,10 +134,12 @@ core_cpp_add_module(fs KIND STATIC # posix/Append.cpp, posix/BeneathDefault.cpp, posix/DirectoryRead.cpp and posix/Lease.cpp are what Apple and # the BSDs append, resolve, read directories and open leased files with, # so a Linux build would never compile them: parse them there too, so a rename or a dropped include -# shows up before a macOS job does. +# shows up before a macOS job does. posix/MountBoundaries.cpp, which only a POSIX system that is +# neither Linux, Apple nor a BSD builds, is parsed with them. if(LINUX) core_cpp_add_unbuilt_source_check(fs-posix SOURCES posix/Append.cpp posix/BeneathDefault.cpp posix/DirectoryRead.cpp posix/Lease.cpp + posix/MountBoundaries.cpp PART_OF fs USAGE core::base core::async core::platform) endif() @@ -131,6 +153,15 @@ else() set(_coreCppFsInheritableAcl posix/InheritableAcl_test.cpp) endif() +# The relation across macOS's own volumes: a firmlink leaves the Data volume below its root, and a +# disk image mounted beneath a grant. On FreeBSD, nullfs and tmpfs mounts beneath a grant. +set(_coreCppFsMountTests) +if(APPLE) + set(_coreCppFsMountTests darwin/Relation_test.cpp) +elseif(CMAKE_SYSTEM_NAME STREQUAL "FreeBSD") + set(_coreCppFsMountTests bsd/Relation_test.cpp) +endif() + # One binary: every case links core::fs and nothing the module's row does not list. # DescriptorTestSupport.hpp is the test-only fixture the descriptor cases share. core_cpp_add_test(fs @@ -142,13 +173,17 @@ core_cpp_add_test(fs DirectoryStream_test.cpp FsError_test.cpp NativeDescriptor_test.cpp + PathPolicy_test.cpp + Relation_test.cpp detail/PathWalk_test.cpp testing/InMemoryDescriptorFileSystem_test.cpp SOURCES_POSIX posix/DescriptorTestSupport.cpp posix/DirectoryEntries_test.cpp + posix/MountBoundaries_test.cpp posix/InheritableAcl.hpp ${_coreCppFsInheritableAcl} + ${_coreCppFsMountTests} posix/OwnerOnly_test.cpp posix/PosixDescriptor_test.cpp posix/PosixPathWalk_test.cpp @@ -157,12 +192,16 @@ core_cpp_add_test(fs linux/DescriptorEscape_test.cpp linux/DirectoryRead_test.cpp linux/Lease_test.cpp + linux/MountInfo_test.cpp linux/Openat2_test.cpp + linux/Relation_test.cpp SOURCES_WINDOWS windows/DescriptorEscape_test.cpp windows/DescriptorTestSupport.cpp windows/DirectoryRecords_test.cpp windows/OwnerOnly_test.cpp + windows/Relation_test.cpp + windows/VirtualVolumeTestSupport.hpp windows/WindowsPathWalk_test.cpp) # What the last owner of a handle does when its queued close cannot be allocated: a binary of its own @@ -175,4 +214,7 @@ if(NOT CORE_CPP_SANITIZERS AND NOT WIN32) # What a directory stream holds while it reads a large directory, counted the same way. core_cpp_add_test(fs NAME fs-memory SOURCES posix/DirectoryStreamMemory_test.cpp DescriptorTestSupport.hpp ../testing/ReplacedGlobalAllocation.cpp) + # What a relation holds while it walks, counted the same way. + core_cpp_add_test(fs NAME fs-relation-memory + SOURCES RelationMemory_test.cpp DescriptorTestSupport.hpp ../testing/ReplacedGlobalAllocation.cpp) endif() diff --git a/src/core/fs/Descriptor.hpp b/src/core/fs/Descriptor.hpp index ffb9ac7f..ace4b0ac 100644 --- a/src/core/fs/Descriptor.hpp +++ b/src/core/fs/Descriptor.hpp @@ -192,8 +192,10 @@ struct DescriptorStat /// Who may reach it, read from the handle the stat was made through (@c classifyAccess). /// /// **nullopt means "cannot judge", never "probably fine"**: an ACL that cannot be read, a - /// Windows object whose DACL withholds `READ_CONTROL`, a FreeBSD or macOS - /// @c IDescriptor::statAt, which holds no handle to read an ACL from. A consumer that guards a + /// Windows object whose DACL withholds `READ_CONTROL`, a Linux, FreeBSD or macOS + /// @c IDescriptor::statAt, which holds no handle to read an ACL or a file system from, an object + /// on Linux whose NFS or SMB mount or NFSv4 ACL the mode does not bound, and every object on + /// NetBSD and on POSIX systems this module reads no ACL of. A consumer that guards a /// secret with this (a key directory, a key file) must refuse nullopt as it refuses /// @c AccessScope::Shared: fail closed. An object created owner-only (@c OpenFlags::OwnerOnly, /// @c CreationAccess::OwnerOnly) reads @c AccessScope::OwnerOnly through its handle when it is @@ -374,7 +376,8 @@ class IDescriptor /// Reads a symbolic link's target. Needs `Read`. /// @param path The relative path of the link. - /// @return Its target, as stored. + /// @return Its target, as stored; `NotPermitted` for a target that names a root + /// (@c isRootedLinkTarget), which no walk follows and no `symlinkAt` makes. [[nodiscard]] virtual async::Task> readlinkAt(std::string path) = 0; /// Removes the empty directory @p path. Needs `MutateDirectory`. @@ -416,6 +419,16 @@ class IDescriptor [[nodiscard]] virtual async::Task> isSameObject(IDescriptor* other) = 0; }; +/// How two opened directories relate in the real directory tree. `Same` is zero, so a +/// zero-initialized value refuses in a guard that admits only `Unrelated`. +enum class Relation : std::uint8_t +{ + Same, ///< One directory. + FirstContainsSecond, ///< The first is a real ancestor of the second. + SecondContainsFirst, ///< The second is a real ancestor of the first. + Unrelated, ///< Neither lies beneath the other. +}; + /// Opens preopened directories, the roots every other descriptor descends from. class IDescriptorFileSystem { @@ -433,6 +446,52 @@ class IDescriptorFileSystem /// @return The root descriptor. [[nodiscard]] virtual async::Task>> openPreopen( std::filesystem::path hostDirectory, DescriptorFlags flags) = 0; + + /// Decides whether @p first is, contains or lies beneath @p second on the opened handles: each + /// one's real parents are walked up to the root and compared by identity (device and inode; + /// volume serial and file id on Windows), never by path text. So a component of the path either + /// was opened by that is a symbolic link, a junction or a mount of a whole file system changes + /// nothing, and nor does a rename after the open: what counts is where the object is now. A + /// mount that shows only a subtree of its file system -- a bind mount of a subdirectory, a btrfs + /// subvolume, a nullfs mount -- hides the directories of that file system above the subtree + /// from a walk that leaves it; a macOS firmlink (`/Users`) leaves the Data volume below its + /// root and skips that volume's directories above it and every directory on its mount point's + /// path (`/System`, `/System/Volumes`), which are on the system volume. A containment the walks + /// meet is always real; an `Unrelated` stands where the other directory is none of what was + /// skipped (known by identity, or `Unsupported` where it cannot be read), and is on the mount + /// left, on another file system, or, where Linux's mountinfo shows it, beneath a part of the + /// file system that is not above the hidden subtree. + /// A file system that may show another's directories as its own -- overlay, any FUSE file + /// system, nullfs, unionfs, a network share -- decides only on its own mount: a walk that leaves + /// one, or a directory on one, is otherwise `Unsupported`, sshfs included. So is any of these + /// facts a system cannot read: macOS and the BSDs say nowhere which subtree a mount shows. + /// A walk up never meets a mount BENEATH either directory, which can put the other inside it + /// (a bind mount of a key directory under a granted one). So on POSIX an `Unrelated` also scans + /// the mount table: each mount point's path is followed from the root one component at a time, + /// never through a link, each component told apart by identity before it is entered and + /// entered only as that directory (a rename between the two is `Busy`); a mount point strictly + /// beneath either directory is opened, and the answer is `Unsupported` where it opens onto + /// another mount than the table's, is of the other directory's file system, or either may show + /// another's. The table is read again after the scan, and a difference is `Busy`. + /// Each walk is checked after it is done: on POSIX both are walked again, on Windows every + /// ancestor met is asked for its path again, and any change is `Busy`. A directory moved away and back + /// between the two passes (ABA) is not seen on POSIX; each chain still is one that existed. + /// **The answer is the layout when it was asked**: a mount made beneath either directory after + /// it is not seen, so a host asks at the moment it grants (Isoline's preopen grant, P14a, + /// evaluates the relation at grant time) and holds the grant to what it decided then. + /// + /// Both descriptors are read on the caller's thread, before the returned task first suspends; + /// neither needs to outlive the task. + /// @param first A directory of this file system. + /// @param second A directory of this file system. + /// @return How they relate; `NotDirectory` where either is not a directory; `CrossDevice` for a + /// descriptor of another file system (D11); `Unsupported` where the file system cannot + /// give stable identities or a mount of a subtree may hide one from the other (fail + /// closed); `Loop` past @c NativeFileSystemOptions::maxAncestorDepth parents; `Busy` + /// where a rename during the walk could have changed the answer; or what refused opening + /// a parent (`Access` on one the user may not search). + [[nodiscard]] virtual async::Task> relation(IDescriptor const& first, + IDescriptor const& second) = 0; }; } // namespace core::fs diff --git a/src/core/fs/DescriptorContract_test.cpp b/src/core/fs/DescriptorContract_test.cpp index e2263b55..a3abb94b 100644 --- a/src/core/fs/DescriptorContract_test.cpp +++ b/src/core/fs/DescriptorContract_test.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -22,7 +23,9 @@ #include #include #include +#include #include +#include #include #include @@ -990,6 +993,189 @@ TEST_CASE("contract: renameAt replaces an existing file atomically", "[fs][contr CHECK(textOf(fixture.run((*reader)->read(64, 0)).value().bytes) == "old"); } +namespace +{ + +using core::fs::Relation; + +/// Opens the directory @p path beneath @p fixture's root, following a final link where @p policy +/// says so; `.` is the root again. +[[nodiscard]] std::unique_ptr openDirectory(DescriptorFixture const& fixture, + std::string path, + SymlinkPolicy policy = SymlinkPolicy::NoFollow) +{ + auto opened = fixture.run( + fixture.root().openAt(policy, std::move(path), OpenFlags::Directory, DescriptorFlags::Read)); + REQUIRE(opened.has_value()); + return std::move(*opened); +} + +/// @return How @p first relates to @p second, or why not. +[[nodiscard]] FsResult relationOf(DescriptorFixture const& fixture, + IDescriptor const& first, + IDescriptor const& second) +{ + return fixture.run(fixture.fileSystem().relation(first, second)); +} + +/// Skips a case of the native relation under wine, which hands out paths by volume GUID +/// (`\\?\Volume{...}\`) that it cannot open again, and the path a handle was opened by after it +/// was renamed (tried with paths by drive letter instead); native Windows runs every one. +void skipNativeRelationUnderWine(FixtureKind kind) +{ + if (kind == FixtureKind::Native && core::fs::test::runsUnderWine()) + SKIP("wine cannot open the volume GUID paths its GetFinalPathNameByHandleW hands out, and names a " + "renamed handle by the path it was opened by"); +} + +/// Makes the directories of @p path beneath @p fixture's root, each one above it first. +void makeDirectories(DescriptorFixture const& fixture, std::string const& path) +{ + auto parent = std::string {}; + for (auto const piece: path | std::views::split('/')) + { + parent += (parent.empty() ? "" : "/") + std::string { std::string_view { piece } }; + auto const made = fixture.run(fixture.root().createDirectoryAt(parent, CreationAccess::Default)); + REQUIRE((made.has_value() || made.error().code == FsErrorCode::Exist)); + } +} + +} // namespace + +TEST_CASE("contract: relation decides on real parents", "[fs][contract][relation]") +{ + auto const kind = GENERATE(FixtureKind::InMemory, FixtureKind::Native); + skipNativeRelationUnderWine(kind); + auto fixture = DescriptorFixture::create(kind); + makeDirectories(fixture, "a/b"); + makeDirectories(fixture, "c"); + fixture.createFile("f", "a file"); + + struct Row + { + std::string first; + std::string second; + Relation expected = Relation::Unrelated; + }; + auto const row = GENERATE(Row { "a", "a", Relation::Same }, + Row { "a", "a/b", Relation::FirstContainsSecond }, + Row { "a/b", "a", Relation::SecondContainsFirst }, + Row { "a/b", "c", Relation::Unrelated }, + Row { ".", "a/b", Relation::FirstContainsSecond }, + Row { "a/b", ".", Relation::SecondContainsFirst }); + CAPTURE(row.first, row.second); + auto const first = openDirectory(fixture, row.first); + auto const second = openDirectory(fixture, row.second); + CHECK(relationOf(fixture, *first, *second) == row.expected); + + // A regular file as either is NotDirectory, whatever the other is. + auto file = fixture.run( + fixture.root().openAt(SymlinkPolicy::NoFollow, "f", OpenFlags::None, DescriptorFlags::Read)); + REQUIRE(file.has_value()); + CHECK(outcomeOf(relationOf(fixture, **file, *second)) == FsErrorCode::NotDirectory); + // A file with itself, too: the walk alone would find the file's parents by name on Windows, or + // its own identity Same, so the type is what refuses. + CHECK(outcomeOf(relationOf(fixture, **file, **file)) == FsErrorCode::NotDirectory); + CHECK(outcomeOf(relationOf(fixture, *first, **file)) == FsErrorCode::NotDirectory); +} + +TEST_CASE("contract: relation sees through a symlinked component", "[fs][contract][relation]") +{ + // The key-path bypass of the P14 review (C1): ~/.config is a link into /data/dotfiles, so the + // key directory lies beneath a grant of /data/dotfiles though no path says so. + auto const kind = GENERATE(FixtureKind::InMemory, FixtureKind::Native); + skipNativeRelationUnderWine(kind); + auto fixture = DescriptorFixture::create(kind); + if (fixture.requireSymlinks() == SymlinkSupport::Unavailable) + SKIP("this file system cannot create symbolic links"); + makeDirectories(fixture, "dotfiles/config/isoline"); + makeDirectories(fixture, "home"); + REQUIRE(fixture.run(fixture.root().symlinkAt("../dotfiles/config", "home/config")).has_value()); + auto const key = openDirectory(fixture, "home/config/isoline", SymlinkPolicy::Follow); + auto const dotfiles = openDirectory(fixture, "dotfiles"); + auto const home = openDirectory(fixture, "home"); + CHECK(relationOf(fixture, *dotfiles, *key) == Relation::FirstContainsSecond); + CHECK(relationOf(fixture, *key, *dotfiles) == Relation::SecondContainsFirst); + // What the opening path says is not what counts: home holds no part of it. + CHECK(relationOf(fixture, *home, *key) == Relation::Unrelated); +} + +TEST_CASE("contract: relation follows a rename after open", "[fs][contract][relation]") +{ + auto const kind = GENERATE(FixtureKind::InMemory, FixtureKind::Native); + skipNativeRelationUnderWine(kind); + auto fixture = DescriptorFixture::create(kind); + makeDirectories(fixture, "a/b"); + makeDirectories(fixture, "c"); + auto const a = openDirectory(fixture, "a"); + auto const b = openDirectory(fixture, "a/b"); + auto const c = openDirectory(fixture, "c"); + REQUIRE(relationOf(fixture, *a, *b) == Relation::FirstContainsSecond); + REQUIRE(fixture.run(fixture.root().renameAt("a/b", &fixture.root(), "c/b")).has_value()); + // The object's parents now, never the path it was opened by. + CHECK(relationOf(fixture, *a, *b) == Relation::Unrelated); + CHECK(relationOf(fixture, *c, *b) == Relation::FirstContainsSecond); +} + +TEST_CASE("contract: relation of a removed directory is NoEntry", "[fs][contract][relation]") +{ + // In the model: a removed directory has no parent, as a native `..` of it on POSIX finds none. + // Windows keeps a removed directory in its parent until its last handle is closed. + auto fixture = DescriptorFixture::createInMemory(); + makeDirectories(fixture, "a/b"); + auto const b = openDirectory(fixture, "a/b"); + REQUIRE(fixture.run(fixture.root().removeDirectoryAt("a/b")).has_value()); + CHECK(outcomeOf(relationOf(fixture, fixture.root(), *b)) == FsErrorCode::NoEntry); + CHECK(outcomeOf(relationOf(fixture, *b, fixture.root())) == FsErrorCode::NoEntry); +} + +TEST_CASE("contract: relation fails closed without identities", "[fs][contract][relation]") +{ + auto fixture = DescriptorFixture::createInMemory(core::fs::posixPathPolicy(), + core::fs::testing::IdentityModel::Unavailable); + makeDirectories(fixture, "a/b"); + auto const a = openDirectory(fixture, "a"); + auto const b = openDirectory(fixture, "a/b"); + CHECK(outcomeOf(relationOf(fixture, *a, *b)) == FsErrorCode::Unsupported); + CHECK(outcomeOf(relationOf(fixture, *a, *a)) == FsErrorCode::Unsupported); +} + +TEST_CASE("contract: relation refuses foreign descriptors", "[fs][contract][relation]") +{ + auto const kind = GENERATE(FixtureKind::InMemory, FixtureKind::Native); + auto fixture = DescriptorFixture::create(kind); + auto other = DescriptorFixture::create(kind); + makeDirectories(fixture, "a"); + auto const a = openDirectory(fixture, "a"); + CHECK(outcomeOf(relationOf(fixture, *a, other.root())) == FsErrorCode::CrossDevice); + CHECK(outcomeOf(relationOf(fixture, other.root(), *a)) == FsErrorCode::CrossDevice); + // The other file system refuses this one's, too. + CHECK(outcomeOf(relationOf(other, other.root(), *a)) == FsErrorCode::CrossDevice); +} + +TEST_CASE("contract: relation is bounded", "[fs][contract][relation]") +{ + auto const kind = GENERATE(FixtureKind::InMemory, FixtureKind::Native); + skipNativeRelationUnderWine(kind); + auto fixture = + DescriptorFixture::create(kind, core::fs::NativeFileSystemOptions { .maxAncestorDepth = 8 }); + makeDirectories(fixture, "d1/d2/d3/d4/d5/d6/d7/d8/d9"); + auto const deep = openDirectory(fixture, "d1/d2/d3/d4/d5/d6/d7/d8/d9"); + // Nine parents below the root before the root's own: past eight, whatever lies above the root. + CHECK(outcomeOf(relationOf(fixture, fixture.root(), *deep)) == FsErrorCode::Loop); + CHECK(outcomeOf(relationOf(fixture, *deep, fixture.root())) == FsErrorCode::Loop); + if (kind == FixtureKind::InMemory) + { + // Within the cap it decides: d5's parents are d4 to d1, the root and the model's root. + auto const shallow = openDirectory(fixture, "d1/d2/d3/d4/d5"); + CHECK(relationOf(fixture, fixture.root(), *shallow) == Relation::FirstContainsSecond); + } + auto unbounded = DescriptorFixture::create(kind); + makeDirectories(unbounded, "d1/d2/d3/d4/d5/d6/d7/d8/d9"); + auto const deepUnbounded = openDirectory(unbounded, "d1/d2/d3/d4/d5/d6/d7/d8/d9"); + CHECK(relationOf(unbounded, unbounded.root(), *deepUnbounded) == Relation::FirstContainsSecond); +} + TEST_CASE("contract: a directory's descriptor reads no bytes", "[fs][contract]") { // POSIX's pread answers EISDIR, Windows' ReadFile ERROR_INVALID_FUNCTION: both are IsDirectory. @@ -1001,3 +1187,16 @@ TEST_CASE("contract: a directory's descriptor reads no bytes", "[fs][contract]") REQUIRE(directory.has_value()); CHECK(outcomeOf(fixture.run((*directory)->read(16, 0))) == FsErrorCode::IsDirectory); } + +TEST_CASE("contract: a link whose target names a root is not read", "[fs][contract]") +{ + // A rooted target names nothing relative to the link: no walk follows it and no symlinkAt makes + // one, so readlinkAt refuses it too (WASI 0.3.2's not-permitted). One that climbs is relative. + auto fixture = DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native)); + if (fixture.requireSymlinks() == SymlinkSupport::Unavailable) + SKIP("this file system cannot create symbolic links"); + fixture.hostSymlink("abs", fixture.outsideAbsoluteTarget()); + REQUIRE(fixture.run(fixture.root().symlinkAt("../up", "climbs")).has_value()); + CHECK(outcomeOf(fixture.run(fixture.root().readlinkAt("abs"))) == FsErrorCode::NotPermitted); + CHECK(fixture.run(fixture.root().readlinkAt("climbs")).value() == "../up"); +} diff --git a/src/core/fs/DescriptorEscape_test.cpp b/src/core/fs/DescriptorEscape_test.cpp index eb128445..60a6c472 100644 --- a/src/core/fs/DescriptorEscape_test.cpp +++ b/src/core/fs/DescriptorEscape_test.cpp @@ -343,8 +343,12 @@ TEST_CASE("a directory swapped for an outward symlink mid-walk never yields a de auto refused = 0; { auto const swapper = fixture.startSwapper("d", "../"); - for (auto const round: std::views::iota(0, 2000)) // bounded by count, not by wall time + // Bounded by count, not by wall time: at least 2000 rounds, and on until the swapper has made + // its hundred swaps, which a slow runner (macOS CI: 78 in 2000) needs more rounds for. + for (auto const round: std::views::iota(0, 20'000)) { + if (round >= 2000 && swapper->swaps() > 100) + break; INFO(round); auto opened = fixture.run(fixture.root().openAt( SymlinkPolicy::Follow, "d/inside.txt", OpenFlags::None, DescriptorFlags::Read)); diff --git a/src/core/fs/DescriptorTestSupport.hpp b/src/core/fs/DescriptorTestSupport.hpp index 5530c17e..6a24cd39 100644 --- a/src/core/fs/DescriptorTestSupport.hpp +++ b/src/core/fs/DescriptorTestSupport.hpp @@ -255,11 +255,30 @@ class DescriptorFixture { if (kind == FixtureKind::Native) return createNative({ .policy = &policy }); + return createInMemory(policy); + } + + /// An in-memory file system under @p policy. + /// @param policy The name rules it applies. + /// @param identities Whether its `relation` can decide. + /// @param maxAncestorDepth How many parents its `relation` walks before `Loop`. + /// @return A fixture with its root descriptor open. + /// @throws std::runtime_error Where the root cannot be opened. + [[nodiscard]] static DescriptorFixture createInMemory( + PathPolicy const& policy = posixPathPolicy(), + testing::IdentityModel identities = testing::IdentityModel::Stable, + std::size_t maxAncestorDepth = DefaultMaxAncestorDepth) + { auto fixture = DescriptorFixture { FixtureKind::InMemory, DefaultSecretSeed }; fixture._outsideDirectory = std::filesystem::path { "/" }; fixture._hostDirectory = std::filesystem::path { "/root" }; - auto fileSystem = std::make_unique( - *fixture._home, *fixture._blocking, *fixture._clock, policy, MaxReadChunk); + auto fileSystem = std::make_unique(*fixture._home, + *fixture._blocking, + *fixture._clock, + policy, + MaxReadChunk, + identities, + maxAncestorDepth); fileSystem->addDirectory("root"); fixture._inMemory = fileSystem.get(); fixture._fileSystem = std::move(fileSystem); @@ -268,14 +287,15 @@ class DescriptorFixture } /// @param kind Which file system to build. - /// @param options What a native one is built with; an in-memory one takes none of them. + /// @param options What a native one is built with; an in-memory one takes only its + /// `maxAncestorDepth`. /// @return A fixture with its root descriptor open. /// @throws std::runtime_error Where the root cannot be opened. [[nodiscard]] static DescriptorFixture create(FixtureKind kind, NativeFileSystemOptions options) { if (kind == FixtureKind::Native) return createNative(options); - return create(kind, posixPathPolicy()); + return createInMemory(posixPathPolicy(), testing::IdentityModel::Stable, options.maxAncestorDepth); } /// A native file system over a temporary directory of its own. diff --git a/src/core/fs/NativeFileSystem.hpp b/src/core/fs/NativeFileSystem.hpp index 7724dc42..f501499f 100644 --- a/src/core/fs/NativeFileSystem.hpp +++ b/src/core/fs/NativeFileSystem.hpp @@ -23,6 +23,10 @@ namespace core::fs /// How many symbolic links one resolution follows before it answers `Loop`, as Linux's own limit. inline constexpr std::size_t DefaultMaxSymlinkHops = 40; +/// How many parents one @c IDescriptorFileSystem::relation walks from each directory before it +/// answers `Loop`: deeper than any real tree, low enough that a crafted one costs a bounded walk. +inline constexpr std::size_t DefaultMaxAncestorDepth = 4'096; + /// How a path is resolved beneath the descriptor it is relative to. enum class BeneathStrategy : std::uint8_t { @@ -44,6 +48,8 @@ struct NativeFileSystemOptions ///< caller asks for. PathPolicy const* policy = nullptr; ///< The name rules; null is @c nativePathPolicy(). Must ///< outlive the file system and its descriptors. + std::size_t maxAncestorDepth = DefaultMaxAncestorDepth; ///< Parents one relation() walks from each + ///< directory before it answers `Loop`. }; /// Builds the operating system's file system. @@ -85,6 +91,11 @@ struct NativeFileSystemOptions /// Before Windows 10 1803, which cannot refuse that reparse, such a point does not open at all. /// - Every open identifies the process to a server it reaches (a named pipe, a share) at most at /// identification level, so no server can impersonate it. +/// - `relation` reads each directory's final path by volume GUID and opens every ancestor on it, and +/// every folder its volume is mounted on, for its file id alone. Identities count only on a local +/// NTFS or ReFS volume: FAT, exFAT, any other file system and every share (whatever file system +/// the server reports) answer `Unsupported`. A rename that moved either directory or any ancestor +/// met during the walk answers `Busy`. /// /// @param home Where every operation resumes. Must outlive the file system and its descriptors. /// @param blocking Where every system call runs. Must outlive them too. diff --git a/src/core/fs/PathPolicy.cpp b/src/core/fs/PathPolicy.cpp index 30a49ba6..e8f940dd 100644 --- a/src/core/fs/PathPolicy.cpp +++ b/src/core/fs/PathPolicy.cpp @@ -64,4 +64,14 @@ PathPolicy const& windowsPathPolicy() noexcept return WindowsPolicy; } +bool isRootedLinkTarget(std::string_view target, PathPolicy const& policy) noexcept +{ + if (target.empty()) + return false; + if (policy.targetSeparators.contains(target.front())) + return true; + auto const firstComponent = target.substr(0, target.find_first_of(policy.targetSeparators)); + return firstComponent.find_first_of(policy.volumeSeparators) != std::string_view::npos; +} + } // namespace core::fs diff --git a/src/core/fs/PathPolicy.hpp b/src/core/fs/PathPolicy.hpp index e5c6cca0..7472417c 100644 --- a/src/core/fs/PathPolicy.hpp +++ b/src/core/fs/PathPolicy.hpp @@ -64,4 +64,16 @@ struct PathPolicy /// @return The rules of the operating system this was built for, chosen by the build. [[nodiscard]] CORE_FS_API PathPolicy const& nativePathPolicy() noexcept; +/// Whether a symbolic link's @p target names a root rather than a place relative to the link: it +/// starts with one of @p policy's target separators (`/etc`; under the Windows rules also `\x`, +/// `\\server\share` and `\\?\C:\`), or its first component holds one of its volume separators +/// (`C:`, `C:x`, `C:\x`). Under the POSIX rules `\x` and `C:x` are relative names. A relative target +/// that climbs out of a root (`../x`) is not rooted; resolution refuses it where it leaves. +/// Every link a walk follows and every `symlinkAt` asks this, so the rule has one definition. +/// A bool: the name asks the question. +/// @param target The link's target, as stored. +/// @param policy The name rules it is read under. +/// @return Whether it is rooted; an empty target is not. +[[nodiscard]] CORE_FS_API bool isRootedLinkTarget(std::string_view target, PathPolicy const& policy) noexcept; + } // namespace core::fs diff --git a/src/core/fs/PathPolicy_test.cpp b/src/core/fs/PathPolicy_test.cpp new file mode 100644 index 00000000..9063a2a1 --- /dev/null +++ b/src/core/fs/PathPolicy_test.cpp @@ -0,0 +1,82 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The name rules as queries: which symbolic-link targets name a root. One table per policy, both run +// on every OS, since the in-memory model runs either and a WASI host answers `readlink-at` from it. +#include +#include +#include + +#include +#include + +#include + +using core::fs::isRootedLinkTarget; +using core::fs::posixPathPolicy; +using core::fs::windowsPathPolicy; + +namespace +{ + +/// A target and whether it names a root. +struct Row +{ + std::string_view target; + bool rooted = false; +}; + +} // namespace + +TEST_CASE("isRootedLinkTarget follows the table", "[fs][pathpolicy]") +{ + SECTION("posix") + { + auto const row = GENERATE(Row { .target = "/etc", .rooted = true }, + Row { .target = "/", .rooted = true }, + Row { .target = "\\x", .rooted = false }, + Row { .target = "C:x", .rooted = false }, + Row { .target = "C:", .rooted = false }, + Row { .target = "a/b", .rooted = false }, + Row { .target = "../x", .rooted = false }, + Row { .target = "", .rooted = false }); + CAPTURE(row.target); + CHECK(isRootedLinkTarget(row.target, posixPathPolicy()) == row.rooted); + } + SECTION("windows") + { + auto const row = GENERATE(Row { .target = "\\x", .rooted = true }, + Row { .target = "/x", .rooted = true }, + Row { .target = "C:", .rooted = true }, + Row { .target = "C:x", .rooted = true }, + Row { .target = "C:\\x", .rooted = true }, + Row { .target = "\\\\server\\share", .rooted = true }, + Row { .target = "\\\\?\\C:\\", .rooted = true }, + Row { .target = "a\\b", .rooted = false }, + Row { .target = "a\\C:", .rooted = false }, + Row { .target = "..\\x", .rooted = false }, + Row { .target = "", .rooted = false }); + CAPTURE(row.target); + CHECK(isRootedLinkTarget(row.target, windowsPathPolicy()) == row.rooted); + } +} + +TEST_CASE("isRootedLinkTarget is what a followed link is refused by", "[fs][pathpolicy]") +{ + // The walk's splice asks the same rule: a rooted target is NotPermitted, a relative one splices. + auto const policy = GENERATE(&posixPathPolicy, &windowsPathPolicy); + for (auto const target: + { std::string_view { "/etc" }, std::string_view { "C:x" }, std::string_view { "a" } }) + { + CAPTURE(target); + auto plan = core::fs::detail::planRelativePath("link", policy()); + REQUIRE(plan.has_value()); + auto const spliced = core::fs::detail::spliceSymlink(*plan, 0, target, policy()); + if (isRootedLinkTarget(target, policy())) + { + REQUIRE_FALSE(spliced.has_value()); + CHECK(spliced.error().code == core::fs::FsErrorCode::NotPermitted); + } + else + CHECK(spliced.has_value()); + } +} diff --git a/src/core/fs/RelationMemory_test.cpp b/src/core/fs/RelationMemory_test.cpp new file mode 100644 index 00000000..28f35f77 --- /dev/null +++ b/src/core/fs/RelationMemory_test.cpp @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// What one IDescriptorFileSystem::relation holds while it walks: the parents it walked, never what +// maxAncestorDepth would allow. This binary replaces the global allocation functions to count the +// bytes alive, which is why it is a binary of its own: a replacement reaches every test linked +// beside it. +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + +/// What precedes each allocation: its size, and room to keep the storage after it aligned. +constexpr auto HeaderBytes = std::size_t { alignof(std::max_align_t) }; + +std::atomic liveBytes { 0 }; +std::atomic peakBytes { 0 }; + +} // namespace + +void* core::testing::replacedAllocate(std::size_t size) +{ + auto* const block = static_cast(std::malloc(HeaderBytes + size)); + if (block == nullptr) + throw std::bad_alloc {}; + std::memcpy(block, &size, sizeof(size)); + auto const live = liveBytes.fetch_add(size) + size; + auto peak = peakBytes.load(); + while (live > peak && !peakBytes.compare_exchange_weak(peak, live)) + { + } + return block + HeaderBytes; +} + +void core::testing::replacedRelease(void* storage) noexcept +{ + if (storage == nullptr) + return; + auto* const block = static_cast(storage) - HeaderBytes; + auto size = std::size_t { 0 }; + std::memcpy(&size, block, sizeof(size)); + liveBytes.fetch_sub(size); + std::free(block); +} + +TEST_CASE("relation holds the parents it walks, not the cap", "[fs][relation]") +{ + using core::fs::test::DescriptorFixture; + using core::fs::test::FixtureKind; + /// A cap whose reservation would show: 24 MiB of identities, where a walk of a few dozen + /// parents holds a few KiB. + constexpr auto MaxAncestorDepth = std::size_t { 1 } << 20U; + constexpr auto Budget = std::size_t { 64 } << 10U; + + auto fixture = + DescriptorFixture::create(GENERATE(FixtureKind::InMemory, FixtureKind::Native), + core::fs::NativeFileSystemOptions { .maxAncestorDepth = MaxAncestorDepth }); + auto path = std::string {}; + for (auto const name: { "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9" }) + { + path += (path.empty() ? "" : "/") + std::string { name }; + REQUIRE(fixture.run(fixture.root().createDirectoryAt(path, core::fs::CreationAccess::Default)) + .has_value()); + } + auto deep = fixture.run(fixture.root().openAt(core::fs::SymlinkPolicy::NoFollow, + path, + core::fs::OpenFlags::Directory, + core::fs::DescriptorFlags::Read)); + REQUIRE(deep.has_value()); + + auto const before = liveBytes.load(); + peakBytes.store(before); + auto const relation = fixture.run(fixture.fileSystem().relation(fixture.root(), **deep)); + auto const held = peakBytes.load() - before; + REQUIRE(relation.has_value()); + CHECK(*relation == core::fs::Relation::FirstContainsSecond); + CAPTURE(held); + CHECK(held < Budget); +} diff --git a/src/core/fs/Relation_test.cpp b/src/core/fs/Relation_test.cpp new file mode 100644 index 00000000..6f7e0464 --- /dev/null +++ b/src/core/fs/Relation_test.cpp @@ -0,0 +1,243 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// What the native relation answers while the tree it walks is renamed under it, on every OS: the +// identity of each parent counts, and a walk that a rename could have misled answers Busy (its +// chains walked again differ on POSIX, its final paths on Windows), never a wrong relation. +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using core::fs::DescriptorFlags; +using core::fs::FsErrorCode; +using core::fs::FsResult; +using core::fs::IDescriptor; +using core::fs::OpenFlags; +using core::fs::Relation; +using core::fs::SymlinkPolicy; +using core::fs::test::DescriptorFixture; + +namespace +{ + +/// A thread that makes a cycle of renames in the host's file system over and over, until it is +/// destroyed, and counts the cycles in which every rename succeeded. Test-only, so it may own a +/// thread. +class Renamer +{ + public: + /// One rename of a cycle. + struct Step + { + std::filesystem::path from; + std::filesystem::path to; + }; + + /// @param cycle The renames, made in this order; after the last, the tree is as it was. + /// @param pause How long each rename's result stands before the next is made: zero renames as + /// fast as the system can, and a pause gives a slow walk a tree that holds still between. + Renamer(std::vector cycle, std::chrono::microseconds pause): _state { std::make_unique() } + { + _thread = std::thread { [state = _state.get(), cycle = std::move(cycle), pause] { + while (!state->stop.load()) + { + auto completed = true; + for (auto const& step: cycle) + { + auto error = std::error_code {}; + std::filesystem::rename(step.from, step.to, error); + completed = completed && !error; + if (pause.count() > 0) + std::this_thread::sleep_for(pause); + } + if (completed) + state->exchanges.fetch_add(1); + } + } }; + } + + Renamer(Renamer const&) = delete; + Renamer(Renamer&&) = delete; + Renamer& operator=(Renamer const&) = delete; + Renamer& operator=(Renamer&&) = delete; + + ~Renamer() + { + _state->stop.store(true); + _thread.join(); + } + + /// Waits, bounded, for the first cycle in which every rename succeeded. + /// @return Whether one did. + [[nodiscard]] bool started() const + { + auto const deadline = std::chrono::steady_clock::now() + std::chrono::seconds { 10 }; + while (exchanges() == 0 && std::chrono::steady_clock::now() < deadline) + std::this_thread::yield(); + return exchanges() > 0; + } + + /// @return How many cycles have completed with every rename made. + [[nodiscard]] std::size_t exchanges() const noexcept { return _state->exchanges.load(); } + + private: + struct State + { + std::atomic stop { false }; + std::atomic exchanges { 0 }; + }; + + std::unique_ptr _state; + std::thread _thread; +}; + +[[nodiscard]] std::unique_ptr openDirectory(DescriptorFixture const& fixture, std::string path) +{ + auto opened = fixture.run(fixture.root().openAt( + SymlinkPolicy::NoFollow, std::move(path), OpenFlags::Directory, DescriptorFlags::Read)); + REQUIRE(opened.has_value()); + return std::move(*opened); +} + +/// @return Whether @p answer is @p expected, or Busy, the one refusal a walk by name may give when a +/// rename could have changed it. +[[nodiscard]] bool isExpectedOrBusy(FsResult const& answer, Relation expected) +{ + if (answer) + return *answer == expected; + return answer.error().code == FsErrorCode::Busy; +} + +/// @return What @p answer is, for a case to name what it did not expect. +[[nodiscard]] std::string describe(FsResult const& answer) +{ + if (!answer) + return answer.error().toString(); + constexpr auto Names = + std::array { "Same", "FirstContainsSecond", "SecondContainsFirst", "Unrelated" }; + return Names.at(static_cast(*answer)); +} + +} // namespace + +TEST_CASE("relation under a swap between check and use", "[fs][native][relation][threading]") +{ + // p and c trade names beneath the root: each stays beneath the root and beside the other, + // whatever name it has. The renamed directories are the opened ones, with nothing open beneath + // them, because Windows renames no directory that has a handle open beneath it. + if (core::fs::test::runsUnderWine()) + SKIP("wine cannot open the volume GUID paths its GetFinalPathNameByHandleW hands out, and names a " + "renamed handle by the path it was opened by"); + auto fixture = DescriptorFixture::createNative(); + std::filesystem::create_directories(fixture.hostDirectory() / "p" / "q"); + std::filesystem::create_directories(fixture.hostDirectory() / "c"); + auto const p = openDirectory(fixture, "p"); + auto const c = openDirectory(fixture, "c"); + + auto const& host = fixture.hostDirectory(); + auto const exchanger = Renamer { { { .from = host / "p", .to = host / "parked" }, + { .from = host / "c", .to = host / "p" }, + { .from = host / "parked", .to = host / "c" } }, + std::chrono::microseconds { 0 } }; + REQUIRE(exchanger.started()); + auto const before = exchanger.exchanges(); + + auto wrong = std::size_t { 0 }; + auto firstWrong = std::string {}; + for ([[maybe_unused]] auto const round: std::views::iota(0, 300)) + { + auto const rootP = fixture.run(fixture.fileSystem().relation(fixture.root(), *p)); + auto const cRoot = fixture.run(fixture.fileSystem().relation(*c, fixture.root())); + auto const pC = fixture.run(fixture.fileSystem().relation(*p, *c)); + if (!isExpectedOrBusy(rootP, Relation::FirstContainsSecond) + || !isExpectedOrBusy(cRoot, Relation::SecondContainsFirst) + || !isExpectedOrBusy(pC, Relation::Unrelated)) + { + if (wrong == 0) + firstWrong = + "root,p: " + describe(rootP) + "; c,root: " + describe(cRoot) + "; p,c: " + describe(pC); + ++wrong; + } + } + INFO("the first unexpected round: " << firstWrong); + CHECK(wrong == 0); + // The renames went on while the relations were walked. + CHECK(exchanger.exchanges() > before); +} + +TEST_CASE("relation under a move to another parent", "[fs][native][relation][threading]") +{ + // a moves between x and y while relations are walked: beneath the root it always is, beneath z + // never, and beneath x or y as it was at some instant -- never in a chain of parents no tree held. + // a is the opened directory itself: Windows moves no directory with a handle open beneath it. + if (core::fs::test::runsUnderWine()) + SKIP("wine cannot open the volume GUID paths its GetFinalPathNameByHandleW hands out, and names a " + "renamed handle by the path it was opened by"); + auto fixture = DescriptorFixture::createNative(); + auto const& host = fixture.hostDirectory(); + std::filesystem::create_directories(host / "x" / "a"); + std::filesystem::create_directories(host / "y"); + std::filesystem::create_directories(host / "z"); + auto const x = openDirectory(fixture, "x"); + auto const y = openDirectory(fixture, "y"); + auto const z = openDirectory(fixture, "z"); + auto const a = openDirectory(fixture, "x/a"); + + // Each move stands a few milliseconds: long enough for a walk by name (Windows) to see a still + // tree between moves, short enough that the walks still meet the moves. + auto const mover = Renamer { { { .from = host / "x" / "a", .to = host / "y" / "a" }, + { .from = host / "y" / "a", .to = host / "x" / "a" } }, + std::chrono::milliseconds { 3 } }; + REQUIRE(mover.started()); + auto const before = mover.exchanges(); + + auto wrong = std::size_t { 0 }; + auto firstWrong = std::string {}; + auto beneathY = std::size_t { 0 }; + // Bounded by count, not by wall time: at least 300 rounds, and on until a walk has found a + // beneath y, where it was never opened. + for (auto const round: std::views::iota(0, 20000)) + { + if (round >= 300 && beneathY > 0) + break; + auto const fromRoot = fixture.run(fixture.fileSystem().relation(fixture.root(), *a)); + auto const fromZ = fixture.run(fixture.fileSystem().relation(*z, *a)); + auto const fromX = fixture.run(fixture.fileSystem().relation(*x, *a)); + auto const fromY = fixture.run(fixture.fileSystem().relation(*y, *a)); + if (!isExpectedOrBusy(fromRoot, Relation::FirstContainsSecond) + || !isExpectedOrBusy(fromZ, Relation::Unrelated) + || !(isExpectedOrBusy(fromX, Relation::FirstContainsSecond) + || isExpectedOrBusy(fromX, Relation::Unrelated)) + || !(isExpectedOrBusy(fromY, Relation::FirstContainsSecond) + || isExpectedOrBusy(fromY, Relation::Unrelated))) + { + if (wrong == 0) + firstWrong = "root: " + describe(fromRoot) + "; z: " + describe(fromZ) + + "; x: " + describe(fromX) + "; y: " + describe(fromY); + ++wrong; + } + if (fromY && *fromY == Relation::FirstContainsSecond) + ++beneathY; + } + INFO("the first unexpected round: " << firstWrong); + CHECK(wrong == 0); + CHECK(mover.exchanges() > before); + // a was opened beneath x: a walk that found it beneath y followed it to where it is now, which + // is what shows the walks ran while it moved and named its parent of that instant. + CHECK(beneathY > 0); +} diff --git a/src/core/fs/bsd/MountBoundaries.cpp b/src/core/fs/bsd/MountBoundaries.cpp new file mode 100644 index 00000000..e2b58072 --- /dev/null +++ b/src/core/fs/bsd/MountBoundaries.cpp @@ -0,0 +1,164 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// Mount boundaries on macOS and the BSDs. fstatfs names the mount each directory is on: where it is +// mounted (f_mntonname) and its file system id. These systems say nowhere which directory of its +// file system a mount shows, so every mount left is taken to show a subtree, and an `Unrelated` +// stands only where the other directory is on that same mount or on another file system +// (posix/MountBoundaries.hpp). The file system is the directory's `st_dev`; a type that may show +// another file system's directories as its own (nullfs, unionfs, FUSE, a network share) is marked +// so, and only the same mount decides there. Whether a step leaves from the mount's root, and what +// it skipped where not, is bsd/MountExit.hpp's to say: below it on a macOS firmlink. The mount +// table, for the mounts beneath a directory, is getfsstat's. +#include + +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace core::fs::detail +{ + +namespace +{ + + /// The file system types that may show another file system's directories as their own: a null + /// or union mount, which also shows them under an id of its own; any FUSE file system (macFUSE, + /// fuse-t, bindfs, sshfs); and a network share, which may be a loopback export of this machine + /// (fuse-t is one: it reports `nfs`). + constexpr auto ReexposingTypes = std::to_array({ + { .name = "nullfs", .match = TypeMatch::Exact }, + { .name = "unionfs", .match = TypeMatch::Exact }, + { .name = "fuse", .match = TypeMatch::Family }, + { .name = "macfuse", .match = TypeMatch::Exact }, + { .name = "osxfuse", .match = TypeMatch::Exact }, + { .name = "bindfs", .match = TypeMatch::Exact }, + { .name = "nfs", .match = TypeMatch::Family }, + { .name = "smbfs", .match = TypeMatch::Exact }, + { .name = "afpfs", .match = TypeMatch::Exact }, + { .name = "webdav", .match = TypeMatch::Exact }, + }); + + /// @return The mount @p handle is on. + [[nodiscard]] FsResult statfsOf(int handle) + { + struct ::statfs status {}; + if (::fstatfs(handle, &status) != 0) + return errnoError("fstatfs"); + return status; + } + + /// @return A name for the mount @p status describes: where it is mounted, and its id, so a mount + /// made over another at one place is not taken for it. + [[nodiscard]] std::string mountNameOf(struct ::statfs const& status) + { + return std::format("{}:{}:{}", + static_cast(status.f_fsid.val[0]), + static_cast(status.f_fsid.val[1]), + std::string_view { status.f_mntonname }); + } + + class BsdMountBoundaries final: public IMountBoundaries + { + public: + [[nodiscard]] FsResult> crossing(int child, int parent) const override + { + auto const childMount = statfsOf(child); + if (!childMount) + return std::unexpected { childMount.error() }; + auto const parentMount = statfsOf(parent); + if (!parentMount) + return std::unexpected { parentMount.error() }; + if (mountNameOf(*childMount) == mountNameOf(*parentMount)) + return std::nullopt; + return viewOf(child, *childMount).transform([&](MountView view) { + return std::optional { crossingFrom(child, *childMount, std::move(view)) }; + }); + } + + [[nodiscard]] FsResult mountOf(int handle) const override + { + return statfsOf(handle).and_then( + [&](struct ::statfs const& status) { return viewOf(handle, status); }); + } + + [[nodiscard]] FsResult> mountTable() const override + { + // getfsstat rather than getmntinfo, whose buffer is shared by every thread. The count is + // asked first, and the table read again where a mount arrived in between: a buffer that + // came back full may have dropped one, and nothing may be missing. + for ([[maybe_unused]] auto const attempt: std::views::iota(0, MaxTableReads)) + { + auto const counted = ::getfsstat(nullptr, 0, MNT_NOWAIT); + if (counted < 0) + return errnoError("getfsstat"); + auto mounts = std::vector(static_cast(counted) + SpareRows); + auto const read = ::getfsstat(mounts.data(), byteSizeOf(mounts), MNT_NOWAIT); + if (read < 0) + return errnoError("getfsstat"); + if (static_cast(read) == mounts.size()) + continue; + mounts.resize(static_cast(read)); + auto rows = std::vector {}; + rows.reserve(mounts.size()); + for (auto const& mount: mounts) + rows.push_back(MountTableRow { .path = std::string { mount.f_mntonname }, + .mount = mountNameOf(mount) }); + return rows; + } + return std::unexpected { FsError { .code = FsErrorCode::Busy, + .systemCode = 0, + .context = + "the mount table kept growing while it was read" } }; + } + + private: + /// How many times the table is read before a table that keeps growing is refused. + static constexpr auto MaxTableReads = 4; + /// Rows beyond the count asked for, so a mount made in between is seen as a full buffer. + static constexpr auto SpareRows = std::size_t { 8 }; + + /// @return @p mounts' size in bytes, as getfsstat takes it: an `int`, which macOS's parameter + /// is and FreeBSD's `long` widens from; a mount table is far below either's limit. + [[nodiscard]] static int byteSizeOf(std::vector const& mounts) noexcept + { + return static_cast(mounts.size() * sizeof(struct ::statfs)); + } + + private: + [[nodiscard]] static FsResult viewOf(int handle, struct ::statfs const& mount) + { + struct ::stat status {}; + if (::fstat(handle, &status) != 0) + return errnoError("fstat"); + return MountView { .mount = mountNameOf(mount), + .fileSystem = static_cast(status.st_dev), + .root = std::nullopt, + .reexposure = + reexposureOf(ReexposingTypes, std::string_view { mount.f_fstypename }) }; + } + }; + +} // namespace + +std::shared_ptr makeMountBoundaries() +{ + return std::make_shared(); +} + +} // namespace core::fs::detail diff --git a/src/core/fs/bsd/MountExit.cpp b/src/core/fs/bsd/MountExit.cpp new file mode 100644 index 00000000..b5ec04e9 --- /dev/null +++ b/src/core/fs/bsd/MountExit.cpp @@ -0,0 +1,21 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// Mount exits on the BSDs but macOS: their `..` leaves a mount only at its root (the lookup crosses +// to the covered directory only from a vnode flagged as its mount's root), so every step that +// changes mount leaves from the root and skips nothing but what the mount's root column would name. +// macOS has firmlinks, which do not: darwin/MountExit.cpp. +#include + +#include + +namespace core::fs::detail +{ + +MountCrossing crossingFrom(int /*child*/, struct ::statfs const& /*mount*/, MountView view) +{ + return MountCrossing { + .mount = std::move(view), .exit = MountExit::AtRoot, .skipped = {}, .skippedSet = SkippedSet::Unknown + }; +} + +} // namespace core::fs::detail diff --git a/src/core/fs/bsd/MountExit.hpp b/src/core/fs/bsd/MountExit.hpp new file mode 100644 index 00000000..d7d26f1e --- /dev/null +++ b/src/core/fs/bsd/MountExit.hpp @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// Where a relation walk on macOS or a BSD leaves a mount, and what that step skipped: one +/// implementation per OS, chosen by CMake (`darwin/MountExit.cpp`, `bsd/MountExit.cpp`). Private to +/// the fs module. + +#include + +#include +#include + +namespace core::fs::detail +{ + +/// @param child A directory whose `..` is on another mount. +/// @param mount The mount it is on (fstatfs). +/// @param view What the walk knows of that mount. +/// @return The crossing: `AtRoot` only where @p child is known to be @p mount's root; below it, the +/// directories the step skipped, as far as they can be read (posix/MountBoundaries.hpp). +[[nodiscard]] MountCrossing crossingFrom(int child, struct ::statfs const& mount, MountView view); + +} // namespace core::fs::detail diff --git a/src/core/fs/bsd/Relation_test.cpp b/src/core/fs/bsd/Relation_test.cpp new file mode 100644 index 00000000..2ba581fb --- /dev/null +++ b/src/core/fs/bsd/Relation_test.cpp @@ -0,0 +1,93 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The native relation on FreeBSD with mounts beneath a grant. A walk up from either directory never +// sees a mount beneath the other, so relation() scans the mount table: a nullfs mount beneath the +// grant that shows the key's file system puts the key inside the grant though neither walk meets the +// other, and is Unsupported; a tmpfs beneath it shows nothing of the key's, and the answer stands. +// Mounting needs root, which FreeBSD's CI VM has; elsewhere the case skips. +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +using core::fs::DescriptorFlags; +using core::fs::FsErrorCode; +using core::fs::Relation; +using core::fs::test::DescriptorFixture; + +namespace +{ + +/// Unmounts what a case mounted when it goes, last first, whatever the case did. +class Mounts +{ + public: + Mounts() = default; + Mounts(Mounts const&) = delete; + Mounts& operator=(Mounts const&) = delete; + Mounts(Mounts&&) = delete; + Mounts& operator=(Mounts&&) = delete; + ~Mounts() + { + for (auto const& point: _points | std::views::reverse) + std::ignore = std::system(("umount -f '" + point + "' 2>/dev/null").c_str()); + } + + /// Runs `mount -t @p type @p source @p point`. + /// @return Whether it mounted. + [[nodiscard]] bool mount(char const* type, std::string const& source, std::string const& point) + { + if (std::system(("mount -t " + std::string { type } + " '" + source + "' '" + point + "' 2>/dev/null") + .c_str()) + != 0) + return false; + _points.push_back(point); + return true; + } + + private: + std::vector _points; +}; + +} // namespace + +TEST_CASE("relation with mounts beneath a grant on FreeBSD", "[fs][native][relation]") +{ + auto fixture = DescriptorFixture::createNative(); + auto const& host = fixture.hostDirectory(); + for (auto const* directory: { "g/inner", "k/secret", "h/tm", "c" }) + std::filesystem::create_directories(host / directory); + auto mounts = Mounts {}; + if (!mounts.mount("nullfs", (host / "k").string(), (host / "g" / "inner").string()) + || !mounts.mount("tmpfs", "tmpfs", (host / "h" / "tm").string())) + SKIP("no nullfs and tmpfs mounts here (they need root)"); + + auto& system = fixture.fileSystem(); + auto const open = [&](std::filesystem::path const& path) { + auto opened = fixture.run(system.openPreopen(path, DescriptorFlags::Read)); + REQUIRE(opened.has_value()); + return std::move(*opened); + }; + auto const grant = open(host / "g"); + auto const key = open(host / "k" / "secret"); + for (auto const& answer: + { fixture.run(system.relation(*grant, *key)), fixture.run(system.relation(*key, *grant)) }) + { + REQUIRE_FALSE(answer.has_value()); + CHECK(answer.error().code == FsErrorCode::Unsupported); + } + auto const beside = open(host / "h"); + auto const other = open(host / "c"); + auto const unrelated = fixture.run(system.relation(*beside, *other)); + INFO((unrelated ? std::string { "decided" } : unrelated.error().toString())); + CHECK((unrelated && *unrelated == Relation::Unrelated)); +} diff --git a/src/core/fs/darwin/MountExit.cpp b/src/core/fs/darwin/MountExit.cpp new file mode 100644 index 00000000..8c2c4c46 --- /dev/null +++ b/src/core/fs/darwin/MountExit.cpp @@ -0,0 +1,169 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// Mount exits on macOS, where a firmlink (`/Users`, `/private`, ... on the Data volume) has a `..` +// on the system volume: a walk leaves the Data volume there, below its root, and skips the Data +// volume's directories above the firmlink and every directory on its mount point's path +// (`/System`, `/System/Volumes`, `/System/Volumes/Data`). +// +// A directory is its mount's root where its identity is that of what the mount's own path names: +// stat of f_mntonname resolves to the root of the mount on top there, never to a covered directory +// and never to a directory below a root. ATTR_DIR_MOUNTSTATUS is asked first: xnu sets +// DIR_MNTSTATUS_MNTPOINT for a mount's root vnode or a covered one (vfs_attrlist.c), so a +// directory it does not flag is below its root without a path being looked at. +// +// Below the root, the skipped directories are read from the root handle down the mount point's +// path, one component at a time with O_NOFOLLOW, each by identity; the mount's root is the last. +// Where the directory left from is a child of that root -- its name (F_GETPATH) opened beneath the +// root has its identity -- that is all the step skipped (Exactly); otherwise the mount's own +// directories between are unknown (AtLeast). Anything unreadable is Unknown (fail closed). +#include + +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace core::fs::detail +{ + +namespace +{ + + constexpr int DirectoryOpenFlags = O_RDONLY | O_NONBLOCK | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC; + + /// What fgetattrlist returns for ATTR_DIR_MOUNTSTATUS alone. + struct MountStatusReply + { + std::uint32_t length = 0; + std::uint32_t status = 0; + }; + + [[nodiscard]] bool isFlaggedMountPoint(int handle) + { + auto request = attrlist {}; + request.bitmapcount = ATTR_BIT_MAP_COUNT; + request.dirattr = ATTR_DIR_MOUNTSTATUS; + auto reply = MountStatusReply {}; + if (::fgetattrlist(handle, &request, &reply, sizeof(reply), 0) != 0) + return false; + return (reply.status & DIR_MNTSTATUS_MNTPOINT) != 0; + } + + [[nodiscard]] std::optional identityOf(int handle) + { + struct ::stat status {}; + if (::fstat(handle, &status) != 0) + return std::nullopt; + return ObjectIdentity { .device = static_cast(status.st_dev), + .idLow = static_cast(status.st_ino), + .idHigh = 0 }; + } + + [[nodiscard]] bool isWhatTheMountPathNames(ObjectIdentity const& child, struct ::statfs const& mount) + { + struct ::stat named {}; + if (::stat(mount.f_mntonname, &named) != 0) + return false; + return child.device == static_cast(named.st_dev) + && child.idLow == static_cast(named.st_ino); + } + + /// The directories on a mount point's path below `/`, and a handle on the last of them. + struct MountPath + { + std::vector directories; + UniqueHandle root; + }; + + /// @return Each directory on @p mountPoint below `/`, opened from the root one component at a + /// time without following a link; nullopt where one cannot be. + [[nodiscard]] std::optional mountPathOf(std::string_view mountPoint) + { + if (!mountPoint.starts_with('/')) + return std::nullopt; + auto current = UniqueHandle { retryOnInterrupt([] { return ::open("/", DirectoryOpenFlags); }) }; + if (current.get() == platform::InvalidHandle) + return std::nullopt; + auto path = MountPath { .directories = {}, .root = UniqueHandle { platform::InvalidHandle } }; + for (auto const componentRange: mountPoint | std::views::split('/')) + { + auto const component = std::string { std::string_view { componentRange } }; + if (component.empty()) + continue; + if (component == "." || component == "..") + return std::nullopt; + auto next = UniqueHandle { retryOnInterrupt( + [&] { return ::openat(current.get(), component.c_str(), DirectoryOpenFlags); }) }; + if (next.get() == platform::InvalidHandle) + return std::nullopt; + auto const identity = identityOf(next.get()); + if (!identity) + return std::nullopt; + path.directories.push_back(*identity); + current = std::move(next); + } + if (path.directories.empty()) + return std::nullopt; + path.root = std::move(current); + return path; + } + + /// @return Whether @p child, @p identity, is a child of @p root: its own name opened beneath + /// @p root has its identity. + [[nodiscard]] bool isChildOf(int root, int child, ObjectIdentity const& identity) + { + auto path = std::array {}; + if (::fcntl(child, F_GETPATH, path.data()) == -1) + return false; + auto const full = std::string_view { path.data() }; + auto const slash = full.rfind('/'); + if (slash == std::string_view::npos || slash + 1 == full.size()) + return false; + auto const name = std::string { full.substr(slash + 1) }; + auto const opened = UniqueHandle { retryOnInterrupt( + [&] { return ::openat(root, name.c_str(), DirectoryOpenFlags); }) }; + if (opened.get() == platform::InvalidHandle) + return false; + return identityOf(opened.get()) == identity; + } + +} // namespace + +MountCrossing crossingFrom(int child, struct ::statfs const& mount, MountView view) +{ + auto crossing = MountCrossing { .mount = std::move(view), + .exit = MountExit::BelowRoot, + .skipped = {}, + .skippedSet = SkippedSet::Unknown }; + auto const self = identityOf(child); + if (!self) + return crossing; + if (isFlaggedMountPoint(child) && isWhatTheMountPathNames(*self, mount)) + { + crossing.exit = MountExit::AtRoot; + return crossing; + } + auto path = mountPathOf(std::string_view { mount.f_mntonname }); + if (!path) + return crossing; + crossing.skippedSet = + isChildOf(path->root.get(), child, *self) ? SkippedSet::Exactly : SkippedSet::AtLeast; + crossing.skipped = std::move(path->directories); + return crossing; +} + +} // namespace core::fs::detail diff --git a/src/core/fs/darwin/Relation_test.cpp b/src/core/fs/darwin/Relation_test.cpp new file mode 100644 index 00000000..aa3d8e6e --- /dev/null +++ b/src/core/fs/darwin/Relation_test.cpp @@ -0,0 +1,157 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The native relation across macOS's own volumes. The home directory lies on the Data volume, +// mounted at /System/Volumes/Data, but a walk up from it meets /Users, a firmlink whose `..` is the +// system volume's root: it leaves the Data volume below that volume's root, and never meets it. So +// the Data volume's root, which does contain the home directory, must never be answered Unrelated, +// and nor must /System/Volumes and /System, which hold the Data volume's mount point and lie on the +// system volume, another device. Two directories beneath the home directory, whose walks both pass +// /Users, are still decided, and so is /private/tmp, beside /Users on the Data volume. +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +#include + +using core::fs::DescriptorFlags; +using core::fs::Relation; +using core::fs::test::DescriptorFixture; + +namespace +{ + +/// Removes a directory tree when it goes, whatever the case did. +class Cleanup +{ + public: + explicit Cleanup(std::filesystem::path path): _path { std::move(path) } {} + Cleanup(Cleanup const&) = delete; + Cleanup& operator=(Cleanup const&) = delete; + Cleanup(Cleanup&&) = delete; + Cleanup& operator=(Cleanup&&) = delete; + ~Cleanup() + { + auto error = std::error_code {}; + std::filesystem::remove_all(_path, error); + } + + private: + std::filesystem::path _path; +}; + +} // namespace + +TEST_CASE("relation across a firmlink", "[fs][native][relation]") +{ + // Every macOS from 10.15 on has the Data volume, and every runner a home directory: a case that + // skipped here would pass unseen, so both are required. + auto const home = core::LiveEnvironment {}.get("HOME"); + auto const data = std::filesystem::path { "/System/Volumes/Data" }; + REQUIRE((home && !home->empty())); + REQUIRE(std::filesystem::is_directory(data)); + auto fixture = DescriptorFixture::createNative(); + auto& system = fixture.fileSystem(); + auto const homeDirectory = std::filesystem::path { *home }; + auto const below = homeDirectory / ("core-cpp-relation-" + std::to_string(::getpid())); + std::filesystem::create_directories(below / "a"); + std::filesystem::create_directories(below / "b"); + auto const cleanup = Cleanup { below }; + + auto const open = [&](std::filesystem::path const& path) { + auto opened = fixture.run(system.openPreopen(path, DescriptorFlags::Read)); + REQUIRE(opened.has_value()); + return std::move(*opened); + }; + auto const dataRoot = open(data); + auto const homeHandle = open(homeDirectory); + auto const a = open(below / "a"); + auto const b = open(below / "b"); + + auto const fromData = fixture.run(system.relation(*dataRoot, *homeHandle)); + INFO((fromData ? std::string { "decided" } : fromData.error().toString())); + CHECK_FALSE((fromData && *fromData == Relation::Unrelated)); + auto const fromHome = fixture.run(system.relation(*homeHandle, *dataRoot)); + CHECK_FALSE((fromHome && *fromHome == Relation::Unrelated)); + + auto const aB = fixture.run(system.relation(*a, *b)); + INFO((aB ? std::string { "decided" } : aB.error().toString())); + CHECK((aB && *aB == Relation::Unrelated)); + auto const homeA = fixture.run(system.relation(*homeHandle, *a)); + CHECK((homeA && *homeA == Relation::FirstContainsSecond)); + + // The mount point's path, on the system volume: skipped by the walk from a, so never Unrelated. + for (auto const* ancestor: { "/System/Volumes", "/System" }) + { + INFO(ancestor); + auto const grant = open(ancestor); + auto const fromGrant = fixture.run(system.relation(*grant, *a)); + INFO((fromGrant ? std::string { "decided" } : fromGrant.error().toString())); + CHECK_FALSE((fromGrant && *fromGrant == Relation::Unrelated)); + auto const fromKey = fixture.run(system.relation(*a, *grant)); + CHECK_FALSE((fromKey && *fromKey == Relation::Unrelated)); + } + // A directory beside the firmlink, on the Data volume: none of what was skipped, so decided. + auto const temporary = open("/private/tmp"); + auto const tmpA = fixture.run(system.relation(*temporary, *a)); + INFO((tmpA ? std::string { "decided" } : tmpA.error().toString())); + CHECK((tmpA && *tmpA == Relation::Unrelated)); + auto const aTmp = fixture.run(system.relation(*a, *temporary)); + CHECK((aTmp && *aTmp == Relation::Unrelated)); +} + +TEST_CASE("relation with a disk image mounted beneath a grant", "[fs][native][relation]") +{ + // A walk up from either directory never sees a mount beneath the other, so relation() scans + // the mount table for one. A disk image of its own file system beneath the grant shows nothing of + // the key's: the answer stays Unrelated, and the scan is not a refusal of every grant that has a + // mount beneath it. (No bind mount exists here to show the key's file system beneath it; the + // Linux namespace rows and the FreeBSD nullfs rows prove that refusal.) + auto const temporary = + std::filesystem::path { "/private/tmp" } / ("core-cpp-mount-" + std::to_string(::getpid())); + std::filesystem::create_directories(temporary / "grant" / "volume"); + std::filesystem::create_directories(temporary / "key"); + auto const cleanup = Cleanup { temporary }; + auto const image = temporary / "image.dmg"; + auto const mountPoint = temporary / "grant" / "volume"; + auto const create = + "hdiutil create -quiet -size 2m -fs HFS+ -volname core-cpp -layout NONE '" + image.string() + "'"; + auto const attach = "hdiutil attach -quiet -nobrowse -noautoopen -mountpoint '" + mountPoint.string() + + "' '" + image.string() + "'"; + if (std::system(create.c_str()) != 0 || std::system(attach.c_str()) != 0) + SKIP("hdiutil cannot make or attach a disk image here"); + struct Detach + { + explicit Detach(std::string text): command { std::move(text) } {} + std::string command; + Detach(Detach const&) = delete; + Detach& operator=(Detach const&) = delete; + Detach(Detach&&) = delete; + Detach& operator=(Detach&&) = delete; + ~Detach() { std::ignore = std::system(command.c_str()); } + } const detach { "hdiutil detach -quiet -force '" + mountPoint.string() + "'" }; + + auto fixture = DescriptorFixture::createNative(); + auto& system = fixture.fileSystem(); + auto const open = [&](std::filesystem::path const& path) { + auto opened = fixture.run(system.openPreopen(path, DescriptorFlags::Read)); + REQUIRE(opened.has_value()); + return std::move(*opened); + }; + auto const grant = open(temporary / "grant"); + auto const key = open(temporary / "key"); + auto const fromGrant = fixture.run(system.relation(*grant, *key)); + INFO((fromGrant ? std::string { "decided" } : fromGrant.error().toString())); + CHECK((fromGrant && *fromGrant == Relation::Unrelated)); + auto const fromKey = fixture.run(system.relation(*key, *grant)); + CHECK((fromKey && *fromKey == Relation::Unrelated)); +} diff --git a/src/core/fs/detail/Ancestry.cpp b/src/core/fs/detail/Ancestry.cpp new file mode 100644 index 00000000..72030e31 --- /dev/null +++ b/src/core/fs/detail/Ancestry.cpp @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: Apache-2.0 +#include + +#include + +#include +#include + +namespace core::fs::detail +{ + +namespace +{ + + [[nodiscard]] bool holds(std::span ancestors, + ObjectIdentity const& identity) noexcept + { + // find_if, not find: the MSVC STL hands find over a 24-byte trivially comparable type to a + // vectorized search that refuses its size at compile time. + return std::ranges::find_if(ancestors, + [&](ObjectIdentity const& ancestor) { return ancestor == identity; }) + != ancestors.end(); + } + +} // namespace + +Relation decideRelation(std::span first, + std::span second) noexcept +{ + if (first.front() == second.front()) + return Relation::Same; + if (holds(second.subspan(1), first.front())) + return Relation::FirstContainsSecond; + if (holds(first.subspan(1), second.front())) + return Relation::SecondContainsFirst; + return Relation::Unrelated; +} + +} // namespace core::fs::detail diff --git a/src/core/fs/detail/Ancestry.hpp b/src/core/fs/detail/Ancestry.hpp new file mode 100644 index 00000000..11b35b58 --- /dev/null +++ b/src/core/fs/detail/Ancestry.hpp @@ -0,0 +1,53 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// How @c IDescriptorFileSystem::relation decides: the identities of a directory and of its real +/// parents, compared. The walk that collects them is the operating system's +/// (`posix/Ancestry.cpp`, `windows/Ancestry.cpp`, one of them chosen by CMake), the decision is +/// shared with the in-memory model. Private to the fs module. + +#include +#include +#include +#include + +#include +#include + +namespace core::fs::detail +{ + +struct NativeContext; // detail/NativeSupport.hpp + +/// What tells one directory from every other for as long as it exists: its device and inode on +/// POSIX, its volume serial number and 128-bit file id on Windows. +struct ObjectIdentity +{ + std::uint64_t device = 0; ///< The device or volume. + std::uint64_t idLow = 0; ///< The inode, or the file id's low 64 bits. + std::uint64_t idHigh = 0; ///< The file id's high 64 bits (Windows). + + [[nodiscard]] bool operator==(ObjectIdentity const&) const = default; +}; + +/// Decides how two directories relate from their ancestries. +/// @param first The first directory's identity, then each of its real parents' up to the root. +/// @param second The same for the second directory. +/// @return `Same` where their own identities match; `FirstContainsSecond` where the first's is +/// among the second's ancestors; the mirror case; otherwise `Unrelated`. Neither may be +/// empty. +[[nodiscard]] CORE_FS_API Relation decideRelation(std::span first, + std::span second) noexcept; + +/// Walks the real parents of two directories of a native file system and decides how they relate; +/// defined by the walker CMake chose. Runs on the blocking executor. +/// @param context The file system's: its `maxAncestorDepth` bounds each walk. +/// @param first A directory handle of it. +/// @param second Another, or the same. +/// @return How they relate, or what @c IDescriptorFileSystem::relation names. +[[nodiscard]] CORE_FS_API FsResult nativeRelation(NativeContext const& context, + platform::NativeHandle first, + platform::NativeHandle second); + +} // namespace core::fs::detail diff --git a/src/core/fs/detail/NativeSupport.cpp b/src/core/fs/detail/NativeSupport.cpp index 2a0e7090..d9144bc1 100644 --- a/src/core/fs/detail/NativeSupport.cpp +++ b/src/core/fs/detail/NativeSupport.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include @@ -79,7 +80,8 @@ NativeContext::NativeContext(async::IExecutor& homeExecutor, std::string_view separators, INtFiles const* files, std::shared_ptr security, - std::shared_ptr creator): + std::shared_ptr creator, + std::shared_ptr boundaries): home { &homeExecutor }, blocking { &blockingExecutor }, wallClock { &clock }, @@ -94,7 +96,8 @@ NativeContext::NativeContext(async::IExecutor& homeExecutor, : nullptr }, ntFiles { files }, ownerSecurity { std::move(security) }, - ownerOnlyCreator { std::move(creator) } + ownerOnlyCreator { std::move(creator) }, + mountBoundaries { std::move(boundaries) } { random.fill(secret); } @@ -130,14 +133,20 @@ FsResult requireDirectory(DescriptorType type) return {}; } +FsResult NativeDescriptorBase::targetIn(SharedContext const& context, + IDescriptor const& descriptor) +{ + auto const* mine = dynamic_cast(&descriptor); + if (mine == nullptr || mine->_context != context) + return refuse(FsErrorCode::CrossDevice); + return Target { .handle = mine->_handle, .flags = mine->_flags, .type = mine->_type }; +} + FsResult NativeDescriptorBase::sameSystemTarget(IDescriptor* other) const { if (other == nullptr) return refuse(FsErrorCode::BadDescriptor); - auto const* mine = dynamic_cast(other); - if (mine == nullptr || mine->_context != _context) - return refuse(FsErrorCode::CrossDevice); - return Target { .handle = mine->_handle, .flags = mine->_flags, .type = mine->_type }; + return targetIn(_context, *other); } FsResult> NativeDescriptorBase::sameObjectCandidate( @@ -151,6 +160,28 @@ FsResult> NativeDescriptorBase::same return std::unexpected { std::move(target.error()) }; } +async::Task> relationOf(SharedContext const& context, + IDescriptor const& first, + IDescriptor const& second) +{ + using Target = NativeDescriptorBase::Target; + auto targets = NativeDescriptorBase::targetIn(context, first).and_then([&](Target firstTarget) { + return NativeDescriptorBase::targetIn(context, second).transform([&](Target secondTarget) { + return std::pair { std::move(firstTarget), std::move(secondTarget) }; + }); + }); + return async::offload( + context->home, context->blocking, [context, targets = std::move(targets)]() -> FsResult { + if (!targets) + return std::unexpected { targets.error() }; + auto const& [firstTarget, secondTarget] = *targets; + if (firstTarget.type != DescriptorType::Directory + || secondTarget.type != DescriptorType::Directory) + return refuse(FsErrorCode::NotDirectory); + return nativeRelation(*context, firstTarget.handle->get(), secondTarget.handle->get()); + }); +} + WalkRules walkRulesOf(NativeContext const& context, SymlinkPolicy finalPolicy, TrailingSlashOnLink onLink) noexcept diff --git a/src/core/fs/detail/NativeSupport.hpp b/src/core/fs/detail/NativeSupport.hpp index 99387673..92ed6a3d 100644 --- a/src/core/fs/detail/NativeSupport.hpp +++ b/src/core/fs/detail/NativeSupport.hpp @@ -35,6 +35,7 @@ namespace core::fs::detail class INtFiles; // windows/WindowsPathWalk.hpp class OwnerSecurity; // windows/OwnerSecurity.hpp class OwnerOnlyCreator; // posix/OwnerOnlyCreation.hpp +class IMountBoundaries; // posix/MountBoundaries.hpp /// @param code What refused. /// @return The refusal, with no system code. @@ -50,7 +51,7 @@ class OwnerOnlyCreator; // posix/OwnerOnlyCreation.hpp using MetadataSecret = std::array; /// What one native file system and all of its descriptors share, fixed at construction. -struct NativeContext +struct CORE_FS_API NativeContext { async::IExecutor* home = nullptr; ///< Where every operation resumes. async::IExecutor* blocking = nullptr; ///< Where every system call runs. @@ -75,6 +76,10 @@ struct NativeContext /// What makes an owner-only file or directory, its staging key drawn when the file system is /// built. Null on Windows. std::shared_ptr ownerOnlyCreator; + /// Where a relation walk leaves a mount that may hide real parents, made when the file system is + /// built. Null on Windows, and where this system's could not be made (every relation is then + /// `Unsupported`). + std::shared_ptr mountBoundaries; /// @param homeExecutor Where every operation resumes. /// @param blockingExecutor Where every system call runs. @@ -85,6 +90,7 @@ struct NativeContext /// @param files The NT calls on Windows; null elsewhere. Must outlive the file system. /// @param security The owner's security on Windows; null elsewhere. /// @param creator What makes owner-only objects on POSIX; null on Windows. + /// @param boundaries The mount boundaries a POSIX relation walk checks; null on Windows. /// The strategy's opener is made here: under `Best`, from @c makeBestBeneathOpener. NativeContext(async::IExecutor& homeExecutor, async::IExecutor& blockingExecutor, @@ -94,7 +100,8 @@ struct NativeContext std::string_view separators, INtFiles const* files, std::shared_ptr security, - std::shared_ptr creator); + std::shared_ptr creator, + std::shared_ptr boundaries); }; /// How a native file system and its descriptors share their @c NativeContext. @@ -145,6 +152,22 @@ class NativeDescriptorBase: public IDescriptor /// @return The flags the descriptor carries. [[nodiscard]] DescriptorFlags flags() const noexcept final { return _flags; } + /// A descriptor passed to another one or to its file system: its handle, rights and type, read + /// on the caller's thread while the caller still holds it. + struct Target + { + SharedHandle handle; ///< Its handle, shared with the job. + DescriptorFlags flags = DescriptorFlags::None; ///< Its rights. + DescriptorType type = DescriptorType::Unknown; ///< What it is. + }; + + /// @param context A native file system's. + /// @param descriptor Any descriptor. + /// @return @p descriptor's handle, rights and type; `CrossDevice` unless it is a descriptor of + /// the file system @p context is (D11). + [[nodiscard]] static FsResult targetIn(SharedContext const& context, + IDescriptor const& descriptor); + protected: /// @param context The file system's. /// @param handle The descriptor's handle. @@ -158,15 +181,6 @@ class NativeDescriptorBase: public IDescriptor { } - /// A directory passed as `newDirectory`: its handle, rights and type, read on the caller's - /// thread while the caller still holds it. - struct Target - { - SharedHandle handle; ///< Its handle, shared with the job. - DescriptorFlags flags = DescriptorFlags::None; ///< Its rights. - DescriptorType type = DescriptorType::Unknown; ///< What it is. - }; - /// Runs @p work on the blocking executor and resumes on home. @p work captures by value /// everything it uses, the handle included, and never the descriptor. template @@ -200,4 +214,15 @@ class NativeDescriptorBase: public IDescriptor DescriptorType _type; }; +/// What a native file system's @c IDescriptorFileSystem::relation is: both descriptors read on the +/// caller's thread, then @c nativeRelation on the blocking executor. +/// @param context The file system's. +/// @param first A directory of it. +/// @param second Another, or the same. +/// @return The task; `CrossDevice` for a foreign descriptor, `NotDirectory` for one that is not a +/// directory, or what @c nativeRelation answers. +[[nodiscard]] async::Task> relationOf(SharedContext const& context, + IDescriptor const& first, + IDescriptor const& second); + } // namespace core::fs::detail diff --git a/src/core/fs/detail/PathWalk.cpp b/src/core/fs/detail/PathWalk.cpp index c6d23e7b..c17c9216 100644 --- a/src/core/fs/detail/PathWalk.cpp +++ b/src/core/fs/detail/PathWalk.cpp @@ -153,12 +153,11 @@ namespace return refuse(FsErrorCode::NoEntry); if (auto checked = checkText(text); !checked) return std::unexpected { std::move(checked.error()) }; - if (separators.contains(text.front())) + auto const rooted = kind == TextKind::SymlinkTarget ? isRootedLinkTarget(text, policy) + : separators.contains(text.front()); + if (rooted) return refuse(FsErrorCode::NotPermitted); auto const pieces = splitOn(text, separators); - if (kind == TextKind::SymlinkTarget && !pieces.empty() - && pieces.front().find_first_of(policy.volumeSeparators) != std::string_view::npos) - return refuse(FsErrorCode::NotPermitted); auto components = Components {}; if (separators.contains(text.back()) || (!pieces.empty() && pieces.back() == ".")) components.finalComponent = FinalComponent::Directory; @@ -204,6 +203,13 @@ FsResult checkSymlinkTarget(std::string_view target, PathPolicy const& pol return componentsOf(target, TextKind::SymlinkTarget, policy).transform([](Components const&) {}); } +FsResult refuseRootedTarget(std::string target, PathPolicy const& policy) +{ + if (isRootedLinkTarget(target, policy)) + return refuse(FsErrorCode::NotPermitted); + return target; +} + FsResult spliceSymlink(PathPlan& plan, std::size_t at, std::string_view target, diff --git a/src/core/fs/detail/PathWalk.hpp b/src/core/fs/detail/PathWalk.hpp index 3fe56917..47e7894f 100644 --- a/src/core/fs/detail/PathWalk.hpp +++ b/src/core/fs/detail/PathWalk.hpp @@ -69,6 +69,14 @@ struct PathPlan [[nodiscard]] CORE_FS_API FsResult checkSymlinkTarget(std::string_view target, PathPolicy const& policy); +/// What `readlinkAt` hands out: a target read from a link, unless it names a root, which no walk +/// follows and no `symlinkAt` makes (@c isRootedLinkTarget), and is refused as WASI 0.3.2 refuses it. +/// @param target The target as stored. +/// @param policy The name rules. +/// @return @p target, or `NotPermitted` where it is rooted. +[[nodiscard]] CORE_FS_API FsResult refuseRootedTarget(std::string target, + PathPolicy const& policy); + /// Replaces component @p at of @p plan, a symbolic link, with the components of its @p target, so /// the walk goes on from the directory holding the link. A target ending in `/` or `/.` that /// replaces the last component makes the plan's @c PathPlan::finalComponent `Directory`. diff --git a/src/core/fs/linux/AccessFacts.cpp b/src/core/fs/linux/AccessFacts.cpp new file mode 100644 index 00000000..7d078b2f --- /dev/null +++ b/src/core/fs/linux/AccessFacts.cpp @@ -0,0 +1,68 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// Who may reach an object on Linux: the owner and the mode of an fstat, read through the very handle. +// A POSIX.1e ACL needs no reading of its own: its named entries are bounded by the mask, which the +// mode's group bits show. An NFSv4 ACL is bounded by nothing in the mode, so where one may decide -- +// an NFS or SMB mount, whose server's ACL the mode only approximates, or an object that carries one +// (ZFS with acltype=nfsv4, an NFSv4 export) -- nothing is judged. Both are told from the handle, so a +// stat by name, which holds none, is not judged either. +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace core::fs::detail +{ + +namespace +{ + + /// The file systems whose access a server decides by an ACL the mode does not bound: NFS (every + /// version shares the magic), and SMB in each of its three magics. + constexpr auto AclFileSystemMagics = std::to_array({ + 0x6969, // NFS_SUPER_MAGIC + 0xFF534D42, // CIFS_SUPER_MAGIC + 0xFE534D42, // SMB2_SUPER_MAGIC + 0x517B, // SMB_SUPER_MAGIC + }); + + /// The extended attributes an object with an NFSv4 ACL answers: the NFS client's, and OpenZFS's. + constexpr auto Nfs4AclAttributes = std::to_array({ + "system.nfs4_acl", + "system.nfs4_acl_xdr", + }); + + /// @return Whether @p handle's object carries @p attribute: a size, or a buffer too small for it. + [[nodiscard]] bool carries(int handle, char const* attribute) + { + return ::fgetxattr(handle, attribute, nullptr, 0) >= 0 || errno == ERANGE; + } + +} // namespace + +std::optional accessFactsOf(int handle, struct ::stat const& status) +{ + // The file system is read from a handle or not at all: by name, another could be mounted there. + if (handle < 0) + return std::nullopt; + struct ::statfs fileSystem {}; + if (::fstatfs(handle, &fileSystem) != 0) + return std::nullopt; + if (std::ranges::find(AclFileSystemMagics, static_cast(fileSystem.f_type)) + != AclFileSystemMagics.end()) + return std::nullopt; + if (std::ranges::any_of(Nfs4AclAttributes, + [&](char const* attribute) { return carries(handle, attribute); })) + return std::nullopt; + return modeFactsOf(status); +} + +} // namespace core::fs::detail diff --git a/src/core/fs/linux/MountBoundaries.cpp b/src/core/fs/linux/MountBoundaries.cpp new file mode 100644 index 00000000..63a996fe --- /dev/null +++ b/src/core/fs/linux/MountBoundaries.cpp @@ -0,0 +1,282 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// Mount boundaries on Linux. statx names the mount each directory is on (STATX_MNT_ID); a mount is +// looked up in this process's mountinfo, read through a handle on /proc/self opened when the file +// system was built, for its file system's device and its root: `/` shows the whole file system; +// anything else (a bind mount of a subdirectory, a btrfs subvolume) shows a subtree whose real +// parents the kernel's `..` skips (posix/MountBoundaries.hpp decides what they may hide). A mount +// missing from the table, or a line that does not parse, is known by its id alone (fail closed). +#include + +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace core::fs::detail +{ + +namespace +{ + + /// The file system types that may show another file system's directories as their own: a union + /// or overlay of other directories, any FUSE file system (bindfs, sshfs, a passthrough), and a + /// network share, which may be a loopback export of this machine's own. + constexpr auto ReexposingTypes = std::to_array({ + { .name = "overlay", .match = TypeMatch::Exact }, + { .name = "aufs", .match = TypeMatch::Exact }, + { .name = "shiftfs", .match = TypeMatch::Exact }, + { .name = "fuse", .match = TypeMatch::Family }, + { .name = "nfs", .match = TypeMatch::Family }, + { .name = "cifs", .match = TypeMatch::Exact }, + { .name = "smb3", .match = TypeMatch::Exact }, + }); + + /// How much of mountinfo is read at most: a mount table larger than this is refused, not + /// half-read. + constexpr auto MaxMountInfoBytes = std::size_t { 16 } << 20U; + + [[nodiscard]] std::unexpected hidden(char const* why) + { + return std::unexpected { FsError { + .code = FsErrorCode::Unsupported, .systemCode = 0, .context = why } }; + } + + [[nodiscard]] FsResult mountIdOf(int handle) + { + struct ::statx status {}; + if (::statx(handle, "", AT_EMPTY_PATH, STATX_MNT_ID, &status) != 0) + return errnoError("statx"); + if ((status.stx_mask & STATX_MNT_ID) == 0) + return hidden("statx names no mount here"); + return std::uint64_t { status.stx_mnt_id }; + } + + class LinuxMountBoundaries final: public IMountBoundaries + { + public: + explicit LinuxMountBoundaries(UniqueHandle processDirectory): + _processDirectory { std::move(processDirectory) } + { + } + + [[nodiscard]] FsResult> crossing(int child, int parent) const override + { + auto const childMount = mountIdOf(child); + if (!childMount) + return std::unexpected { childMount.error() }; + auto const parentMount = mountIdOf(parent); + if (!parentMount) + return std::unexpected { parentMount.error() }; + if (*childMount == *parentMount) + return std::nullopt; + // Linux's `..` leaves a mount only at its root (follow_dotdot); below it, `..` stays on + // the mount. + return viewOf(*childMount).transform([](MountView view) { + return std::optional { MountCrossing { .mount = std::move(view), + .exit = MountExit::AtRoot, + .skipped = {}, + .skippedSet = SkippedSet::Unknown } }; + }); + } + + [[nodiscard]] FsResult mountOf(int handle) const override + { + return mountIdOf(handle).and_then([&](std::uint64_t mount) { return viewOf(mount); }); + } + + [[nodiscard]] FsResult> mountTable() const override + { + return readMountInfo().and_then( + [](std::string const& table) -> FsResult> { + auto places = mountPlacesOf(table); + if (!places) + return hidden("mountinfo holds a line that does not parse"); + auto rows = std::vector {}; + rows.reserve(places->size()); + for (auto& place: *places) + rows.push_back(MountTableRow { .path = std::move(place.mountPoint), + .mount = std::to_string(place.id) }); + return rows; + }); + } + + private: + [[nodiscard]] FsResult viewOf(std::uint64_t mount) const + { + return readMountInfo().transform([&](std::string const& table) { + auto view = MountView { .mount = std::to_string(mount), + .fileSystem = {}, + .root = {}, + .reexposure = Reexposure::Possible }; + if (auto entry = mountEntryOf(table, mount)) + { + view.fileSystem = entry->device; + view.root = std::move(entry->root); + view.reexposure = reexposureOf(ReexposingTypes, entry->type); + } + return view; + }); + } + + [[nodiscard]] FsResult readMountInfo() const + { + auto const file = UniqueHandle { retryOnInterrupt( + [&] { return ::openat(_processDirectory.get(), "mountinfo", O_RDONLY | O_CLOEXEC); }) }; + if (file.get() == platform::InvalidHandle) + return errnoError("openat(mountinfo)"); + auto text = std::string {}; + auto buffer = std::array {}; + while (true) + { + auto const got = + retryOnInterrupt([&] { return ::read(file.get(), buffer.data(), buffer.size()); }); + if (got < 0) + return errnoError("read(mountinfo)"); + if (got == 0) + return text; + if (text.size() + static_cast(got) > MaxMountInfoBytes) + return hidden("mountinfo is larger than is read"); + text.append(buffer.data(), static_cast(got)); + } + } + + UniqueHandle _processDirectory; + }; + + /// @return @p text with mountinfo's octal escapes (`\040` for a space) decoded; nullopt for a bad + /// escape, or one that decodes to NUL, which no path holds. + [[nodiscard]] std::optional unescaped(std::string_view text) + { + auto decoded = std::string {}; + while (!text.empty()) + { + if (text.front() != '\\') + { + decoded += text.front(); + text.remove_prefix(1); + continue; + } + if (text.size() < 4) + return std::nullopt; + auto value = 0U; + for (auto const digit: text.substr(1, 3)) + { + if (digit < '0' || digit > '7') + return std::nullopt; + value = (value * 8U) + static_cast(digit - '0'); + } + if (value == 0 || value > 0xFFU) + return std::nullopt; + decoded += static_cast(value); + text.remove_prefix(4); + } + return decoded; + } + + /// @return @p text as a decimal number; nullopt where it is empty, holds anything but digits, + /// or overflows. + [[nodiscard]] std::optional decimal(std::string_view text) + { + if (text.empty() || text.size() > 19 + || !std::ranges::all_of(text, [](char c) { return c >= '0' && c <= '9'; })) + return std::nullopt; + auto value = std::uint64_t { 0 }; + for (auto const digit: text) + value = (value * 10U) + static_cast(digit - '0'); + return value; + } + + /// @return mountinfo's `major:minor` as `major << 32 | minor`; nullopt where it is not one. + [[nodiscard]] std::optional deviceOf(std::string_view text) + { + auto const colon = text.find(':'); + if (colon == std::string_view::npos) + return std::nullopt; + auto const major = decimal(text.substr(0, colon)); + auto const minor = decimal(text.substr(colon + 1)); + if (!major || !minor || *major > 0xFFFF'FFFFU || *minor > 0xFFFF'FFFFU) + return std::nullopt; + return (*major << 32U) | *minor; + } + +} // namespace + +std::optional> mountPlacesOf(std::string_view mountInfo) +{ + auto places = std::vector {}; + for (auto const lineRange: mountInfo | std::views::split('\n')) + { + auto const line = std::string_view { lineRange }; + if (line.empty()) + continue; + // mount-id parent-id major:minor root mount-point ... + auto fields = std::vector {}; + for (auto const fieldRange: line | std::views::split(' ')) + fields.emplace_back(fieldRange); + if (fields.size() < 5) + return std::nullopt; + auto const id = decimal(fields[0]); + auto mountPoint = unescaped(fields[4]); + if (!id || !mountPoint || !mountPoint->starts_with('/')) + return std::nullopt; + places.push_back(MountPlace { .id = *id, .mountPoint = std::move(*mountPoint) }); + } + return places; +} + +std::optional mountEntryOf(std::string_view mountInfo, std::uint64_t mountId) +{ + for (auto const lineRange: mountInfo | std::views::split('\n')) + { + // mount-id parent-id major:minor root mount-point options [optional fields...] - type source + // super-options + auto fields = std::vector {}; + for (auto const fieldRange: std::string_view { lineRange } | std::views::split(' ')) + fields.emplace_back(fieldRange); + if (fields.size() < 4 || decimal(fields[0]) != mountId) + continue; + // The optional fields end at a lone `-`, never before the seventh column. + auto const separator = std::ranges::find(fields | std::views::drop(6), std::string_view { "-" }); + auto device = deviceOf(fields[2]); + auto root = unescaped(fields[3]); + if (!device || !root || separator == fields.end() || std::next(separator) == fields.end()) + return std::nullopt; + auto type = unescaped(*std::next(separator)); + if (!type || type->empty()) + return std::nullopt; + return MountEntry { .device = *device, .root = std::move(*root), .type = std::move(*type) }; + } + return std::nullopt; +} + +std::shared_ptr makeMountBoundaries() +{ + auto processDirectory = UniqueHandle { retryOnInterrupt( + [] { return ::open("/proc/self", O_PATH | O_DIRECTORY | O_CLOEXEC); }) }; + if (processDirectory.get() == platform::InvalidHandle) + return nullptr; + return std::make_shared(std::move(processDirectory)); +} + +} // namespace core::fs::detail diff --git a/src/core/fs/linux/MountInfo.hpp b/src/core/fs/linux/MountInfo.hpp new file mode 100644 index 00000000..13e10621 --- /dev/null +++ b/src/core/fs/linux/MountInfo.hpp @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// The three columns of Linux's `/proc//mountinfo` the relation walk reads for a mount: the +/// device of its file system (the superblock's, one for every btrfs subvolume of it), and its root, +/// the directory of that file system it shows -- `/` for a mount of a whole file system, the +/// subdirectory's path for a bind mount of one or a subvolume's -- and its file system's type. +/// Private to the fs module. + +#include + +#include +#include +#include +#include +#include + +namespace core::fs::detail +{ + +/// One mount's line of mountinfo, the columns the relation walk reads. +struct MountEntry +{ + std::uint64_t device = 0; ///< Its file system's device, `major << 32 | minor`. + std::string root; ///< Its root, octal escapes (`\040`) decoded. + std::string type; ///< Its file system's type (`ext4`, `overlay`, `fuse.sshfs`). + + [[nodiscard]] bool operator==(MountEntry const&) const = default; +}; + +/// One mount's place, as the scan for mounts beneath a directory reads it. +struct MountPlace +{ + std::uint64_t id = 0; ///< Its mount id. + std::string mountPoint; ///< Where it is mounted, octal escapes decoded. + + [[nodiscard]] bool operator==(MountPlace const&) const = default; +}; + +/// @param mountInfo The text of a `mountinfo` file. +/// @return Every mount's id and mount point, in the file's order; nullopt where any line but the +/// empty one after the last newline is malformed: an id that is no number, a missing mount +/// point, or one with a bad escape or an escaped NUL. +[[nodiscard]] CORE_FS_API std::optional> mountPlacesOf(std::string_view mountInfo); + +/// @param mountInfo The text of a `mountinfo` file. +/// @param mountId A mount's id (`statx`'s `stx_mnt_id`). +/// @return That mount's entry; nullopt where no well-formed line has the id. A line is malformed +/// where a column is missing (the `-` separator and the type after it included), the id or +/// the device is no number, or the root or the type holds a bad escape or an escaped NUL. +[[nodiscard]] CORE_FS_API std::optional mountEntryOf(std::string_view mountInfo, + std::uint64_t mountId); + +} // namespace core::fs::detail diff --git a/src/core/fs/linux/MountInfo_test.cpp b/src/core/fs/linux/MountInfo_test.cpp new file mode 100644 index 00000000..9b2b2ca1 --- /dev/null +++ b/src/core/fs/linux/MountInfo_test.cpp @@ -0,0 +1,99 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The device, root and type columns of Linux's mountinfo, read for a mount a relation walk meets. +#include + +#include + +#include +#include +#include +#include +#include + +using core::fs::detail::MountEntry; +using core::fs::detail::mountEntryOf; +using core::fs::detail::MountPlace; +using core::fs::detail::mountPlacesOf; + +namespace +{ + +constexpr auto Table = std::string_view { "22 1 0:21 / / rw,relatime shared:1 - ext4 /dev/sda1 rw\n" + "35 22 0:32 / /tmp rw,nosuid shared:15 - tmpfs tmpfs rw\n" + "61 35 0:32 /a/sub /tmp/m rw,relatime shared:15 - tmpfs tmpfs rw\n" + "62 22 8:1 /home/with\\040space /mnt/s rw - ext4 /dev/sda1 rw\n" + "63 22 8:1 /bad\\09x /mnt/b rw - ext4 /dev/sda1 rw\n" + "x4 22 8:1 /not-a-number /mnt/n rw - ext4 /dev/sda1 rw\n" + "65 22\n" + "66 22 8 /no-minor /mnt/d rw - ext4 /dev/sda1 rw\n" + "67 22 8:1 /a\\000b /mnt/z rw - ext4 /dev/sda1 rw\n" + "68 22 4294967296:1 /wide /mnt/w rw - ext4 /dev/sda1 rw\n" + "69 22 259:3 /home /home rw - btrfs /dev/nvme0n1p3 rw\n" + "70 22 0:50 / /merged rw shared:3 master:1 - overlay overlay rw\n" + "71 22 0:51 / /mnt/r rw - fuse.sshfs host: rw\n" + "72 22 0:52 / /mnt/q rw ext4 /dev/sda1 rw\n" + "73 22 0:53 / /mnt/t rw -\n" }; + +/// @return A device as mountEntryOf packs it. +[[nodiscard]] constexpr std::uint64_t device(std::uint64_t major, std::uint64_t minor) +{ + return (major << 32U) | minor; +} + +} // namespace + +TEST_CASE("mountinfo: a mount's device, root and type are its third, fourth and post-separator columns", + "[fs][relation]") +{ + CHECK(mountEntryOf(Table, 22) + == std::optional { MountEntry { .device = device(0, 21), .root = "/", .type = "ext4" } }); + CHECK(mountEntryOf(Table, 35) + == std::optional { MountEntry { .device = device(0, 32), .root = "/", .type = "tmpfs" } }); + CHECK(mountEntryOf(Table, 61) + == std::optional { MountEntry { .device = device(0, 32), .root = "/a/sub", .type = "tmpfs" } }); + CHECK(mountEntryOf(Table, 62) + == std::optional { + MountEntry { .device = device(8, 1), .root = "/home/with space", .type = "ext4" } }); + CHECK(mountEntryOf(Table, 70) + == std::optional { MountEntry { .device = device(0, 50), .root = "/", .type = "overlay" } }); + CHECK(mountEntryOf(Table, 71) + == std::optional { MountEntry { .device = device(0, 51), .root = "/", .type = "fuse.sshfs" } }); + CHECK(mountEntryOf(Table, 69) + == std::optional { MountEntry { .device = device(259, 3), .root = "/home", .type = "btrfs" } }); +} + +TEST_CASE("mountinfo: no well-formed line is no entry", "[fs][relation]") +{ + CHECK_FALSE(mountEntryOf(Table, 63).has_value()); // a bad escape + CHECK_FALSE(mountEntryOf(Table, 65).has_value()); // too few columns + CHECK_FALSE(mountEntryOf(Table, 4).has_value()); // an id that is no number + CHECK_FALSE(mountEntryOf(Table, 66).has_value()); // a device with no minor + CHECK_FALSE(mountEntryOf(Table, 67).has_value()); // an escaped NUL in the middle of the root + CHECK_FALSE(mountEntryOf(Table, 68).has_value()); // a major wider than 32 bits + CHECK_FALSE(mountEntryOf(Table, 72).has_value()); // no separator before the type + CHECK_FALSE(mountEntryOf(Table, 73).has_value()); // a separator with no type after it + CHECK_FALSE(mountEntryOf(Table, 99).has_value()); // no such mount + CHECK_FALSE(mountEntryOf("", 22).has_value()); +} + +TEST_CASE("mountinfo: every mount's id and mount point, or nothing where a line does not parse", + "[fs][relation]") +{ + constexpr auto Good = std::string_view { "22 1 0:21 / / rw - ext4 /dev/sda1 rw\n" + "62 22 8:1 /home /mnt/with\\040space rw - ext4 /dev/sda1 rw\n" }; + CHECK(mountPlacesOf(Good) + == std::optional { std::vector { MountPlace { .id = 22, .mountPoint = "/" }, + MountPlace { .id = 62, .mountPoint = "/mnt/with space" } } }); + CHECK(mountPlacesOf("") == std::optional { std::vector {} }); + // One line that cannot be read hides a mount the scan must see: the whole table is refused. + for (auto const* bad: { "x4 22 8:1 / /mnt/n rw - ext4 /dev/sda1 rw\n", + "65 22 8:1 /\n", + "67 22 8:1 / /mnt/a\\000b rw - ext4 /dev/sda1 rw\n", + "68 22 8:1 / /mnt/a\\09x rw - ext4 /dev/sda1 rw\n", + "69 22 8:1 / relative rw - ext4 /dev/sda1 rw\n" }) + { + INFO(bad); + CHECK_FALSE(mountPlacesOf(std::string { Good } + bad).has_value()); + } +} diff --git a/src/core/fs/linux/Relation_test.cpp b/src/core/fs/linux/Relation_test.cpp new file mode 100644 index 00000000..a21c6a69 --- /dev/null +++ b/src/core/fs/linux/Relation_test.cpp @@ -0,0 +1,266 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The native relation across mount boundaries on Linux: the kernel's own `..` leaves a mount for +// the directory it is mounted on, so a mount -- a bind mount of a directory beneath the root +// included -- is beneath what it is mounted beneath, whatever device it is on. +#include +#include +#include +#include + +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +using core::fs::DescriptorFlags; +using core::fs::FsResult; +using core::fs::IDescriptor; +using core::fs::Relation; +using core::fs::test::DescriptorFixture; + +namespace +{ + +/// What a child process exits with to say its case could not run here. +constexpr int SkippedExit = 77; + +/// @return The device @p path is on, or nullopt where it cannot be stat'ed. +[[nodiscard]] std::optional<::dev_t> deviceOf(char const* path) +{ + struct ::stat status {}; + if (::stat(path, &status) != 0) + return std::nullopt; + return status.st_dev; +} + +/// @return A preopen of @p path, the host's, or null where it cannot be opened: no assertion, so a +/// forked child may call it. +[[nodiscard]] std::unique_ptr tryPreopen(DescriptorFixture const& fixture, + std::filesystem::path path) +{ + auto opened = fixture.run(fixture.fileSystem().openPreopen(std::move(path), DescriptorFlags::Read)); + return opened ? std::move(*opened) : nullptr; +} + +/// @return A preopen of @p path, the host's. +[[nodiscard]] std::unique_ptr preopen(DescriptorFixture const& fixture, + std::filesystem::path path) +{ + auto opened = tryPreopen(fixture, std::move(path)); + REQUIRE(opened != nullptr); + return opened; +} + +/// Writes @p text to @p path, as a process's id maps are written. +/// @return Whether it was written. +[[nodiscard]] bool writeFile(char const* path, std::string const& text) +{ + auto file = std::ofstream { path }; + file << text; + file.flush(); + return file.good(); +} + +/// @return Whether @p answer is @p expected. +[[nodiscard]] bool is(FsResult const& answer, Relation expected) +{ + return answer.has_value() && *answer == expected; +} + +} // namespace + +TEST_CASE("relation crosses a mount upward", "[fs][native][relation]") +{ + // /proc is a mount of its own wherever Linux runs: its `..` is the root of another device. + auto const rootDevice = deviceOf("/"); + auto const procDevice = deviceOf("/proc"); + if (!rootDevice || !procDevice || *rootDevice == *procDevice) + SKIP("/proc is not a mount of its own here"); + auto fixture = DescriptorFixture::createNative(); + auto const root = preopen(fixture, "/"); + auto const proc = preopen(fixture, "/proc"); + CHECK(is(fixture.run(fixture.fileSystem().relation(*root, *proc)), Relation::FirstContainsSecond)); + CHECK(is(fixture.run(fixture.fileSystem().relation(*proc, *root)), Relation::SecondContainsFirst)); +} + +namespace +{ + +/// What a row of the namespace case expects. +enum class Expect : std::uint8_t +{ + Same, + FirstContainsSecond, + Unrelated, + Unsupported, +}; + +/// One row of the namespace case: two directories by their path beneath the host (empty for the +/// host itself), and the answer. +struct NamespaceRow +{ + char const* name; + char const* first; + char const* second; + Expect expect; +}; + +constexpr auto NamespaceRows = std::to_array({ + { "the root contains a tmpfs mounted whole", "", "t/x", Expect::FirstContainsSecond }, + { "a directory beside the tmpfs", "c", "t/x", Expect::Unrelated }, + { "a sub-bind hides a from a walk up from its key", "a", "m/key", Expect::Unsupported }, + { "the root contains the sub-bind mounted beneath it", "", "m", Expect::FirstContainsSecond }, + { "a/sub and its bind at m", "a/sub", "m", Expect::Same }, + { "two directories on the sub-bind", "m/x", "m/y", Expect::Unrelated }, + { "the sub-bind contains its own", "m", "m/y", Expect::FirstContainsSecond }, + { "a tmpfs directory against the sub-bind", "t/x", "m/key", Expect::Unrelated }, + { "the sub-bind against a tmpfs directory", "m/key", "t/x", Expect::Unrelated }, + { "two directories on the overlay", "o/x", "o/y", Expect::Unrelated }, + { "the overlay's lower directory and what it shows", "lower", "o/x", Expect::Unsupported }, + { "the overlay against another file system's directory", "o/x", "c", Expect::Unsupported }, + { "the overlay contains its own", "o", "o/x", Expect::FirstContainsSecond }, + { "a bind beneath the grant shows the key's file system", "g", "k/secret", Expect::Unsupported }, + { "the key, against a grant a bind beneath shows it through", "k/secret", "g", Expect::Unsupported }, + { "a tmpfs beneath the grant shows no other file system", "h", "c", Expect::Unrelated }, + { "a mount beneath the grant shows none of the key's", "g", "t/x", Expect::Unrelated }, +}); + +/// What a forked child exits with where it could not run its rows: an open failed, something threw, +/// or no unprivileged overlay could be mounted. A row that fails exits with its number, from 1. +constexpr int OpenFailedExit = 100; +constexpr int ThrewExit = 101; +constexpr int NoOverlayExit = 102; + +/// @return Whether @p answer is what @p expect says. +[[nodiscard]] bool meets(FsResult const& answer, Expect expect) +{ + switch (expect) + { + case Expect::Same: return is(answer, Relation::Same); + case Expect::FirstContainsSecond: return is(answer, Relation::FirstContainsSecond); + case Expect::Unrelated: return is(answer, Relation::Unrelated); + case Expect::Unsupported: + return !answer.has_value() && answer.error().code == core::fs::FsErrorCode::Unsupported; + } + return false; +} + +} // namespace + +TEST_CASE("relation across mounts made in a namespace of its own", "[fs][native][relation]") +{ + // In a child's own user and mount namespace, with a file system built there so it reads that + // namespace's mountinfo: + // - a tmpfs mounted whole at root/t is walked across: t/x lies beneath the root; + // - root/a/sub bound at root/m hides a: the kernel's `..` of m is the root, so a walk from m/key + // never meets a, though m/key lies beneath it. That is Unsupported, never Unrelated (the root, + // which m is mounted beneath, still contains it); + // - but two directories both on m are walked whole inside it, and a directory on the tmpfs is on + // another file system, which nothing m hides can be: those answers stand; + // - an overlay at root/o shows root/lower's directories as its own: only its own mount decides; + // - root/k bound at root/g/inner puts the key root/k/secret beneath the grant root/g, though + // neither walk up meets the other: a mount beneath a directory that shows the other's file + // system is Unsupported, and one of another file system (a tmpfs at root/h/tm) changes nothing. + auto const uid = ::getuid(); + auto const gid = ::getgid(); + auto const child = ::fork(); + REQUIRE(child >= 0); + if (child == 0) + { + if (::unshare(CLONE_NEWUSER | CLONE_NEWNS) != 0) + ::_exit(SkippedExit); + if (!writeFile("/proc/self/setgroups", "deny") + || !writeFile("/proc/self/uid_map", "0 " + std::to_string(uid) + " 1") + || !writeFile("/proc/self/gid_map", "0 " + std::to_string(gid) + " 1")) + ::_exit(SkippedExit); + if (::mount("none", "/", nullptr, MS_REC | MS_PRIVATE, nullptr) != 0) + ::_exit(SkippedExit); + try + { + auto fixture = DescriptorFixture::createNative(); + auto const& host = fixture.hostDirectory(); + for (auto const* directory: { "a/sub/key", + "a/sub/x", + "a/sub/y", + "m", + "t", + "c", + "lower/x", + "lower/y", + "upper", + "work", + "o", + "k/secret", + "g/inner", + "h/tm" }) + std::filesystem::create_directories(host / directory); + if (::mount((host / "a" / "sub").c_str(), (host / "m").c_str(), nullptr, MS_BIND, nullptr) != 0 + || ::mount("tmpfs", (host / "t").c_str(), "tmpfs", 0, "size=1m") != 0 + || ::mount((host / "k").c_str(), (host / "g" / "inner").c_str(), nullptr, MS_BIND, nullptr) + != 0 + || ::mount("tmpfs", (host / "h" / "tm").c_str(), "tmpfs", 0, "size=1m") != 0) + ::_exit(SkippedExit); + auto const overlayOptions = "lowerdir=" + (host / "lower").string() + ",upperdir=" + + (host / "upper").string() + ",workdir=" + (host / "work").string(); + if (::mount("overlay", (host / "o").c_str(), "overlay", 0, overlayOptions.c_str()) != 0) + ::_exit(NoOverlayExit); + std::filesystem::create_directories(host / "t" / "x"); + auto& system = fixture.fileSystem(); + for (auto const& [index, row]: std::views::zip(std::views::iota(1), NamespaceRows)) + { + auto const first = tryPreopen(fixture, host / row.first); + auto const second = tryPreopen(fixture, host / row.second); + if (!first || !second) + ::_exit(OpenFailedExit); + if (!meets(fixture.run(system.relation(*first, *second)), row.expect)) + ::_exit(index); + } + } + catch (...) + { + ::_exit(ThrewExit); + } + ::_exit(0); + } + auto status = 0; + while (::waitpid(child, &status, 0) < 0) + REQUIRE(errno == EINTR); + REQUIRE(WIFEXITED(status)); + auto const exit = WEXITSTATUS(status); + if (exit == SkippedExit || exit == NoOverlayExit) + { + auto const why = exit == SkippedExit ? "no user and mount namespace for an unprivileged mount here" + : "no unprivileged overlay mount here"; + // CI's Linux jobs allow unprivileged user namespaces and set this, so the rows cannot skip + // there unseen. + if (core::LiveEnvironment {}.get("CORE_TEST_REQUIRE_USERNS") == "1") + FAIL("CORE_TEST_REQUIRE_USERNS=1, but " << why); + SKIP(why); + } + REQUIRE(exit != OpenFailedExit); + REQUIRE(exit != ThrewExit); + auto const failedRow = exit > 0 ? static_cast(exit) : std::size_t { 0 }; + INFO("the first row that failed: " << (failedRow >= 1 && failedRow <= NamespaceRows.size() + ? NamespaceRows.at(failedRow - 1).name + : "none")); + CHECK(exit == 0); +} diff --git a/src/core/fs/posix/AccessFacts.cpp b/src/core/fs/posix/AccessFacts.cpp index 121e2ba5..c3b93164 100644 --- a/src/core/fs/posix/AccessFacts.cpp +++ b/src/core/fs/posix/AccessFacts.cpp @@ -1,12 +1,9 @@ // SPDX-License-Identifier: Apache-2.0 // -// Who may reach an object on Linux, and on every POSIX system without an ACL of its own: the owner -// and the mode of an fstat. A POSIX.1e ACL needs no reading of its own here: its named entries are -// bounded by the mask, which the mode's group bits show, so a mode with no group or other bit -// leaves no named entry any right. Nothing else is read, so the facts hold for an fstatat by name -// as for a handle. +// Who may reach an object on a BSD with no ACL beyond the mode (OpenBSD, DragonFly): the owner and +// the mode of an fstat. Nothing else is read, so the facts hold for an fstatat by name as for a +// handle. #include -#include #include #include @@ -21,18 +18,4 @@ std::optional accessFactsOf(int /*handle*/, struct ::stat const& st return modeFactsOf(status); } -FsResult stripInheritedAcl(int /*handle*/, ::mode_t /*mode*/) -{ - // A POSIX.1e default ACL replaces the umask step, but each entry it hands down is ANDed with the - // mode argument's bits: the mask with the group bits, other with the other bits. Under 0600 or - // 0700 both are zero, so no named entry and no other is left any right; nothing to strip. - return {}; -} - -OwnerOnlyCreation nativeOwnerOnlyCreation() noexcept -{ - // The mode caps every entry a default ACL hands down. - return OwnerOnlyCreation::Direct; -} - } // namespace core::fs::detail diff --git a/src/core/fs/posix/Ancestry.cpp b/src/core/fs/posix/Ancestry.cpp new file mode 100644 index 00000000..f60a3019 --- /dev/null +++ b/src/core/fs/posix/Ancestry.cpp @@ -0,0 +1,452 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The real parents of a directory on POSIX, walked through the kernel's own `..`: each one is +// opened relative to the last, never by a name, until `..` is the directory itself -- the root of +// this process's view. The kernel crosses a mount boundary upward on its own, to the directory +// the mount is on; where the mount left shows a subtree of its file system (a bind mount of a +// subdirectory) or below its root (a macOS firmlink), parents are never seen, so each mount left is kept, +// and an `Unrelated` that one of them could hide the other directory behind is refused +// (posix/MountBoundaries.hpp). A walk up never sees a mount beneath either directory, so an +// `Unrelated` also reads the mount table and opens each mount point beneath either one, refusing +// where it may show the other's file system; a parent the user cannot search is the +// error it is, and the caller fails closed. Each parent is opened as a path handle where the system +// has O_PATH, so a directory the user may search but not read is walked through. CMake compiles +// this file on every POSIX system, and windows/Ancestry.cpp on Windows; the one #ifdef below picks a +// flag inside the data, as posix/BeneathDefault.cpp does. +#include + +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace core::fs::detail +{ + +namespace +{ + +#ifdef O_PATH + constexpr int ParentAccess = O_PATH; +#else + constexpr int ParentAccess = O_RDONLY | O_NONBLOCK; +#endif + + constexpr int ParentOpenFlags = ParentAccess | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC; + + [[nodiscard]] FsResult identityOf(int handle) + { + struct ::stat status {}; + if (::fstat(handle, &status) != 0) + return errnoError("fstat"); + return ObjectIdentity { .device = static_cast(status.st_dev), + .idLow = static_cast(status.st_ino), + .idHigh = 0 }; + } + + /// A directory's ancestry: its identity, then each real parent's up to the root, and each mount + /// the walk left on the way. + struct Ancestry + { + /// A mount the walk left, and the directory it was left from. + struct Crossing + { + MountCrossing crossing; + ObjectIdentity from; + + [[nodiscard]] bool operator==(Crossing const&) const = default; + }; + + std::vector chain; + std::vector crossings; + + [[nodiscard]] bool operator==(Ancestry const&) const = default; + }; + + /// @param handle A directory; never closed here. + /// @param self Its identity. + /// @param boundaries What reads each step that leaves a mount. + /// @param maxDepth How many parents may be walked before `Loop`. + /// @return Its ancestry. + [[nodiscard]] FsResult ancestryOf(int handle, + ObjectIdentity const& self, + IMountBoundaries const& boundaries, + std::size_t maxDepth) + { + // Grown per step, never reserved to the cap: a deep tree costs what it walks. At most + // maxDepth + 1 parents are opened, and the last of them must be the root. + auto ancestry = Ancestry { .chain = { self }, .crossings = {} }; + auto current = UniqueHandle { platform::InvalidHandle }; + for ([[maybe_unused]] auto const step: std::views::iota(std::size_t { 0 }, maxDepth + 1)) + { + auto const from = current.get() == platform::InvalidHandle ? handle : current.get(); + auto parent = + UniqueHandle { retryOnInterrupt([&] { return ::openat(from, "..", ParentOpenFlags); }) }; + if (parent.get() == platform::InvalidHandle) + return errnoError("openat(..)"); + auto const identity = identityOf(parent.get()); + if (!identity) + return std::unexpected { identity.error() }; + if (*identity == ancestry.chain.back()) + return ancestry; + auto crossed = boundaries.crossing(from, parent.get()); + if (!crossed) + return std::unexpected { crossed.error() }; + if (*crossed) + ancestry.crossings.push_back( + { .crossing = std::move(**crossed), .from = ancestry.chain.back() }); + ancestry.chain.push_back(*identity); + current = std::move(parent); // closes the one before + } + return refuse(FsErrorCode::Loop); + } + + /// @return Both directories' ancestries, walked one after the other. + [[nodiscard]] FsResult> ancestriesOf(int first, + ObjectIdentity const& firstSelf, + int second, + ObjectIdentity const& secondSelf, + IMountBoundaries const& boundaries, + std::size_t maxDepth) + { + return ancestryOf(first, firstSelf, boundaries, maxDepth).and_then([&](Ancestry up) { + return ancestryOf(second, secondSelf, boundaries, maxDepth).transform([&](Ancestry down) { + return std::pair { std::move(up), std::move(down) }; + }); + }); + } + + /// @param crossings The mounts one walk left. + /// @param other The other directory. + /// @param otherChain The other directory's walked ancestry. + /// @return Nothing where none of @p crossings can hide @p other; `Unsupported` where one may. + [[nodiscard]] FsResult checkHidden(std::span crossings, + int other, + std::span otherChain, + IMountBoundaries const& boundaries) + { + // A mount of a whole file system of its own, left from its root, hides nothing, and needs no + // read of the other's mount. + auto const hidesNothing = [](Ancestry::Crossing const& left) { + return left.crossing.exit == MountExit::AtRoot && left.crossing.mount.root == "/" + && left.crossing.mount.reexposure == Reexposure::Impossible; + }; + if (std::ranges::all_of(crossings, hidesNothing)) + return {}; + auto const otherMount = boundaries.mountOf(other); + if (!otherMount) + return std::unexpected { otherMount.error() }; + auto const hides = [&](Ancestry::Crossing const& left) { + auto const passes = std::ranges::find(otherChain, left.from) != otherChain.end() + ? PassesThrough::Yes + : PassesThrough::No; + return mayHide( + left.crossing, + HidingCandidate { .mount = *otherMount, .identity = otherChain.front(), .passes = passes }); + }; + if (std::ranges::any_of(crossings, hides)) + return std::unexpected { FsError { .code = FsErrorCode::Unsupported, + .systemCode = 0, + .context = + "a mount left on the way may hide the other directory" } }; + return {}; + } + + /// @return The identity of @p name in @p directory, a symbolic link's own: a stat needs search + /// permission on @p directory alone, so a directory nobody may enter still has one. + [[nodiscard]] FsResult identityAt(int directory, std::string const& name) + { + struct ::stat status {}; + if (::fstatat(directory, name.c_str(), &status, AT_SYMLINK_NOFOLLOW) != 0) + return errnoError("fstatat"); + return ObjectIdentity { .device = static_cast(status.st_dev), + .idLow = static_cast(status.st_ino), + .idHigh = 0 }; + } + + /// @return @p name in @p directory, opened as a directory without following a link. + [[nodiscard]] FsResult openNamed(int directory, std::string const& name) + { + auto opened = UniqueHandle { retryOnInterrupt( + [&] { return ::openat(directory, name.c_str(), ParentOpenFlags); }) }; + if (opened.get() == platform::InvalidHandle) + return errnoError("openat(mount point)"); + return opened; + } + + /// @return A refusal saying a mount beneath a directory may show the other one. + [[nodiscard]] std::unexpected mayExpose(char const* why) + { + return std::unexpected { FsError { + .code = FsErrorCode::Unsupported, .systemCode = 0, .context = why } }; + } + + /// Opens @p row's mount point where it lies strictly beneath @p topSelf, walking its path from + /// the root one component at a time, never following a link. + /// + /// Each component is told apart by identity before it is entered: a path that reaches the + /// directory a walk up from @p topSelf passed through stays on @p topChain until it reaches + /// @p topSelf itself, so the first component that is neither is where the path leaves for + /// somewhere else, and nothing past it needs to be entered -- or may be, where the user cannot. + /// A component identified is entered only as that directory (@c openNamedAs): a rename between + /// the stat and the open, which would carry the scan on through a directory it never told + /// apart, is `Busy`. + /// @param row A mount of the table. + /// @param topSelf The directory the mount may lie beneath. + /// @param topChain Its walked ancestry, itself first and the root last. + /// @return The mount point, opened; an invalid handle where it is not beneath @p topSelf; or a + /// refusal where a component beneath @p topSelf, or the path's shape, could not be read; + /// `Busy` where a component changed between its stat and its open. + [[nodiscard]] FsResult openIfBeneath(MountTableRow const& row, + ObjectIdentity const& topSelf, + std::span topChain) + { + if (!row.path.starts_with('/')) + return mayExpose("a mount point in the table is no absolute path"); + auto current = UniqueHandle { retryOnInterrupt([] { return ::open("/", ParentOpenFlags); }) }; + if (current.get() == platform::InvalidHandle) + return errnoError("open(/)"); + auto const root = identityOf(current.get()); + if (!root) + return std::unexpected { root.error() }; + if (topChain.empty() || *root != topChain.back()) + return mayExpose("the root a mount point is read from is not the walk's"); + auto beneath = *root == topSelf; + auto components = std::vector {}; + for (auto const part: std::string_view { row.path } | std::views::split('/')) + if (!std::ranges::empty(part)) + components.emplace_back(std::string_view { part }); + if (components.empty()) + return UniqueHandle { platform::InvalidHandle }; // the root is beneath nothing + for (auto const& component: components) + { + if (component == "." || component == "..") + return mayExpose("a mount point in the table is not a plain path"); + if (beneath) + { + auto next = openNamed(current.get(), component); + if (!next) + return std::unexpected { next.error() }; + current = std::move(*next); + continue; + } + auto const identity = identityAt(current.get(), component); + if (!identity) + return std::unexpected { identity.error() }; + if (*identity == topSelf) + beneath = true; + else if (std::ranges::find(topChain, *identity) == topChain.end()) + return UniqueHandle { platform::InvalidHandle }; + // The mount point itself is the directory, or one of its parents: not beneath it. + if (&component == &components.back()) + return UniqueHandle { platform::InvalidHandle }; + // Entered only as what was identified: a rename since the stat answers Busy. + auto next = openNamedAs(current.get(), component, *identity); + if (!next) + return std::unexpected { next.error() }; + current = std::move(*next); + } + return current; + } + + /// Refuses where a mount strictly beneath @p topSelf may show @p other's file system: one of + /// the same file system, one whose file system may show another's, or any where @p other's may, + /// or where either is unknown. + /// @param topSelf The directory. + /// @param topChain Its walked ancestry. + /// @param other The mount the other directory is on. + /// @param table The mount table. + /// @param boundaries What reads a mount. + /// @return Nothing where no mount beneath @p topSelf may show @p other; `Unsupported` otherwise. + [[nodiscard]] FsResult checkMountsBeneath(ObjectIdentity const& topSelf, + std::span topChain, + MountView const& other, + std::span table, + IMountBoundaries const& boundaries) + { + for (auto const& row: table) + { + auto const opened = openIfBeneath(row, topSelf, topChain); + if (!opened) + return std::unexpected { opened.error() }; + if (opened->get() == platform::InvalidHandle) + continue; + auto const mounted = boundaries.mountOf(opened->get()); + if (!mounted) + return std::unexpected { mounted.error() }; + // A path that opens onto another mount than the row's (one made over it, or a row of the + // table that moved) says nothing about the row's. + if (!row.mount || mounted->mount != row.mount) + return mayExpose("a mount point beneath the directory opens onto another mount"); + auto const shows = mounted->reexposure == Reexposure::Possible + || other.reexposure == Reexposure::Possible || !mounted->fileSystem + || !other.fileSystem || *mounted->fileSystem == *other.fileSystem; + if (shows) + return mayExpose("a mount beneath one directory may show the other's file system"); + } + return {}; + } + + /// Refuses where a mount beneath either directory may show the other's file system; `Busy` where + /// the mount table changed while it was scanned. + [[nodiscard]] FsResult checkBothBeneath( + int first, Ancestry const& up, int second, Ancestry const& down, IMountBoundaries const& boundaries) + { + auto const table = boundaries.mountTable(); + if (!table) + return std::unexpected { table.error() }; + auto const firstMount = boundaries.mountOf(first); + if (!firstMount) + return std::unexpected { firstMount.error() }; + auto const secondMount = boundaries.mountOf(second); + if (!secondMount) + return std::unexpected { secondMount.error() }; + if (auto scanned = checkMountsBeneath(up.chain.front(), up.chain, *secondMount, *table, boundaries) + .and_then([&] { + return checkMountsBeneath( + down.chain.front(), down.chain, *firstMount, *table, boundaries); + }); + !scanned) + return scanned; + auto const again = boundaries.mountTable(); + if (!again || *again != *table) + return refuse(FsErrorCode::Busy); + return {}; + } + + /// @return Whether @p ancestor is a path above @p path, `/` above every other. + [[nodiscard]] bool isAbove(std::string_view ancestor, std::string_view path) noexcept + { + if (ancestor == path) + return false; + if (ancestor == "/") + return true; + return path.starts_with(ancestor) && path.size() > ancestor.size() && path[ancestor.size()] == '/'; + } + +} // namespace + +FsResult openNamedAs(int directory, std::string const& name, ObjectIdentity const& expected) +{ + return openNamed(directory, name).and_then([&](UniqueHandle opened) -> FsResult { + auto const identity = identityOf(opened.get()); + if (!identity) + return std::unexpected { identity.error() }; + if (*identity != expected) + return refuse(FsErrorCode::Busy); + return opened; + }); +} + +bool mayHide(MountCrossing const& left, HidingCandidate const& other) +{ + auto const& mount = left.mount; + auto const sameMount = mount.mount && other.mount.mount && *mount.mount == *other.mount.mount; + // Below its root (a firmlink), the step skipped the mount's own directories above the one left + // from and each directory on the mount point's path; a directory whose walk passed the one left + // from lies at or beneath it, and is none of them. This comes before every shortcut: a skipped + // directory on the mount point's path is on another mount, often another device. + if (left.exit == MountExit::BelowRoot && other.passes == PassesThrough::No) + { + auto const skipped = std::ranges::find(left.skipped, other.identity) != left.skipped.end(); + switch (left.skippedSet) + { + case SkippedSet::Unknown: return true; + case SkippedSet::AtLeast: + if (skipped || sameMount) + return true; + break; + case SkippedSet::Exactly: + if (skipped) + return true; + break; + } + } + // On the mount left, the other walk is whole inside it. + if (sameMount) + return false; + if (mount.reexposure == Reexposure::Possible) + return true; + if (left.exit == MountExit::AtRoot && mount.root == "/") + return false; + if (other.mount.reexposure == Reexposure::Possible) + return true; + if (!mount.fileSystem || !other.mount.fileSystem) + return true; + if (*mount.fileSystem != *other.mount.fileSystem) + return false; + // Below the root, through another mount of the same file system: decided only where every + // directory skipped is known by identity, which the check above has compared. + if (left.exit == MountExit::BelowRoot) + return other.passes == PassesThrough::No && left.skippedSet != SkippedSet::Exactly; + // One file system, reached through another mount: a directory there lies beneath what that + // mount shows, so it can be above left's root only where what that mount shows is. + return !mount.root || !other.mount.root || isAbove(*other.mount.root, *mount.root); +} + +Reexposure reexposureOf(std::span table, std::string_view type) +{ + if (type.empty()) + return Reexposure::Possible; + auto const matches = [&](ReexposingType const& row) { + return row.match == TypeMatch::Family ? type.starts_with(row.name) : type == row.name; + }; + return std::ranges::any_of(table, matches) ? Reexposure::Possible : Reexposure::Impossible; +} + +FsResult nativeRelation(NativeContext const& context, + platform::NativeHandle first, + platform::NativeHandle second) +{ + if (context.mountBoundaries == nullptr) + return refuse(FsErrorCode::Unsupported); + auto const& boundaries = *context.mountBoundaries; + auto const maxDepth = context.options.maxAncestorDepth; + return identityOf(first).and_then([&](ObjectIdentity const& firstSelf) { + return identityOf(second).and_then([&](ObjectIdentity const& secondSelf) -> FsResult { + if (firstSelf == secondSelf) + return Relation::Same; + // Each `..` is atomic, but the two walks are not one instant: a directory moved between + // them, or during one, could make the chains agree with no tree that ever existed. Both are + // walked again, and any difference is Busy. What remains is a move away and back between + // the two passes (ABA), which leaves each chain as a tree that did exist. + auto const walked = ancestriesOf(first, firstSelf, second, secondSelf, boundaries, maxDepth); + if (!walked) + return std::unexpected { walked.error() }; + auto const again = ancestriesOf(first, firstSelf, second, secondSelf, boundaries, maxDepth); + if (!again || *again != *walked) + return refuse(FsErrorCode::Busy); + auto const& [up, down] = *walked; + auto const decided = decideRelation(up.chain, down.chain); + // A containment the walks met is real; an `Unrelated` stands only where no mount left on + // either way hides the other directory above its root, and no mount beneath either + // shows the other's file system. + if (decided != Relation::Unrelated) + return decided; + return checkHidden(up.crossings, second, down.chain, boundaries) + .and_then([&] { return checkHidden(down.crossings, first, up.chain, boundaries); }) + .and_then([&] { return checkBothBeneath(first, up, second, down, boundaries); }) + .transform([] { return Relation::Unrelated; }); + }); + }); +} + +} // namespace core::fs::detail diff --git a/src/core/fs/posix/ModeCappedCreation.cpp b/src/core/fs/posix/ModeCappedCreation.cpp new file mode 100644 index 00000000..61f01e39 --- /dev/null +++ b/src/core/fs/posix/ModeCappedCreation.cpp @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// Owner-only creation where the creating call's mode caps whatever a directory hands down: Linux, +// whose POSIX.1e default ACL is ANDed with the mode, and every POSIX system whose ACLs are not read +// here. Each fills its AccessFacts in its own AccessFacts.cpp. +#include +#include + +#include + +namespace core::fs::detail +{ + +FsResult stripInheritedAcl(int /*handle*/, ::mode_t /*mode*/) +{ + // A POSIX.1e default ACL replaces the umask step, but each entry it hands down is ANDed with the + // mode argument's bits: the mask with the group bits, other with the other bits. Under 0600 or + // 0700 both are zero, so no named entry and no other is left any right; nothing to strip. + return {}; +} + +OwnerOnlyCreation nativeOwnerOnlyCreation() noexcept +{ + // The mode caps every entry a default ACL hands down. + return OwnerOnlyCreation::Direct; +} + +} // namespace core::fs::detail diff --git a/src/core/fs/posix/MountBoundaries.cpp b/src/core/fs/posix/MountBoundaries.cpp new file mode 100644 index 00000000..8b1c7120 --- /dev/null +++ b/src/core/fs/posix/MountBoundaries.cpp @@ -0,0 +1,86 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// Mount boundaries on a POSIX system with no way to tell what a mount shows (neither Linux's +// mountinfo nor the BSDs' statfs): every step that changes device leaves a mount, which may show a +// subtree, from below its root, of a type that may show another file system's directories; no +// mount can be named, so every `Unrelated` past a change of device is Unsupported (fail closed). Nor +// can the mounts be listed, so no `Unrelated` stands at all: one beneath either directory could show +// the other. +#include + +#include +#include + +#include + +#include +#include +#include +#include +#include + +namespace core::fs::detail +{ + +namespace +{ + + [[nodiscard]] FsResult deviceOf(int handle) + { + struct ::stat status {}; + if (::fstat(handle, &status) != 0) + return errnoError("fstat"); + return static_cast(status.st_dev); + } + + [[nodiscard]] MountView viewOn(std::uint64_t device) + { + // Nor what type of file system it is: one that may show another's (fail closed). + return MountView { .mount = std::nullopt, + .fileSystem = device, + .root = std::nullopt, + .reexposure = Reexposure::Possible }; + } + + class DeviceMountBoundaries final: public IMountBoundaries + { + public: + [[nodiscard]] FsResult> crossing(int child, int parent) const override + { + auto const childDevice = deviceOf(child); + if (!childDevice) + return std::unexpected { childDevice.error() }; + auto const parentDevice = deviceOf(parent); + if (!parentDevice) + return std::unexpected { parentDevice.error() }; + if (*childDevice == *parentDevice) + return std::nullopt; + // Nothing here says whether the step left from the mount's root: below it (fail closed). + return std::optional { MountCrossing { .mount = viewOn(*childDevice), + .exit = MountExit::BelowRoot, + .skipped = {}, + .skippedSet = SkippedSet::Unknown } }; + } + + [[nodiscard]] FsResult mountOf(int handle) const override + { + return deviceOf(handle).transform(viewOn); + } + + [[nodiscard]] FsResult> mountTable() const override + { + // No table to read: a mount beneath either directory cannot be ruled out (fail closed). + return std::unexpected { FsError { .code = FsErrorCode::Unsupported, + .systemCode = 0, + .context = "this system lists no mounts" } }; + } + }; + +} // namespace + +std::shared_ptr makeMountBoundaries() +{ + return std::make_shared(); +} + +} // namespace core::fs::detail diff --git a/src/core/fs/posix/MountBoundaries.hpp b/src/core/fs/posix/MountBoundaries.hpp new file mode 100644 index 00000000..1ed61961 --- /dev/null +++ b/src/core/fs/posix/MountBoundaries.hpp @@ -0,0 +1,198 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// Where the POSIX relation walk leaves a mount, and whether the mount it leaves hides real parents +/// that the other directory could be. +/// - A mount that shows a subtree of its file system -- a bind mount of a subdirectory or a btrfs +/// subvolume (Linux), a nullfs mount (FreeBSD) -- has a `..` at its root that leads to the +/// directory it is mounted on, so the directories of that file system above the subtree are never +/// seen. Each of them is on the left mount's own file system and reached through some other +/// mount; so a walk's `Unrelated` still stands where the other directory is on the left mount +/// itself, or on another file system. +/// - A macOS firmlink (`/Users` on the Data volume) leaves a mount below its root: its `..` is the +/// system volume's root. The directories skipped are the mount's own above the one left from, +/// and every directory on its mount point's path below `/` (`/System`, `/System/Volumes`, and +/// `/System/Volumes/Data`, the mount's root): read by identity where they can be, and any +/// directory may be one where they cannot. +/// - A file system that may show another's directories as its own (overlay, FUSE, nullfs, a network +/// share that may export this machine) has no identity that says what it shows: a walk that +/// leaves one, or meets a directory on one, decides only on that same mount. +/// - Walks up never see a mount BENEATH either directory: a bind mount of the other's file system +/// below one of them puts the other inside it all the same. So an `Unrelated` also scans the mount +/// table (@c IMountBoundaries::mountTable) for mounts beneath each, and stands only where every one +/// is of a file system that shows nothing of the other's. +/// One implementation per OS, chosen by CMake. Private to the fs module. + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace core::fs::detail +{ + +/// Whether a mount's file system may show another file system's directories as its own. +enum class Reexposure : std::uint8_t +{ + Possible, ///< Overlay, FUSE, nullfs, a network share, or a type that cannot be read. + Impossible, ///< A file system that shows only its own directories. +}; + +/// What a relation walk knows about one mount: each part is nullopt where this system cannot tell +/// it, which decides nothing (fail closed). +struct MountView +{ + /// Names the mount; one name, one mount. Linux: its mount id; macOS and the BSDs: where it is + /// mounted and its file system id. + std::optional mount; + /// Names the file system the mount shows a directory of: Linux's superblock device from + /// mountinfo, never a btrfs subvolume's `st_dev`; elsewhere `st_dev`. + std::optional fileSystem; + /// The directory of that file system the mount shows, as an absolute path: `/` for all of it. + std::optional root; + /// Whether its file system may show another's directories. + Reexposure reexposure = Reexposure::Possible; + + [[nodiscard]] bool operator==(MountView const&) const = default; +}; + +/// Where a walk left a mount. +enum class MountExit : std::uint8_t +{ + BelowRoot, ///< From a directory below its root (a macOS firmlink), or where that cannot be told. + AtRoot, ///< From its root, to the directory it is mounted on. +}; + +/// How much of what a step below a mount's root skipped is known. +enum class SkippedSet : std::uint8_t +{ + Unknown, ///< Nothing could be read: any directory may have been skipped. + AtLeast, ///< @c MountCrossing::skipped, and the mount's own directories above the one left from. + Exactly, ///< @c MountCrossing::skipped and nothing else: the one left from is a child of the root. +}; + +/// One step of a walk that left a mount. +struct MountCrossing +{ + MountView mount; ///< The mount left. + MountExit exit = MountExit::BelowRoot; ///< Where it was left. + /// Below the root only: the directories the step skipped, by identity -- each directory on the + /// mount point's path below `/`, the last of them the mount's root as that path reaches it. + /// Ignored at the root. + std::vector skipped; + SkippedSet skippedSet = SkippedSet::Unknown; ///< How much of what was skipped @c skipped is. + + [[nodiscard]] bool operator==(MountCrossing const&) const = default; +}; + +/// Whether the other directory's walk passed through the directory a crossing left from. +enum class PassesThrough : std::uint8_t +{ + No, + Yes, +}; + +/// The other directory of a relation, as a crossing's check sees it. +struct HidingCandidate +{ + MountView mount; ///< The mount it is on. + ObjectIdentity identity; ///< Its own identity. + PassesThrough passes = PassesThrough::No; ///< Whether its walk passed the one the crossing left from. +}; + +/// Decides whether @p other could be one of the directories @p left skipped or hides. +/// @param left A mount a walk left. +/// @param other The other directory. +/// @return For a crossing below its root that @p other's walk did not pass: true where nothing of +/// what was skipped could be read, where @p other is one of the directories known skipped, +/// or (unless all skipped is known) where @p other is on the mount left. On the mount left, +/// false otherwise. Then true where either may re-expose another file system (unless +/// @p left shows its own file system whole, from its root); false where the two are on +/// different file systems, or (left at its root) @p other shows a directory not above +/// @p left's root; true otherwise, and wherever a part needed is unknown. +[[nodiscard]] CORE_FS_API bool mayHide(MountCrossing const& left, HidingCandidate const& other); + +/// Opens @p name in @p directory as a directory, never following a link, and only as the directory +/// a stat of the name identified: the beneath scan's step, between whose `fstatat` and `openat` a +/// rename can put another directory under the name. +/// @param directory Where @p name is. +/// @param name One component. +/// @param expected What the stat of @p name answered. +/// @return The opened directory; `Busy` where it is not @p expected; otherwise what refused the open. +[[nodiscard]] CORE_FS_API FsResult openNamedAs(int directory, + std::string const& name, + ObjectIdentity const& expected); + +/// How a @c ReexposingType's name matches a mount's type. +enum class TypeMatch : std::uint8_t +{ + Exact, ///< The type is the name. + Family, ///< The type starts with the name (`fuse` for `fuse.sshfs` and `fuseblk`). +}; + +/// A file system type, or a family of them, that may re-expose another file system. +struct ReexposingType +{ + std::string_view name; ///< The type, or the prefix of a family. + TypeMatch match = TypeMatch::Exact; ///< How @c name matches. +}; + +/// @param table The types a system names as re-exposing. +/// @param type A mount's type. +/// @return `Possible` where @p type is in @p table, or empty (unreadable); `Impossible` otherwise. +[[nodiscard]] CORE_FS_API Reexposure reexposureOf(std::span table, + std::string_view type); + +/// One row of this process's mount table, as the scan for mounts beneath a directory reads it. +struct MountTableRow +{ + /// Where the mount is, absolute, as this process sees it. + std::string path; + /// Its name, as @c MountView::mount spells it for a directory on it; nullopt where it has none. + std::optional mount; + + [[nodiscard]] bool operator==(MountTableRow const&) const = default; +}; + +/// Reads the mounts of a relation walk. +class IMountBoundaries +{ + public: + IMountBoundaries() = default; + IMountBoundaries(IMountBoundaries const&) = delete; + IMountBoundaries(IMountBoundaries&&) = delete; + IMountBoundaries& operator=(IMountBoundaries const&) = delete; + IMountBoundaries& operator=(IMountBoundaries&&) = delete; + virtual ~IMountBoundaries() = default; + + /// Checks the step from @p child to @p parent, its `..`. + /// @param child A directory the walk is at. + /// @param parent What its `..` opened. + /// @return Nullopt where both are on one mount; otherwise the mount @p child is on, which the + /// step leaves, and whether @p child is its root; or what refused reading them. + [[nodiscard]] virtual FsResult> crossing(int child, int parent) const = 0; + + /// @param handle A directory. + /// @return The mount it is on, or what refused reading it. + [[nodiscard]] virtual FsResult mountOf(int handle) const = 0; + + /// @return Every mount this process sees, in the table's order; or what refused reading the + /// table. Nothing may be missing from it: a row that does not parse refuses the whole. + [[nodiscard]] virtual FsResult> mountTable() const = 0; +}; + +/// @return This system's boundaries, made when a file system is built (`linux/`, `bsd/` or +/// `posix/MountBoundaries.cpp`); null where they cannot be read, so that every relation is +/// `Unsupported`. +[[nodiscard]] CORE_FS_API std::shared_ptr makeMountBoundaries(); + +} // namespace core::fs::detail diff --git a/src/core/fs/posix/MountBoundaries_test.cpp b/src/core/fs/posix/MountBoundaries_test.cpp new file mode 100644 index 00000000..0d7ff37f --- /dev/null +++ b/src/core/fs/posix/MountBoundaries_test.cpp @@ -0,0 +1,854 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// What a POSIX relation walk decides from the mounts it leaves (mayHide, the table every system's +// boundaries feed), and the walk itself under scripted boundaries: a mount left that may hide the +// other directory turns `Unrelated` into `Unsupported`, and a rename between the two passes is +// `Busy`. +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +using core::fs::FsErrorCode; +using core::fs::FsResult; +using core::fs::Relation; +using core::fs::detail::HidingCandidate; +using core::fs::detail::IMountBoundaries; +using core::fs::detail::mayHide; +using core::fs::detail::MountCrossing; +using core::fs::detail::MountExit; +using core::fs::detail::MountTableRow; +using core::fs::detail::MountView; +using core::fs::detail::ObjectIdentity; +using core::fs::detail::openNamedAs; +using core::fs::detail::PassesThrough; +using core::fs::detail::Reexposure; +using core::fs::detail::SkippedSet; +using core::fs::detail::UniqueHandle; + +namespace +{ + +/// One row of the hiding table: a mount left, the other directory's mount, whether the other walk +/// passed the directory left from, the answer, and the other directory's identity. +struct HidingRow +{ + char const* name; + MountCrossing left; + MountView other; + PassesThrough passes; + bool hides; + ObjectIdentity identity; +}; + +/// Identities of a scripted macOS: /System and /System/Volumes on the system volume (device 8), +/// the Data volume's root (device 7), and a directory that is none of them. +constexpr auto SystemDirectory = ObjectIdentity { .device = 8, .idLow = 10, .idHigh = 0 }; +constexpr auto VolumesDirectory = ObjectIdentity { .device = 8, .idLow = 11, .idHigh = 0 }; +constexpr auto DataRoot = ObjectIdentity { .device = 7, .idLow = 2, .idHigh = 0 }; +constexpr auto Elsewhere = ObjectIdentity { .device = 99, .idLow = 99, .idHigh = 0 }; + +[[nodiscard]] MountView linuxMount(char const* id, + std::uint64_t fileSystem, + char const* root, + Reexposure reexposure = Reexposure::Impossible) +{ + return MountView { .mount = id, .fileSystem = fileSystem, .root = root, .reexposure = reexposure }; +} + +[[nodiscard]] MountView bsdMount(char const* name, + std::uint64_t fileSystem, + Reexposure reexposure = Reexposure::Impossible) +{ + return MountView { + .mount = name, .fileSystem = fileSystem, .root = std::nullopt, .reexposure = reexposure + }; +} + +[[nodiscard]] MountCrossing atRoot(MountView mount) +{ + return MountCrossing { + .mount = std::move(mount), .exit = MountExit::AtRoot, .skipped = {}, .skippedSet = SkippedSet::Unknown + }; +} + +/// @return A crossing below @p mount's root that skipped @p skipped, known as far as @p known says. +[[nodiscard]] MountCrossing belowRoot(MountView mount, std::vector skipped, SkippedSet known) +{ + return MountCrossing { .mount = std::move(mount), + .exit = MountExit::BelowRoot, + .skipped = std::move(skipped), + .skippedSet = known }; +} + +/// @return A firmlink crossing of the Data volume whose skipped directories are all known. +[[nodiscard]] MountCrossing firmlink(MountView data, SkippedSet known = SkippedSet::Exactly) +{ + return belowRoot(std::move(data), { SystemDirectory, VolumesDirectory, DataRoot }, known); +} + +/// A directory's device and inode. +using DirectoryIdentity = std::pair; + +/// Boundaries a test scripts: every step stays on one mount but the one from @c crossingAt, which +/// leaves @c left; every directory is on @c others but those @c mountsAt names; @c onStep runs at +/// each step, numbered from zero, before it is answered; and @c table answers each read of the mount +/// table, numbered from zero (none: an empty table). +class ScriptedBoundaries final: public IMountBoundaries +{ + public: + struct Script + { + std::optional crossingAt; + MountCrossing left; + MountView others; + std::function onStep; + std::function>(std::size_t)> table; + std::vector> mountsAt; + }; + + explicit ScriptedBoundaries(Script script): _script { std::move(script) } {} + + [[nodiscard]] FsResult> crossing(int child, int /*parent*/) const override + { + if (_script.onStep) + _script.onStep(_steps); + ++_steps; + struct ::stat status {}; + REQUIRE(::fstat(child, &status) == 0); + auto const here = std::pair { static_cast(status.st_dev), + static_cast(status.st_ino) }; + if (_script.crossingAt == here) + return std::optional { _script.left }; + return std::nullopt; + } + + [[nodiscard]] FsResult mountOf(int handle) const override + { + struct ::stat status {}; + REQUIRE(::fstat(handle, &status) == 0); + auto const here = DirectoryIdentity { static_cast(status.st_dev), + static_cast(status.st_ino) }; + auto const named = + std::ranges::find(_script.mountsAt, here, [](auto const& row) { return row.first; }); + return named != _script.mountsAt.end() ? named->second : _script.others; + } + + [[nodiscard]] FsResult> mountTable() const override + { + auto const read = _tableReads++; + return _script.table ? _script.table(read) : std::vector {}; + } + + /// @return How many steps have been checked. + [[nodiscard]] std::size_t steps() const noexcept { return _steps; } + + private: + Script _script; + mutable std::size_t _steps = 0; + mutable std::size_t _tableReads = 0; +}; + +/// A native file system's context with @p boundaries, and what it is built from. +class ScriptedContext +{ + public: + explicit ScriptedContext(std::shared_ptr boundaries): + _context { _home, _blocking, _clock, _random, {}, + "/", nullptr, nullptr, nullptr, std::move(boundaries) } + { + } + + /// @return How @p first and @p second relate, walked natively. + [[nodiscard]] FsResult relation(std::filesystem::path const& first, + std::filesystem::path const& second) const + { + auto const a = openDirectory(first); + auto const b = openDirectory(second); + return core::fs::detail::nativeRelation(_context, a.get(), b.get()); + } + + private: + [[nodiscard]] static UniqueHandle openDirectory(std::filesystem::path const& path) + { + auto handle = UniqueHandle { ::open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC) }; + REQUIRE(handle.get() >= 0); + return handle; + } + + core::async::testing::ManualExecutor _home; + core::async::testing::ManualExecutor _blocking; + core::platform::ManualWallClock _clock; + core::fs::test::FixedRandom _random { 1 }; + core::fs::detail::NativeContext _context; +}; + +[[nodiscard]] std::pair identityOf(std::filesystem::path const& path) +{ + struct ::stat status {}; + REQUIRE(::stat(path.c_str(), &status) == 0); + return { static_cast(status.st_dev), static_cast(status.st_ino) }; +} + +[[nodiscard]] ObjectIdentity objectIdentityOf(std::filesystem::path const& path) +{ + auto const [device, inode] = identityOf(path); + return ObjectIdentity { .device = device, .idLow = inode, .idHigh = 0 }; +} + +[[nodiscard]] bool isError(FsResult const& answer, FsErrorCode code) +{ + return !answer.has_value() && answer.error().code == code; +} + +} // namespace + +TEST_CASE("mayHide: what a mount left can hide", "[fs][relation]") +{ + using enum PassesThrough; + auto const overlay = Reexposure::Possible; + auto const rows = std::to_array({ + // Linux: mount ids, the superblock device, the root column; `..` leaves only at a root. + { "a whole file system hides nothing", + atRoot(linuxMount("35", 1, "/")), + linuxMount("22", 1, "/"), + No, + false, + Elsewhere }, + { "a sub-bind hides the mount of its whole file system", + atRoot(linuxMount("61", 1, "/a/sub")), + linuxMount("22", 1, "/"), + No, + true, + Elsewhere }, + { "a sub-bind hides nothing from a directory on itself", + atRoot(linuxMount("61", 1, "/a/sub")), + linuxMount("61", 1, "/a/sub"), + No, + false, + Elsewhere }, + { "a sub-bind hides nothing from another file system", + atRoot(linuxMount("61", 1, "/a/sub")), + linuxMount("35", 2, "/"), + No, + false, + Elsewhere }, + { "a subvolume hides nothing from a sibling subvolume", + atRoot(linuxMount("69", 3, "/home")), + linuxMount("70", 3, "/root"), + No, + false, + Elsewhere }, + { "a nested subvolume is hidden by its parent's mount", + atRoot(linuxMount("71", 3, "/root/var")), + linuxMount("70", 3, "/root"), + No, + true, + Elsewhere }, + { "a second bind of the same subtree is not above it", + atRoot(linuxMount("72", 1, "/a/sub")), + linuxMount("61", 1, "/a/sub"), + No, + false, + Elsewhere }, + { "a bind of a subtree below is not above it", + atRoot(linuxMount("61", 1, "/a/sub")), + linuxMount("73", 1, "/a/sub/deeper"), + No, + false, + Elsewhere }, + { "a path sharing only a prefix of letters is not above", + atRoot(linuxMount("61", 1, "/a/sub")), + linuxMount("74", 1, "/a/su"), + No, + false, + Elsewhere }, + { "an unknown root hides", + atRoot( + MountView { .mount = "61", .fileSystem = 1, .root = {}, .reexposure = Reexposure::Impossible }), + linuxMount("22", 1, "/"), + No, + true, + Elsewhere }, + { "an unknown file system hides", + atRoot(MountView { + .mount = "61", .fileSystem = {}, .root = {}, .reexposure = Reexposure::Impossible }), + linuxMount("22", 1, "/"), + No, + true, + Elsewhere }, + // A file system that may re-expose another's: only its own mount decides. + { "an overlay left hides from another file system", + atRoot(linuxMount("80", 5, "/", overlay)), + linuxMount("22", 1, "/"), + No, + true, + Elsewhere }, + { "an overlay left hides nothing from a directory on itself", + atRoot(linuxMount("80", 5, "/", overlay)), + linuxMount("80", 5, "/", overlay), + No, + false, + Elsewhere }, + { "a FUSE mount left hides from another file system", + atRoot(linuxMount("81", 6, "/", overlay)), + linuxMount("35", 2, "/"), + No, + true, + Elsewhere }, + { "a directory on an overlay may be what a sub-bind hides", + atRoot(linuxMount("61", 1, "/a/sub")), + linuxMount("80", 5, "/", overlay), + No, + true, + Elsewhere }, + { "a whole file system hides nothing, even from an overlay", + atRoot(linuxMount("35", 2, "/")), + linuxMount("80", 5, "/", overlay), + No, + false, + Elsewhere }, + // macOS and the BSDs: no root is known, so only the mount or the file system decides. + { "BSD: the same mount", + atRoot(bsdMount("1:2:/Volumes/Data", 7)), + bsdMount("1:2:/Volumes/Data", 7), + No, + false, + Elsewhere }, + { "BSD: another file system", + atRoot(bsdMount("1:2:/Volumes/Data", 7)), + bsdMount("3:4:/", 8), + No, + false, + Elsewhere }, + { "BSD: one file system through another mount", + atRoot(bsdMount("1:2:/mnt/a", 7)), + bsdMount("3:4:/", 7), + No, + true, + Elsewhere }, + { "BSD: a nullfs mount and anything else", + atRoot(bsdMount("5:6:/mnt/null", 9, overlay)), + bsdMount("3:4:/", 8), + No, + true, + Elsewhere }, + { "BSD: a nullfs mount and itself", + atRoot(bsdMount("5:6:/mnt/null", 9, overlay)), + bsdMount("5:6:/mnt/null", 9, overlay), + No, + false, + Elsewhere }, + // A macOS firmlink: the Data volume left at /Users, below its root, skipping /System, + // /System/Volumes and the Data root. + { "firmlink: the Data root, not passed", + firmlink(bsdMount("1:2:/System/Volumes/Data", 7)), + bsdMount("1:2:/System/Volumes/Data", 7), + No, + true, + DataRoot }, + { "firmlink: a directory beneath the firmlink", + firmlink(bsdMount("1:2:/System/Volumes/Data", 7)), + bsdMount("1:2:/System/Volumes/Data", 7), + Yes, + false, + Elsewhere }, + { "firmlink: another directory on the Data volume, all skipped known", + firmlink(bsdMount("1:2:/System/Volumes/Data", 7)), + bsdMount("1:2:/System/Volumes/Data", 7), + No, + false, + Elsewhere }, + { "firmlink: another directory on the Data volume, more skipped than known", + firmlink(bsdMount("1:2:/System/Volumes/Data", 7), SkippedSet::AtLeast), + bsdMount("1:2:/System/Volumes/Data", 7), + No, + true, + Elsewhere }, + { "firmlink: /System/Volumes, on the parent mount and another device", + firmlink(bsdMount("1:2:/System/Volumes/Data", 7)), + bsdMount("3:4:/", 8), + No, + true, + VolumesDirectory }, + { "firmlink: /System, on the parent mount and another device", + firmlink(bsdMount("1:2:/System/Volumes/Data", 7)), + bsdMount("3:4:/", 8), + No, + true, + SystemDirectory }, + { "firmlink: an unrelated directory on the parent mount", + firmlink(bsdMount("1:2:/System/Volumes/Data", 7)), + bsdMount("3:4:/", 8), + No, + false, + Elsewhere }, + { "firmlink: a mount point's path that could not be read", + belowRoot(bsdMount("1:2:/System/Volumes/Data", 7), {}, SkippedSet::Unknown), + bsdMount("3:4:/", 8), + No, + true, + Elsewhere }, + { "firmlink: the same file system through another mount, more skipped than known", + firmlink(bsdMount("1:2:/System/Volumes/Data", 7), SkippedSet::AtLeast), + bsdMount("3:4:/Volumes/Again", 7), + No, + true, + Elsewhere }, + { "firmlink: the same file system through another mount, all skipped known", + firmlink(bsdMount("1:2:/System/Volumes/Data", 7)), + bsdMount("3:4:/Volumes/Again", 7), + No, + false, + Elsewhere }, + { "below the root of a whole file system on Linux terms", + belowRoot(linuxMount("35", 2, "/"), {}, SkippedSet::Unknown), + linuxMount("22", 2, "/"), + No, + true, + Elsewhere }, + // A system that names no mount and no type: the device alone, and it fails closed. + { "device only: another device", + belowRoot(MountView { .mount = {}, .fileSystem = 1, .root = {}, .reexposure = overlay }, + {}, + SkippedSet::Unknown), + MountView { .mount = {}, .fileSystem = 2, .root = {}, .reexposure = overlay }, + No, + true, + Elsewhere }, + }); + for (auto const& row: rows) + { + INFO(row.name); + CHECK(mayHide(row.left, + HidingCandidate { .mount = row.other, .identity = row.identity, .passes = row.passes }) + == row.hides); + } +} + +TEST_CASE("reexposureOf: the types that may show another file system", "[fs][relation]") +{ + using core::fs::detail::ReexposingType; + using core::fs::detail::reexposureOf; + using core::fs::detail::TypeMatch; + constexpr auto Table = std::to_array({ + { .name = "overlay", .match = TypeMatch::Exact }, + { .name = "fuse", .match = TypeMatch::Family }, + }); + CHECK(reexposureOf(Table, "overlay") == Reexposure::Possible); + CHECK(reexposureOf(Table, "overlayfs") == Reexposure::Impossible); // exact, not a prefix + CHECK(reexposureOf(Table, "fuse") == Reexposure::Possible); + CHECK(reexposureOf(Table, "fuse.sshfs") == Reexposure::Possible); + CHECK(reexposureOf(Table, "fuseblk") == Reexposure::Possible); + CHECK(reexposureOf(Table, "ext4") == Reexposure::Impossible); + CHECK(reexposureOf(Table, "") == Reexposure::Possible); // unreadable +} + +TEST_CASE("relation: a mount left that may hide the other directory is Unsupported", "[fs][native][relation]") +{ + // m is scripted as a mount the walk from m/key leaves; p lies beside m, on the mount the script + // names. The walks meet no containment, so the mount decides. + auto const fixture = core::fs::test::DescriptorFixture::createNative(); + auto const& host = fixture.hostDirectory(); + std::filesystem::create_directories(host / "m" / "key"); + std::filesystem::create_directories(host / "p"); + struct Row + { + char const* name; + MountCrossing left; + MountView others; + std::optional refusal; + }; + auto const rows = std::to_array({ + { "p on the mount left", atRoot(bsdMount("1:2:/m", 7)), bsdMount("1:2:/m", 7), std::nullopt }, + { "p on another file system", atRoot(bsdMount("1:2:/m", 7)), bsdMount("3:4:/", 8), std::nullopt }, + { "p on the same file system through another mount", + atRoot(bsdMount("1:2:/m", 7)), + bsdMount("3:4:/", 7), + FsErrorCode::Unsupported }, + { "m an overlay, p on another file system", + atRoot(linuxMount("80", 5, "/", Reexposure::Possible)), + linuxMount("22", 1, "/"), + FsErrorCode::Unsupported }, + { "m a FUSE mount, p on another file system", + atRoot(bsdMount("7:8:/m", 9, Reexposure::Possible)), + bsdMount("3:4:/", 8), + FsErrorCode::Unsupported }, + }); + for (auto const& row: rows) + { + INFO(row.name); + auto const context = ScriptedContext { std::make_shared( + ScriptedBoundaries::Script { .crossingAt = identityOf(host / "m"), + .left = row.left, + .others = row.others, + .onStep = {}, + .table = {}, + .mountsAt = {} }) }; + auto const keyFirst = context.relation(host / "m" / "key", host / "p"); + auto const keySecond = context.relation(host / "p", host / "m" / "key"); + if (row.refusal) + { + CHECK(isError(keyFirst, *row.refusal)); + CHECK(isError(keySecond, *row.refusal)); + } + else + { + CHECK((keyFirst && *keyFirst == Relation::Unrelated)); + CHECK((keySecond && *keySecond == Relation::Unrelated)); + } + // A containment the walks meet stands, whatever the mount. + auto const contained = context.relation(host / "m", host / "m" / "key"); + CHECK((contained && *contained == Relation::FirstContainsSecond)); + } +} + +TEST_CASE("relation: a mount left below its root, as at a macOS firmlink", "[fs][native][relation]") +{ + // sys/vol/d stands for /System/Volumes/Data, d for the Data volume's root, and u for /Users. The + // host's real `..` cannot skip a parent, so u lies beside them, as the system volume's /Users + // does: the walk from u/me leaves d's mount at u, below its root, and skips sys, sys/vol and d. + // Every directory is scripted on the mount a row names. + auto const fixture = core::fs::test::DescriptorFixture::createNative(); + auto const& host = fixture.hostDirectory(); + for (auto const* directory: { "sys/vol/d", "u/me", "u/foo", "elsewhere" }) + std::filesystem::create_directories(host / directory); + auto const data = bsdMount("1:2:/System/Volumes/Data", 7); + auto const parentMount = bsdMount("3:4:/", 8); + auto const skipped = std::vector { objectIdentityOf(host / "sys"), + objectIdentityOf(host / "sys" / "vol"), + objectIdentityOf(host / "sys" / "vol" / "d") }; + auto const scripted = [&](SkippedSet known, MountView const& others) { + return std::make_shared( + ScriptedBoundaries::Script { .crossingAt = identityOf(host / "u"), + .left = belowRoot(data, skipped, known), + .others = others, + .onStep = {}, + .table = {}, + .mountsAt = {} }); + }; + struct Row + { + char const* name; + SkippedSet known; + MountView const* others; + char const* grant; + std::optional refusal; + }; + auto const rows = std::to_array({ + { "the Data root", SkippedSet::Exactly, &data, "sys/vol/d", FsErrorCode::Unsupported }, + { "another directory on the Data volume, all skipped known", + SkippedSet::Exactly, + &data, + "elsewhere", + std::nullopt }, + { "another directory on the Data volume, more skipped than known", + SkippedSet::AtLeast, + &data, + "elsewhere", + FsErrorCode::Unsupported }, + { "a directory on the mount point's path, on the parent mount", + SkippedSet::Exactly, + &parentMount, + "sys/vol", + FsErrorCode::Unsupported }, + { "the top of the mount point's path, on the parent mount", + SkippedSet::Exactly, + &parentMount, + "sys", + FsErrorCode::Unsupported }, + { "an unrelated directory on the parent mount", + SkippedSet::Exactly, + &parentMount, + "elsewhere", + std::nullopt }, + { "an unrelated directory, the mount point's path unread", + SkippedSet::Unknown, + &parentMount, + "elsewhere", + FsErrorCode::Unsupported }, + }); + for (auto const& row: rows) + { + INFO(row.name); + auto const context = ScriptedContext { scripted(row.known, *row.others) }; + auto const grantFirst = context.relation(host / row.grant, host / "u" / "me"); + auto const keyFirst = context.relation(host / "u" / "me", host / row.grant); + if (row.refusal) + { + CHECK(isError(grantFirst, *row.refusal)); + CHECK(isError(keyFirst, *row.refusal)); + } + else + { + CHECK((grantFirst && *grantFirst == Relation::Unrelated)); + CHECK((keyFirst && *keyFirst == Relation::Unrelated)); + } + // Both beneath the firmlink: both walks pass it, so the answer stands whatever is known. + auto const siblings = context.relation(host / "u" / "foo", host / "u" / "me"); + CHECK((siblings && *siblings == Relation::Unrelated)); + } +} + +TEST_CASE("relation: a move between the two passes is Busy", "[fs][native][relation]") +{ + // x/a and y are unrelated in the first pass. At the first step of the second, x moves into y, so + // the second pass walks a up through y: the passes differ, and the answer is Busy, never the + // first pass's Unrelated. + auto const fixture = core::fs::test::DescriptorFixture::createNative(); + auto const& host = fixture.hostDirectory(); + std::filesystem::create_directories(host / "x" / "a"); + std::filesystem::create_directories(host / "y"); + + // A pass is as many steps as both chains are long below the root: counted once, unscripted. + auto const counter = std::make_shared(ScriptedBoundaries::Script {}); + auto const unscripted = ScriptedContext { counter }.relation(host / "x" / "a", host / "y"); + REQUIRE((unscripted && *unscripted == Relation::Unrelated)); + auto const pass = counter->steps() / 2; + REQUIRE(pass > 0); + + auto moved = false; + auto const mover = std::make_shared( + ScriptedBoundaries::Script { .crossingAt = std::nullopt, + .left = {}, + .others = {}, + .onStep = + [&](std::size_t step) { + if (step != pass) + return; + std::filesystem::rename(host / "x", host / "y" / "x"); + moved = true; + }, + .table = {}, + .mountsAt = {} }); + auto const answer = ScriptedContext { mover }.relation(host / "x" / "a", host / "y"); + REQUIRE(moved); + CHECK(isError(answer, FsErrorCode::Busy)); +} + +TEST_CASE("relation across this system's own mounts", "[fs][native][relation]") +{ + // /dev is a mount of its own on Linux (devtmpfs), macOS and the BSDs (devfs): a walk leaves it + // for the root, and the fixture's directory is on another file system, which nothing /dev + // could hide is on. With the native boundaries -- statfs on macOS and the BSDs, mountinfo on + // Linux -- that is Unrelated, never a refusal; and the root contains /dev. + auto const devStatus = [] { + struct ::stat status {}; + return ::stat("/dev", &status) == 0 ? std::optional { status.st_dev } : std::nullopt; + }(); + auto const rootStatus = [] { + struct ::stat status {}; + return ::stat("/", &status) == 0 ? std::optional { status.st_dev } : std::nullopt; + }(); + if (!devStatus || !rootStatus || *devStatus == *rootStatus) + SKIP("/dev is not a mount of its own here"); + auto fixture = core::fs::test::DescriptorFixture::createNative(); + auto& system = fixture.fileSystem(); + auto const dev = fixture.run(system.openPreopen("/dev", core::fs::DescriptorFlags::Read)); + auto const root = fixture.run(system.openPreopen("/", core::fs::DescriptorFlags::Read)); + REQUIRE(dev.has_value()); + REQUIRE(root.has_value()); + auto const fromDev = fixture.run(system.relation(**dev, fixture.root())); + INFO((fromDev ? std::string { "decided" } : fromDev.error().toString())); + CHECK((fromDev && *fromDev == Relation::Unrelated)); + auto const fromRoot = fixture.run(system.relation(**root, **dev)); + CHECK((fromRoot && *fromRoot == Relation::FirstContainsSecond)); +} + +TEST_CASE("relation: a mount beneath either directory that may show the other's file system", + "[fs][native][relation]") +{ + // g and k/secret lie side by side on one file system, so neither walk up meets the other. The + // table names a mount at g/inner -- beneath g -- and the scan opens it: where its file system is + // the key's, or may show another's, the key may be reached through g, and Unrelated cannot stand. + auto const fixture = core::fs::test::DescriptorFixture::createNative(); + auto const& host = fixture.hostDirectory(); + std::filesystem::create_directories(host / "g" / "inner" / "deeper"); + std::filesystem::create_directories(host / "k" / "secret"); + auto const keyFileSystem = bsdMount("1:2:/", 7); + struct Row + { + char const* name; + char const* mountPoint; ///< Beneath the host, where the table says it is. + std::optional tableName; ///< The name the table gives it. + MountView mounted; ///< What opening it finds. + std::optional refusal; + }; + auto const rows = std::to_array({ + { "the key's file system beneath the grant", + "g/inner", + "1:2:/g/inner", + bsdMount("1:2:/g/inner", 7), + FsErrorCode::Unsupported }, + { "a file system that may show another's beneath the grant", + "g/inner", + "5:6:/g/inner", + bsdMount("5:6:/g/inner", 9, Reexposure::Possible), + FsErrorCode::Unsupported }, + { "a file system of its own beneath the grant", + "g/inner", + "5:6:/g/inner", + bsdMount("5:6:/g/inner", 9), + std::nullopt }, + { "the key's file system deeper beneath the grant", + "g/inner/deeper", + "1:2:/g/inner/deeper", + bsdMount("1:2:/g/inner/deeper", 7), + FsErrorCode::Unsupported }, + { "a path that opens onto another mount than the table's", + "g/inner", + "8:8:/g/inner", + bsdMount("1:2:/g/inner", 9), + FsErrorCode::Unsupported }, + { "the key's file system beside the grant", "k", "1:2:/k", bsdMount("1:2:/k", 7), std::nullopt }, + }); + for (auto const& row: rows) + { + INFO(row.name); + // As a mount table names it: the path with no link in it (macOS's /var is one). + auto const mountPoint = std::filesystem::canonical(host / row.mountPoint).string(); + auto const context = + ScriptedContext { std::make_shared(ScriptedBoundaries::Script { + .crossingAt = std::nullopt, + .left = {}, + .others = keyFileSystem, + .onStep = {}, + .table = + [&](std::size_t) { + return std::vector { MountTableRow { .path = mountPoint, .mount = row.tableName } }; + }, + .mountsAt = { { identityOf(host / row.mountPoint), row.mounted } } }) }; + auto const grantFirst = context.relation(host / "g", host / "k" / "secret"); + auto const keyFirst = context.relation(host / "k" / "secret", host / "g"); + if (row.refusal) + { + CHECK(isError(grantFirst, *row.refusal)); + CHECK(isError(keyFirst, *row.refusal)); + } + else + { + CHECK((grantFirst && *grantFirst == Relation::Unrelated)); + CHECK((keyFirst && *keyFirst == Relation::Unrelated)); + } + } +} + +TEST_CASE("relation: a mount point beneath a directory that cannot be read is Unsupported", + "[fs][native][relation]") +{ + auto const fixture = core::fs::test::DescriptorFixture::createNative(); + auto const& host = fixture.hostDirectory(); + std::filesystem::create_directories(host / "g"); + std::filesystem::create_directories(host / "k"); + auto const missing = (std::filesystem::canonical(host / "g") / "gone").string(); + auto const context = + ScriptedContext { std::make_shared(ScriptedBoundaries::Script { + .crossingAt = std::nullopt, + .left = {}, + .others = bsdMount("1:2:/", 7), + .onStep = {}, + .table = + [&](std::size_t) { + return std::vector { MountTableRow { .path = missing, .mount = "1:2:/g/gone" } }; + }, + .mountsAt = {} }) }; + auto const answer = context.relation(host / "g", host / "k"); + REQUIRE_FALSE(answer.has_value()); + CHECK(answer.error().code != FsErrorCode::Busy); +} + +TEST_CASE("the beneath scan opens a component only as the directory it identified", "[fs][native][relation]") +{ + // The scan identifies a component with fstatat and then opens it by name. A rename in between + // makes the name another directory's: the opened handle's identity is not the one checked, and + // the answer is Busy rather than a scan continued through a directory it never identified. + auto const fixture = core::fs::test::DescriptorFixture::createNative(); + auto const& host = fixture.hostDirectory(); + std::filesystem::create_directories(host / "x"); + auto const parent = UniqueHandle { ::open(host.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC) }; + REQUIRE(parent.get() >= 0); + auto const identified = objectIdentityOf(host / "x"); + + SECTION("the name still names the directory identified") + { + auto const opened = openNamedAs(parent.get(), "x", identified); + REQUIRE(opened.has_value()); + CHECK(objectIdentityOf(host / "x") == identified); + } + + SECTION("the name was moved onto another directory in between") + { + std::filesystem::rename(host / "x", host / "moved"); + std::filesystem::create_directories(host / "x"); + auto const opened = openNamedAs(parent.get(), "x", identified); + REQUIRE_FALSE(opened.has_value()); + CHECK(opened.error().code == FsErrorCode::Busy); + } +} + +TEST_CASE("relation: a mount table that changes while it is scanned is Busy", "[fs][native][relation]") +{ + auto const fixture = core::fs::test::DescriptorFixture::createNative(); + auto const& host = fixture.hostDirectory(); + std::filesystem::create_directories(host / "g"); + std::filesystem::create_directories(host / "k"); + auto const context = + ScriptedContext { std::make_shared(ScriptedBoundaries::Script { + .crossingAt = std::nullopt, + .left = {}, + .others = bsdMount("1:2:/", 7), + .onStep = {}, + .table = [](std::size_t read) -> FsResult> { + // The first read sees nothing; a mount arrives before the read that confirms it. + auto rows = std::vector {}; + if (read > 0) + rows.push_back(MountTableRow { .path = "/nowhere", .mount = "9:9:/nowhere" }); + return rows; + }, + .mountsAt = {} }) }; + CHECK(isError(context.relation(host / "g", host / "k"), FsErrorCode::Busy)); +} + +TEST_CASE("relation: a mount table that cannot be read leaves no Unrelated standing", + "[fs][native][relation]") +{ + auto const fixture = core::fs::test::DescriptorFixture::createNative(); + auto const& host = fixture.hostDirectory(); + std::filesystem::create_directories(host / "g"); + std::filesystem::create_directories(host / "k"); + auto const context = + ScriptedContext { std::make_shared(ScriptedBoundaries::Script { + .crossingAt = std::nullopt, + .left = {}, + .others = bsdMount("1:2:/", 7), + .onStep = {}, + .table = [](std::size_t) -> FsResult> { + return std::unexpected { core::fs::FsError { + .code = FsErrorCode::Unsupported, .systemCode = 0, .context = "scripted" } }; + }, + .mountsAt = {} }) }; + CHECK(isError(context.relation(host / "g", host / "k"), FsErrorCode::Unsupported)); +} diff --git a/src/core/fs/posix/OwnerOnly_test.cpp b/src/core/fs/posix/OwnerOnly_test.cpp index c348b63b..65427619 100644 --- a/src/core/fs/posix/OwnerOnly_test.cpp +++ b/src/core/fs/posix/OwnerOnly_test.cpp @@ -427,3 +427,15 @@ TEST_CASE("posix: a staged creation under an inheritable ACL is owner-only", "[f CHECK(modeOf(held.directory.path() / "keys") == 0700); CHECK(held.names() == std::vector { "keys", "secret" }); } + +TEST_CASE("posix: who may reach an object is judged through a handle only", "[fs][native][access]") +{ + // Linux decides from the handle whether the mode bounds access at all (an NFS or SMB mount, an + // NFSv4 ACL); by name there is no handle to ask, so nothing is judged. + auto const directory = core::testing::ScopedTempDir { "core-cpp-fs-facts" }; + auto const path = directory.path() / "plain"; + std::ofstream { path } << "x"; + struct ::stat status {}; + REQUIRE(::stat(path.c_str(), &status) == 0); + CHECK_FALSE(core::fs::detail::accessFactsOf(core::platform::InvalidHandle, status).has_value()); +} diff --git a/src/core/fs/posix/PosixDescriptor.cpp b/src/core/fs/posix/PosixDescriptor.cpp index c7e2b1d1..a804b4af 100644 --- a/src/core/fs/posix/PosixDescriptor.cpp +++ b/src/core/fs/posix/PosixDescriptor.cpp @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -711,6 +712,9 @@ namespace if (resolved.name.empty()) return refuse(FsErrorCode::Invalid); return detail::readLinkAt(resolved.directory(), resolved.name); + }) + .and_then([&](std::string target) { + return detail::refuseRootedTarget(std::move(target), *context->policy); }); }); } @@ -918,6 +922,11 @@ namespace }); } + async::Task> relation(IDescriptor const& first, IDescriptor const& second) override + { + return detail::relationOf(_context, first, second); + } + private: SharedContext _context; }; @@ -941,7 +950,8 @@ FsResult> makeNativeDescriptorFileSystem( KernelSeparators, nullptr, nullptr, - std::make_shared(random, detail::nativeOwnerOnlyCreation()))); + std::make_shared(random, detail::nativeOwnerOnlyCreation()), + detail::makeMountBoundaries())); }); } diff --git a/src/core/fs/posix/PosixSystem.hpp b/src/core/fs/posix/PosixSystem.hpp index cc59765c..20a5c8a4 100644 --- a/src/core/fs/posix/PosixSystem.hpp +++ b/src/core/fs/posix/PosixSystem.hpp @@ -146,9 +146,11 @@ struct StatTimes } /// What the open object tells about who may reach it: its owner and mode, and where the system has -/// ACLs beyond the mode, its ACL read from the very handle (`posix/AccessFacts.cpp` on Linux, which -/// has none beyond the mode; `bsd/AccessFacts.cpp` on FreeBSD, NFSv4; `darwin/AccessFacts.cpp` on -/// macOS, extended). Never by name. +/// ACLs beyond the mode, its ACL read from the very handle (`linux/AccessFacts.cpp` on Linux, where +/// only an NFS or SMB mount or an NFSv4 ACL goes beyond the mode, and then nothing is judged; +/// `bsd/AccessFacts.cpp` on FreeBSD, NFSv4; `darwin/AccessFacts.cpp` on macOS, extended; +/// `posix/AccessFacts.cpp`, the mode alone, on OpenBSD and DragonFly; nothing judged on NetBSD and +/// elsewhere). Never by name. /// @param handle The open object, or @c platform::InvalidHandle where only @p status is at hand (a /// `statAt`, made by name with `fstatat`). /// @param status Its `fstat` (or `fstatat` without following). diff --git a/src/core/fs/posix/UnknownAccessFacts.cpp b/src/core/fs/posix/UnknownAccessFacts.cpp new file mode 100644 index 00000000..9b37fb02 --- /dev/null +++ b/src/core/fs/posix/UnknownAccessFacts.cpp @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// Who may reach an object where this module reads no ACL the system may keep: NetBSD, whose FFS keeps +// NFSv4 ACLs the mode does not bound, and any POSIX system CMake names no other file for. The mode +// alone could call an object owner-only that an ACL opens to anyone, so nothing is judged: every +// answer is nullopt, and an owner-only creation, which reads its access back, is refused. +#include +#include + +#include + +#include + +namespace core::fs::detail +{ + +std::optional accessFactsOf(int /*handle*/, struct ::stat const& /*status*/) +{ + return std::nullopt; +} + +} // namespace core::fs::detail diff --git a/src/core/fs/testing/InMemoryDescriptorFileSystem.cpp b/src/core/fs/testing/InMemoryDescriptorFileSystem.cpp index 5b317b34..4a9530e4 100644 --- a/src/core/fs/testing/InMemoryDescriptorFileSystem.cpp +++ b/src/core/fs/testing/InMemoryDescriptorFileSystem.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -80,6 +81,9 @@ struct InMemoryState FileTime statusChanged; DescriptorType type = DescriptorType::Unknown; AccessFacts access; ///< Who may reach it, as a native reader would have found it. + /// A directory's real parent: the root's is itself, and a directory removed or replaced has + /// none (0), as a native `..` of it finds nothing. + std::uint64_t parent = 0; }; /// Where a path resolved to: the directories walked from the descriptor down to the one holding @@ -164,6 +168,8 @@ struct InMemoryState platform::IWallClock const* clock; PathPolicy const* policy; std::size_t maxReadChunk; + IdentityModel identities; + std::size_t maxAncestorDepth; std::mutex mutex; std::map nodes; std::uint64_t nextInode = RootInode; @@ -172,14 +178,18 @@ struct InMemoryState async::IExecutor& blockingExecutor, platform::IWallClock const& wallClock, PathPolicy const& pathPolicy, - std::size_t readChunk): + std::size_t readChunk, + IdentityModel identityModel, + std::size_t ancestorDepth): home { &homeExecutor }, blocking { &blockingExecutor }, clock { &wallClock }, policy { &pathPolicy }, - maxReadChunk { readChunk } + maxReadChunk { readChunk }, + identities { identityModel }, + maxAncestorDepth { ancestorDepth } { - std::ignore = createNode(DescriptorType::Directory); + nodes.at(createNode(DescriptorType::Directory)).parent = RootInode; } [[nodiscard]] FileTime now() const @@ -256,19 +266,55 @@ struct InMemoryState void insert(std::uint64_t directory, std::string name, std::uint64_t inode) { - auto& parent = nodes.at(directory); auto key = keyOf(name); + detach(directory, key); + if (auto& node = nodes.at(inode); node.type == DescriptorType::Directory) + node.parent = directory; + auto& parent = nodes.at(directory); parent.entries.insert_or_assign(std::move(key), Entry { .name = std::move(name), .inode = inode }); touch(parent, now()); } void erase(std::uint64_t directory, std::string_view name) { + auto const key = keyOf(name); + detach(directory, key); auto& parent = nodes.at(directory); - parent.entries.erase(keyOf(name)); + parent.entries.erase(key); touch(parent, now()); } + /// Takes the parent of the directory @p key names in @p directory, which is losing that entry. + void detach(std::uint64_t directory, std::string const& key) + { + auto const& entries = nodes.at(directory).entries; + if (auto const found = entries.find(key); found != entries.end()) + if (auto& node = nodes.at(found->second.inode); + node.type == DescriptorType::Directory && node.parent == directory) + node.parent = 0; + } + + /// @return @p inode's identity, then each real parent's up to the model's root; `NoEntry` past + /// a directory with no parent, `Loop` past @c maxAncestorDepth parents. + [[nodiscard]] FsResult> ancestryOf(std::uint64_t inode) const + { + // Grown per step, never reserved to the cap, as the native walkers do. At most + // maxAncestorDepth + 1 parents are looked at, and the last of them must be the root. + auto chain = std::vector { fs::detail::ObjectIdentity { .device = 0, .idLow = inode, .idHigh = 0 } }; + auto current = inode; + for ([[maybe_unused]] auto const step: std::views::iota(std::size_t { 0 }, maxAncestorDepth + 1)) + { + auto const parent = nodes.at(current).parent; + if (parent == 0) + return refuse(FsErrorCode::NoEntry); + if (parent == current) + return chain; + chain.push_back(fs::detail::ObjectIdentity { .device = 0, .idLow = parent, .idHigh = 0 }); + current = parent; + } + return refuse(FsErrorCode::Loop); + } + void dropLink(std::uint64_t inode) { auto& node = nodes.at(inode); @@ -537,6 +583,18 @@ namespace { } + /// @param descriptor Any descriptor. + /// @param state A model's. + /// @return The node @p descriptor is open on where it is a descriptor of that model. + [[nodiscard]] static std::optional nodeOf(IDescriptor const& descriptor, + std::shared_ptr const& state) + { + auto const* mine = dynamic_cast(&descriptor); + if (mine == nullptr || mine->_state != state) + return std::nullopt; + return mine->_inode; + } + async::Task> read(std::size_t maxBytes, std::uint64_t offset) override { return submit([inode = _inode, flags = _flags, maxBytes, offset]( @@ -761,7 +819,8 @@ namespace auto const& node = state.nodes.at(found); if (node.type != DescriptorType::SymbolicLink) return refuse(FsErrorCode::Invalid); - return node.target; + // One rule with the walk and symlinkAt: a rooted target is never handed out. + return fs::detail::refuseRootedTarget(node.target, *state.policy); }); }); } @@ -991,8 +1050,11 @@ InMemoryDescriptorFileSystem::InMemoryDescriptorFileSystem(async::IExecutor& hom async::IExecutor& blocking, platform::IWallClock const& clock, PathPolicy const& policy, - std::size_t maxReadChunk): - _state { std::make_shared(home, blocking, clock, policy, maxReadChunk) } + std::size_t maxReadChunk, + IdentityModel identities, + std::size_t maxAncestorDepth): + _state { std::make_shared( + home, blocking, clock, policy, maxReadChunk, identities, maxAncestorDepth) } { } @@ -1064,4 +1126,30 @@ async::Task>> InMemoryDescriptorFileSystem }); } +async::Task> InMemoryDescriptorFileSystem::relation(IDescriptor const& first, + IDescriptor const& second) +{ + return async::offload(_state->home, + _state->blocking, + [state = _state, + firstNode = InMemoryDescriptor::nodeOf(first, _state), + secondNode = InMemoryDescriptor::nodeOf(second, _state)]() -> FsResult { + if (!firstNode || !secondNode) + return refuse(FsErrorCode::CrossDevice); + auto const lock = std::scoped_lock { state->mutex }; + if (state->nodes.at(*firstNode).type != DescriptorType::Directory + || state->nodes.at(*secondNode).type != DescriptorType::Directory) + return refuse(FsErrorCode::NotDirectory); + if (state->identities == IdentityModel::Unavailable) + return refuse(FsErrorCode::Unsupported); + if (*firstNode == *secondNode) + return Relation::Same; + return state->ancestryOf(*firstNode).and_then([&](auto const& up) { + return state->ancestryOf(*secondNode).transform([&](auto const& down) { + return fs::detail::decideRelation(up, down); + }); + }); + }); +} + } // namespace core::fs::testing diff --git a/src/core/fs/testing/InMemoryDescriptorFileSystem.hpp b/src/core/fs/testing/InMemoryDescriptorFileSystem.hpp index 1dcdedff..579884ed 100644 --- a/src/core/fs/testing/InMemoryDescriptorFileSystem.hpp +++ b/src/core/fs/testing/InMemoryDescriptorFileSystem.hpp @@ -10,10 +10,12 @@ #include #include #include +#include #include #include #include +#include #include #include #include @@ -25,6 +27,14 @@ namespace core::fs::testing /// The nodes and the configuration a file system and its descriptors share; defined in the source. struct InMemoryState; +/// Whether the model's nodes have identities @c IDescriptorFileSystem::relation can decide on. +enum class IdentityModel : std::uint8_t +{ + Stable, ///< Every node has one for its life, as on a native file system that keeps them. + Unavailable, ///< None has: `relation` is `Unsupported`, as on FAT, so a consumer tests its + ///< fail-closed path on every OS. +}; + /// A file system of nodes in memory: directories, regular files and symbolic links. /// /// It is held to the same contract as the native one, through the same code where there is code to @@ -52,11 +62,16 @@ class CORE_FS_API InMemoryDescriptorFileSystem final: public IDescriptorFileSyst /// @param policy The name rules paths are held to. Must outlive the file system and its /// descriptors: it is kept by address, and its rows are views. /// @param maxReadChunk The most one read returns. + /// @param identities Whether `relation` can decide. + /// @param maxAncestorDepth How many parents `relation` walks from each directory before it + /// answers `Loop`. InMemoryDescriptorFileSystem(async::IExecutor& home, async::IExecutor& blocking, platform::IWallClock const& clock, PathPolicy const& policy = posixPathPolicy(), - std::size_t maxReadChunk = std::size_t { 1 } << 20U); + std::size_t maxReadChunk = std::size_t { 1 } << 20U, + IdentityModel identities = IdentityModel::Stable, + std::size_t maxAncestorDepth = DefaultMaxAncestorDepth); InMemoryDescriptorFileSystem(InMemoryDescriptorFileSystem const&) = delete; InMemoryDescriptorFileSystem(InMemoryDescriptorFileSystem&&) = delete; @@ -97,6 +112,14 @@ class CORE_FS_API InMemoryDescriptorFileSystem final: public IDescriptorFileSyst [[nodiscard]] async::Task>> openPreopen( std::filesystem::path hostDirectory, DescriptorFlags flags) override; + /// Walks each directory's parent links up to the model's root. A directory removed since it was + /// opened has no parent: `NoEntry`, as a native `..` of it answers. + /// @param first A directory of this model. + /// @param second A directory of this model. + /// @return How they relate, or what @c IDescriptorFileSystem::relation names. + [[nodiscard]] async::Task> relation(IDescriptor const& first, + IDescriptor const& second) override; + private: std::shared_ptr _state; }; diff --git a/src/core/fs/windows/Ancestry.cpp b/src/core/fs/windows/Ancestry.cpp new file mode 100644 index 00000000..6066a4ba --- /dev/null +++ b/src/core/fs/windows/Ancestry.cpp @@ -0,0 +1,328 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The real parents of a directory on Windows. NtCreateFile has no `..` relative to a handle, so the +// walk is by name and the decision by identity: the handle's final path +// (`GetFinalPathNameByHandleW`, normalized, by volume GUID, every junction and link on the way +// resolved), then each ancestor prefix of it opened for its attributes only, without following a +// reparse point, and its `FILE_ID_INFO` (volume serial number and 128-bit file id) read. At a volume's +// root the walk goes on from each folder the volume is mounted on (`GetVolumePathNamesForVolumeNameW`), +// as POSIX's `..` leaves a mount for the directory it is mounted on; a drive letter is a root. +// +// A prefix renamed while it is walked can only lead to an object that is not the real ancestor, so +// every ancestor's handle is held, and once both walks are done the final paths of the two handles +// and of every ancestor are read again: a change is `Busy`, never a guess, and so is a failure on +// the way that a change could explain. A volume's mount folders are taken once, so a volume +// mounted inside itself ends; the walk keeps a list of paths to go on from, not a call stack. Any other +// failure -- a parent the user may not open, among them -- is the error it is, and the caller fails closed. +// Identities count only on the file systems of StableFileIdRows.cpp. These opens name absolute paths, outside +// every root: they read attributes and nothing else, and no handle they make leaves this file. +// +// CMake compiles this file on Windows, and posix/Ancestry.cpp everywhere else. +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace core::fs::detail +{ + +namespace +{ + + /// The prefix of a path by volume GUID, before the GUID's closing `}\`. + constexpr auto VerbatimPrefix = std::wstring_view { L"\\\\?\\" }; + + /// The longest file-system name `GetVolumeInformationByHandleW` writes, with its NUL. + constexpr auto FileSystemNameCapacity = std::size_t { MAX_PATH + 1 }; + + [[nodiscard]] std::unexpected lastError(char const* call) + { + return std::unexpected { fsErrorFromSystemCode(std::int64_t { ::GetLastError() }, call) }; + } + + /// @return @p handle's path by volume GUID, normalized: `\\?\Volume{...}\a\b`. + [[nodiscard]] FsResult finalPathOf(HANDLE handle) + { + auto path = std::wstring(MAX_PATH, L'\0'); + for ([[maybe_unused]] auto const attempt: { 0, 1, 2 }) + { + auto const length = ::GetFinalPathNameByHandleW(handle, + path.data(), + static_cast(path.size()), + FILE_NAME_NORMALIZED | VOLUME_NAME_GUID); + if (length == 0) + return lastError("GetFinalPathNameByHandleW"); + if (length < path.size()) + { + path.resize(length); + return path; + } + path.resize(length); // the size it needs, its NUL included + } + return refuse(FsErrorCode::Busy); + } + + /// @return The root of the volume @p path is on, `\\?\Volume{...}\`; empty where @p path is no + /// path by volume GUID. + [[nodiscard]] std::wstring_view volumeRootOf(std::wstring_view path) noexcept + { + if (!path.starts_with(VerbatimPrefix)) + return {}; + auto const separator = path.find(L'\\', VerbatimPrefix.size()); + return separator == std::wstring_view::npos ? std::wstring_view {} : path.substr(0, separator + 1); + } + + /// @return @p path without its last component; the volume's root stays as it is. + [[nodiscard]] std::wstring_view parentPathOf(std::wstring_view path, std::wstring_view root) noexcept + { + auto const separator = path.find_last_of(L'\\'); + if (separator == std::wstring_view::npos || separator < root.size()) + return root; + return path.substr(0, separator); + } + + /// @return The identity of @p handle's object, where its file system gives stable ones. + [[nodiscard]] FsResult identityOf(HANDLE handle) + { + // The file system first: FAT and others refuse FileIdInfo itself, which is no reason to give + // than that they have no stable ids. + auto fileSystem = std::array {}; + if (::GetVolumeInformationByHandleW(handle, + nullptr, + 0, + nullptr, + nullptr, + nullptr, + fileSystem.data(), + static_cast(fileSystem.size())) + == FALSE) + return lastError("GetVolumeInformationByHandleW"); + auto const fileSystemName = std::wstring_view { fileSystem.data() }; + if (fileIdStabilityOf(fileSystemName) != FileIdStability::Stable) + return refuse(FsErrorCode::Unsupported); + // A share reports the file system of the server's volume, NTFS as often as not, but its ids + // are the server's to keep: only a local volume's are trusted. The query answers only for a + // remote file. + auto remote = FILE_REMOTE_PROTOCOL_INFO {}; + if (::GetFileInformationByHandleEx(handle, FileRemoteProtocolInfo, &remote, sizeof(remote)) != FALSE) + return refuse(FsErrorCode::Unsupported); + auto id = FILE_ID_INFO {}; + if (::GetFileInformationByHandleEx(handle, FileIdInfo, &id, sizeof(id)) == FALSE) + return lastError("GetFileInformationByHandleEx(FileIdInfo)"); + return stableIdentityOf( + id.VolumeSerialNumber, std::as_bytes(std::span { id.FileId.Identifier }), fileSystemName); + } + + /// Opens @p path for its attributes alone, a reparse point as itself. + [[nodiscard]] FsResult openForIdentity(std::wstring const& path) + { + auto handle = UniqueHandle { ::CreateFileW(path.c_str(), + FILE_READ_ATTRIBUTES, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + nullptr, + OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, + nullptr) }; + if (handle.get() == platform::InvalidHandle) + return lastError("CreateFileW"); + return handle; + } + + /// @return The folders the volume @p root is mounted on, drive letters left out. + [[nodiscard]] FsResult> mountFoldersOf(std::wstring const& root) + { + auto names = std::wstring(MAX_PATH, L'\0'); + auto needed = DWORD { 0 }; + while (::GetVolumePathNamesForVolumeNameW( + root.c_str(), names.data(), static_cast(names.size()), &needed) + == FALSE) + { + if (::GetLastError() != ERROR_MORE_DATA || needed <= names.size()) + return lastError("GetVolumePathNamesForVolumeNameW"); + names.resize(needed); + } + auto folders = std::vector {}; + auto rest = std::wstring_view { names }; + while (!rest.empty() && rest.front() != L'\0') + { + auto const name = rest.substr(0, rest.find(L'\0')); + // `C:\` is a drive's root, above which there is nothing; `C:\mnt\v\` is a folder. + if (name.size() > 3) + folders.emplace_back(name); + rest.remove_prefix(std::min(rest.size(), name.size() + 1)); + } + return folders; + } + + /// An ancestor the walk opened, held until the walk is checked, and the path it was opened by. + struct Held + { + UniqueHandle handle; + std::wstring path; + }; + + /// One walk's state: the identities met, every ancestor still held, the volumes whose mount + /// folders were taken, and how many parents are left before `Loop`. + struct Walk + { + std::vector chain; + std::vector held; + std::vector volumesSeen; + std::size_t parentsLeft = 0; + }; + + /// Records one ancestor: its identity, and its handle with the path it is expected at. + [[nodiscard]] FsResult record(Walk& walk, UniqueHandle handle, std::wstring path) + { + if (walk.parentsLeft == 0) + return refuse(FsErrorCode::Loop); + --walk.parentsLeft; + auto const identity = identityOf(handle.get()); + if (!identity) + return std::unexpected { identity.error() }; + walk.chain.push_back(*identity); + walk.held.push_back(Held { .handle = std::move(handle), .path = std::move(path) }); + return {}; + } + + /// Records the parents of the object at @p start, which is already in the walk, up to its + /// volume's root, then on from each folder that volume is mounted on, and so on, without + /// recursion; a volume's folders are taken once. + [[nodiscard]] FsResult walkUp(Walk& walk, std::wstring start) + { + auto pending = std::vector { std::move(start) }; + while (!pending.empty()) + { + auto const path = std::move(pending.back()); + pending.pop_back(); + auto const root = std::wstring { volumeRootOf(path) }; + if (root.empty()) + return refuse(FsErrorCode::Unsupported); + auto current = std::wstring_view { path }; + while (current.size() > root.size()) + { + current = parentPathOf(current, root); + auto prefix = std::wstring { current }; + auto opened = openForIdentity(prefix); + if (!opened) + return std::unexpected { opened.error() }; + if (auto recorded = record(walk, std::move(*opened), std::move(prefix)); !recorded) + return recorded; + } + if (std::ranges::find(walk.volumesSeen, root) != walk.volumesSeen.end()) + continue; + walk.volumesSeen.push_back(root); + auto folders = mountFoldersOf(root); + if (!folders) + return std::unexpected { folders.error() }; + for (auto& folder: *folders) + { + // `C:\mnt\v\` with its separator names the root of the volume mounted there; without + // it, and with OPEN_REPARSE_POINT, the folder itself, on the volume that holds it. + while (folder.size() > 3 && folder.back() == L'\\') + folder.pop_back(); + auto opened = openForIdentity(folder); + if (!opened) + return std::unexpected { opened.error() }; + auto folderPath = finalPathOf(opened->get()); + if (!folderPath) + return std::unexpected { folderPath.error() }; + pending.push_back(*folderPath); + if (auto recorded = record(walk, std::move(*opened), std::move(*folderPath)); !recorded) + return recorded; + } + } + return {}; + } + + /// @return Whether @p handle's final path is still @p path. + [[nodiscard]] bool stillAt(HANDLE handle, std::wstring const& path) + { + auto const now = finalPathOf(handle); + return now && *now == path; + } + + /// @return Whether every ancestor @p walk holds is still at the path it was opened by: an + /// ancestor renamed away and another put in its place (ABA) shows here, through the + /// handle of the one that was met. + [[nodiscard]] bool stillWhereMet(Walk const& walk) + { + return std::ranges::all_of( + walk.held, [](Held const& ancestor) { return stillAt(ancestor.handle.get(), ancestor.path); }); + } + + /// @return @p error, or `Busy` for a name that is gone: an open directory the system cannot name + /// for a moment, or an ancestor read off its live path that is no longer there, is one + /// that a rename is moving. + [[nodiscard]] std::unexpected movedOr(FsError const& error) + { + if (error.code == FsErrorCode::NoEntry) + return refuse(FsErrorCode::Busy); + return std::unexpected { error }; + } + + /// What one handle's walk starts from. + struct Start + { + ObjectIdentity identity; + std::wstring path; + }; + + [[nodiscard]] FsResult startOf(HANDLE handle) + { + return identityOf(handle).and_then([&](ObjectIdentity const& identity) { + return finalPathOf(handle).transform( + [&](std::wstring path) { return Start { .identity = identity, .path = std::move(path) }; }); + }); + } + +} // namespace + +FsResult nativeRelation(NativeContext const& context, + platform::NativeHandle first, + platform::NativeHandle second) +{ + auto const maxDepth = context.options.maxAncestorDepth; + auto const firstStart = startOf(first); + if (!firstStart) + return movedOr(firstStart.error()); + auto const secondStart = startOf(second); + if (!secondStart) + return movedOr(secondStart.error()); + if (firstStart->identity == secondStart->identity) + return Relation::Same; + // Grown per step, never reserved to the cap: a deep tree costs what it walks. + auto up = + Walk { .chain = { firstStart->identity }, .held = {}, .volumesSeen = {}, .parentsLeft = maxDepth }; + auto down = + Walk { .chain = { secondStart->identity }, .held = {}, .volumesSeen = {}, .parentsLeft = maxDepth }; + auto const walked = + walkUp(up, firstStart->path).and_then([&] { return walkUp(down, secondStart->path); }); + // A rename during the walks could have led either one astray, or made it fail: what it found is + // trusted only where both handles, and every ancestor met, are still where they were. + if (!stillAt(first, firstStart->path) || !stillAt(second, secondStart->path) || !stillWhereMet(up) + || !stillWhereMet(down)) + return refuse(FsErrorCode::Busy); + if (!walked) + return movedOr(walked.error()); + return decideRelation(up.chain, down.chain); +} + +} // namespace core::fs::detail diff --git a/src/core/fs/windows/OwnerOnly_test.cpp b/src/core/fs/windows/OwnerOnly_test.cpp index 32616bf4..275d3a1b 100644 --- a/src/core/fs/windows/OwnerOnly_test.cpp +++ b/src/core/fs/windows/OwnerOnly_test.cpp @@ -38,12 +38,16 @@ #include #include +#include "VirtualVolumeTestSupport.hpp" + using core::fs::AccessScope; using core::fs::CreationAccess; using core::fs::DescriptorFlags; using core::fs::OpenFlags; using core::fs::SymlinkPolicy; using core::fs::test::DescriptorFixture; +using core::fs::test::requireElevationOrSkip; +using core::fs::test::VirtualVolume; namespace { @@ -155,15 +159,6 @@ void grantEveryone(std::filesystem::path const& path, DWORD inheritance = NO_INH == ERROR_SUCCESS); } -/// Skips a case that needs elevation, or fails it where `CORE_TEST_REQUIRE_ELEVATED=1` says the -/// runner is elevated (Windows CI), so a lost privilege fails rather than skips there. -void requireElevationOrSkip(char const* why) -{ - if (core::LiveEnvironment {}.get("CORE_TEST_REQUIRE_ELEVATED") == "1") - FAIL("CORE_TEST_REQUIRE_ELEVATED=1, but " << why); - SKIP(why); -} - /// @return The access @p descriptor's own handle reports. [[nodiscard]] std::optional accessOf(DescriptorFixture const& fixture, core::fs::IDescriptor& descriptor) @@ -424,3 +419,36 @@ TEST_CASE("windows: a DACL that withholds READ_CONTROL still stats, with access fileSystem->reset(); std::ignore = home.drain() + blocking.drain(); } + +TEST_CASE("windows: owner-only creation on FAT is refused and leaves nothing behind", + "[fs][native][access][windows-native]") +{ + // FAT keeps no security descriptor: what NtCreateFile was given is dropped without an error, so + // only reading the new object's access back can tell. It is then deleted through its own handle. + auto const scratch = core::testing::ScopedTempDir { "core-cpp-fs-fat-owner" }; + auto volume = VirtualVolume { scratch.path(), "fat32" }; + auto const root = volume.attach(); + if (!root) + requireElevationOrSkip("no FAT volume could be attached here: diskpart needs an administrator"); + std::filesystem::create_directories(*root / "grant"); + auto fixture = DescriptorFixture::createNative(); + auto directory = fixture.run(fixture.fileSystem().openPreopen( + *root / "grant", DescriptorFlags::Read | DescriptorFlags::MutateDirectory)); + INFO("open: " << (directory ? std::string { "ok" } : directory.error().toString())); + REQUIRE(directory.has_value()); + + auto const file = + fixture.run((*directory) + ->openAt(SymlinkPolicy::NoFollow, + "secret", + OpenFlags::Create | OpenFlags::Exclusive | OpenFlags::OwnerOnly, + DescriptorFlags::Read | DescriptorFlags::Write)); + REQUIRE_FALSE(file.has_value()); + CHECK(file.error().code == core::fs::FsErrorCode::NotPermitted); + CHECK_FALSE(std::filesystem::exists(*root / "grant" / "secret")); + + auto const made = fixture.run((*directory)->createDirectoryAt("keys", CreationAccess::OwnerOnly)); + REQUIRE_FALSE(made.has_value()); + CHECK(made.error().code == core::fs::FsErrorCode::NotPermitted); + CHECK_FALSE(std::filesystem::exists(*root / "grant" / "keys")); +} diff --git a/src/core/fs/windows/Relation_test.cpp b/src/core/fs/windows/Relation_test.cpp new file mode 100644 index 00000000..36f99ab1 --- /dev/null +++ b/src/core/fs/windows/Relation_test.cpp @@ -0,0 +1,147 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// What the Windows relation trusts an identity from: the file systems of StableFileIdRows, never a +// zero id, and nothing on a FAT volume, whose ids move with a directory entry. +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "VirtualVolumeTestSupport.hpp" + +using core::fs::DescriptorFlags; +using core::fs::FsErrorCode; +using core::fs::detail::FileIdStability; +using core::fs::detail::fileIdStabilityOf; +using core::fs::detail::stableIdentityOf; +using core::fs::test::DescriptorFixture; +using core::fs::test::requireElevationOrSkip; +using core::fs::test::VirtualVolume; + +namespace +{ + +/// A file id of 16 bytes, each @p fill. +[[nodiscard]] std::array fileIdOf(std::byte fill) +{ + auto id = std::array {}; + id.fill(fill); + return id; +} + +} // namespace + +TEST_CASE("windows: only the file systems of StableFileIdRows give identities", "[fs][relation]") +{ + struct Row + { + std::wstring_view name; + FileIdStability stability = FileIdStability::Unstable; + }; + auto const row = GENERATE(Row { L"NTFS", FileIdStability::Stable }, + Row { L"ReFS", FileIdStability::Stable }, + Row { L"FAT", FileIdStability::Unstable }, + Row { L"FAT32", FileIdStability::Unstable }, + Row { L"exFAT", FileIdStability::Unstable }, + Row { L"CSVFS", FileIdStability::Unstable }, + Row { L"ntfs", FileIdStability::Unstable }, + Row { L"", FileIdStability::Unstable }); + CHECK(fileIdStabilityOf(row.name) == row.stability); + auto const id = fileIdOf(std::byte { 7 }); + auto const identity = stableIdentityOf(42, id, row.name); + CHECK(identity.has_value() == (row.stability == FileIdStability::Stable)); +} + +TEST_CASE("windows: a zero file id is no identity", "[fs][relation]") +{ + auto const zero = fileIdOf(std::byte { 0 }); + auto const identity = stableIdentityOf(42, zero, L"NTFS"); + REQUIRE_FALSE(identity.has_value()); + CHECK(identity.error().code == FsErrorCode::Unsupported); + // Either half alone is an id. + auto low = zero; + low.front() = std::byte { 1 }; + CHECK(stableIdentityOf(42, low, L"NTFS").has_value()); + auto high = zero; + high.back() = std::byte { 1 }; + CHECK(stableIdentityOf(42, high, L"NTFS").has_value()); +} + +TEST_CASE("relation on FAT is Unsupported", "[fs][native][relation][windows-native]") +{ + auto const scratch = core::testing::ScopedTempDir { "core-cpp-fs-fat" }; + auto volume = VirtualVolume { scratch.path(), "fat32" }; + auto const root = volume.attach(); + if (!root) + requireElevationOrSkip( + "no FAT volume could be attached here: diskpart needs an administrator, and wine has none"); + std::filesystem::create_directories(*root / "a" / "b"); + auto fixture = DescriptorFixture::createNative(); + auto top = fixture.run(fixture.fileSystem().openPreopen(*root / "a", DescriptorFlags::Read)); + auto inner = fixture.run(fixture.fileSystem().openPreopen(*root / "a" / "b", DescriptorFlags::Read)); + INFO("open a: " << (top ? std::string { "ok" } : top.error().toString())); + INFO("open a/b: " << (inner ? std::string { "ok" } : inner.error().toString())); + REQUIRE(top.has_value()); + REQUIRE(inner.has_value()); + auto const relation = fixture.run(fixture.fileSystem().relation(**top, **inner)); + REQUIRE_FALSE(relation.has_value()); + CHECK(relation.error().code == FsErrorCode::Unsupported); +} + +TEST_CASE("relation crosses a volume mounted in a folder", "[fs][native][relation][windows-native]") +{ + // An NTFS volume mounted at outer/mnt, with no drive letter: outer contains what is on it, though + // no path by volume GUID of it passes through outer. + auto const scratch = core::testing::ScopedTempDir { "core-cpp-fs-mount" }; + std::filesystem::create_directories(scratch.path() / "outer" / "mnt"); + std::filesystem::create_directories(scratch.path() / "beside"); + auto volume = VirtualVolume { scratch.path(), "ntfs" }; + auto const root = volume.attach(scratch.path() / "outer" / "mnt"); + if (!root) + requireElevationOrSkip( + "no volume could be mounted in a folder here: diskpart needs an administrator, and " + "wine has none"); + std::filesystem::create_directories(*root / "key"); + auto fixture = DescriptorFixture::createNative(); + auto const open = [&](std::filesystem::path const& path) { + auto opened = fixture.run(fixture.fileSystem().openPreopen(path, DescriptorFlags::Read)); + INFO("open " << path.string() << ": " << (opened ? std::string { "ok" } : opened.error().toString())); + REQUIRE(opened.has_value()); + return std::move(*opened); + }; + auto const outer = open(scratch.path() / "outer"); + auto const beside = open(scratch.path() / "beside"); + auto const mounted = open(*root); + auto const key = open(*root / "key"); + auto const relationOf = [&](core::fs::IDescriptor const& first, core::fs::IDescriptor const& second) { + return fixture.run(fixture.fileSystem().relation(first, second)); + }; + auto const outerKey = relationOf(*outer, *key); + INFO("outer, key: " << (outerKey ? std::string { "ok" } : outerKey.error().toString())); + REQUIRE(outerKey.has_value()); + CHECK(*outerKey == core::fs::Relation::FirstContainsSecond); + auto const outerMounted = relationOf(*outer, *mounted); + REQUIRE(outerMounted.has_value()); + CHECK(*outerMounted == core::fs::Relation::FirstContainsSecond); + auto const besideKey = relationOf(*beside, *key); + REQUIRE(besideKey.has_value()); + CHECK(*besideKey == core::fs::Relation::Unrelated); +} diff --git a/src/core/fs/windows/StableFileIdRows.cpp b/src/core/fs/windows/StableFileIdRows.cpp new file mode 100644 index 00000000..796113f2 --- /dev/null +++ b/src/core/fs/windows/StableFileIdRows.cpp @@ -0,0 +1,71 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// The file systems whose file ids relation() trusts. A row is added only for a file system whose id +// is persistent and unique on its volume: NTFS's file reference and ReFS's 128-bit id are; FAT's and +// exFAT's are the position of a directory entry, which a rename moves, and an SMB share's are the +// server's, persistent only where the server says so -- which the name alone does not tell, so a +// share stays unsupported. A name not in the table is refused: fail closed. +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace core::fs::detail +{ + +namespace +{ + + using namespace std::string_view_literals; + + constexpr auto Rows = std::to_array({ + { .fileSystemName = L"NTFS"sv, .stability = FileIdStability::Stable }, + { .fileSystemName = L"ReFS"sv, .stability = FileIdStability::Stable }, + }); + + [[nodiscard]] std::uint64_t littleEndian(std::span bytes) noexcept + { + auto value = std::uint64_t { 0 }; + for (auto const index: std::views::iota(std::size_t { 0 }, bytes.size())) + value |= std::uint64_t { std::to_integer(bytes[index]) } << (8U * index); + return value; + } + +} // namespace + +std::span stableFileIdRows() noexcept +{ + return Rows; +} + +FileIdStability fileIdStabilityOf(std::wstring_view fileSystemName) noexcept +{ + auto const row = std::ranges::find(Rows, fileSystemName, &StableFileIdRow::fileSystemName); + return row == Rows.end() ? FileIdStability::Unstable : row->stability; +} + +FsResult stableIdentityOf(std::uint64_t volumeSerial, + std::span fileId, + std::wstring_view fileSystemName) +{ + auto const identity = ObjectIdentity { .device = volumeSerial, + .idLow = littleEndian(fileId.first<8>()), + .idHigh = littleEndian(fileId.last<8>()) }; + if (fileIdStabilityOf(fileSystemName) != FileIdStability::Stable + || (identity.idLow == 0 && identity.idHigh == 0)) + return std::unexpected { FsError { .code = FsErrorCode::Unsupported, + .systemCode = 0, + .context = "this file system gives no stable file identities" } }; + return identity; +} + +} // namespace core::fs::detail diff --git a/src/core/fs/windows/StableFileIdRows.hpp b/src/core/fs/windows/StableFileIdRows.hpp new file mode 100644 index 00000000..1a1ef101 --- /dev/null +++ b/src/core/fs/windows/StableFileIdRows.hpp @@ -0,0 +1,53 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// Which Windows file systems give an object a file id that names it, and only it, for its life: +/// the table @c IDescriptorFileSystem::relation trusts identities from. Private to the fs module. + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace core::fs::detail +{ + +/// Whether a file system's file ids can decide a relation. The refusing case is zero. +enum class FileIdStability : std::uint8_t +{ + Unstable, ///< Not to be trusted: ids that move with a directory entry (FAT, exFAT), are made up + ///< per session (SMB without persistent ids), or a file system nobody has vouched for. + Stable, ///< An id names one object for its life (NTFS, ReFS). +}; + +/// One file system, by the name `GetVolumeInformationByHandleW` reports. +struct StableFileIdRow +{ + std::wstring_view fileSystemName; ///< As reported, compared exactly. + FileIdStability stability = FileIdStability::Unstable; +}; + +/// @return The file systems whose ids are trusted; every name not here is @c FileIdStability::Unstable. +[[nodiscard]] CORE_FS_API std::span stableFileIdRows() noexcept; + +/// @param fileSystemName What `GetVolumeInformationByHandleW` reports. +/// @return Its row's stability; `Unstable` for a name no row has. +[[nodiscard]] CORE_FS_API FileIdStability fileIdStabilityOf(std::wstring_view fileSystemName) noexcept; + +/// An object's identity, where it can decide a relation. +/// @param volumeSerial `FILE_ID_INFO::VolumeSerialNumber`. +/// @param fileId `FILE_ID_INFO::FileId`, 16 bytes, least significant first. +/// @param fileSystemName What the volume's file system is called. +/// @return The identity; `Unsupported` on a file system whose ids are not trusted, or for a zero +/// id, which names no object. +[[nodiscard]] CORE_FS_API FsResult stableIdentityOf(std::uint64_t volumeSerial, + std::span fileId, + std::wstring_view fileSystemName); + +} // namespace core::fs::detail diff --git a/src/core/fs/windows/VirtualVolumeTestSupport.hpp b/src/core/fs/windows/VirtualVolumeTestSupport.hpp new file mode 100644 index 00000000..2d210e42 --- /dev/null +++ b/src/core/fs/windows/VirtualVolumeTestSupport.hpp @@ -0,0 +1,143 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +/// @file +/// Test-only support for the Windows cases that need a volume of their own: a small virtual disk made, +/// formatted and attached through diskpart, and the rule for a case that needs the elevation diskpart +/// does. Beside the tests, because it needs Catch2; compiled into no module. + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace core::fs::test +{ + +/// Skips a case that needs elevation, or fails it where `CORE_TEST_REQUIRE_ELEVATED=1` says the +/// runner is elevated (Windows CI), so a lost privilege fails rather than skips there. +/// @param why What could not be done, for the message. +inline void requireElevationOrSkip(char const* why) +{ + if (core::LiveEnvironment {}.get("CORE_TEST_REQUIRE_ELEVATED") == "1") + FAIL("CORE_TEST_REQUIRE_ELEVATED=1, but " << why); + SKIP(why); +} + +/// @return A drive letter no volume has, from Z down; nullopt where every one is taken. +[[nodiscard]] inline std::optional freeDriveLetter() +{ + auto const used = ::GetLogicalDrives(); + for (auto const index: std::views::iota(0, 26) | std::views::reverse) + if ((used & (DWORD { 1 } << static_cast(index))) == 0) + return static_cast('A' + index); + return std::nullopt; +} + +/// Runs a diskpart script. +/// @return Whether diskpart ran it and succeeded; never where it is missing or needs elevation. +[[nodiscard]] inline bool runDiskpart(std::filesystem::path const& script, std::string const& text) +{ + { + auto file = std::ofstream { script }; + file << text; + if (!file.good()) + return false; + } + // CreateProcessW, not std::system: a child of its own, with nothing but its exit code read. + auto command = L"diskpart.exe /s \"" + script.wstring() + L"\""; + auto startup = STARTUPINFOW {}; + startup.cb = sizeof(startup); + auto process = PROCESS_INFORMATION {}; + if (::CreateProcessW(nullptr, + command.data(), + nullptr, + nullptr, + FALSE, + CREATE_NO_WINDOW, + nullptr, + nullptr, + &startup, + &process) + == FALSE) + return false; + // Bounded: a diskpart that hangs is a volume not made, not a case that never ends. + auto code = DWORD { 1 }; + if (::WaitForSingleObject(process.hProcess, 120'000) == WAIT_OBJECT_0) + ::GetExitCodeProcess(process.hProcess, &code); + else + ::TerminateProcess(process.hProcess, 1); + ::CloseHandle(process.hThread); + ::CloseHandle(process.hProcess); + return code == 0; +} + +/// A small virtual disk formatted with one file system and attached at a drive letter or a folder of +/// its own, detached on destruction. +class VirtualVolume +{ + public: + /// @param directory Where the disk file and the scripts go. + /// @param fileSystem What diskpart formats it with: `fat32`, `ntfs`. + VirtualVolume(std::filesystem::path directory, std::string fileSystem): + _directory { std::move(directory) }, _fileSystem { std::move(fileSystem) } + { + } + + VirtualVolume(VirtualVolume const&) = delete; + VirtualVolume(VirtualVolume&&) = delete; + VirtualVolume& operator=(VirtualVolume const&) = delete; + VirtualVolume& operator=(VirtualVolume&&) = delete; + + ~VirtualVolume() + { + if (_isAttached) + std::ignore = runDiskpart(_directory / "detach.txt", + "select vdisk file=\"" + disk().string() + "\"\ndetach vdisk\n"); + } + + /// Attaches the disk. + /// @param folder An empty folder of another volume to mount it on; nullopt for a free drive letter. + /// @return Its root, `X:\` or @p folder; nullopt where no disk could be made and attached here. + [[nodiscard]] std::optional attach( + std::optional folder = std::nullopt) + { + auto const letter = freeDriveLetter(); + if (!folder && !letter) + return std::nullopt; + auto const assignment = folder ? "assign mount=\"" + folder->string() + "\"\n" + : "assign letter=" + std::string(1, *letter) + "\n"; + auto const path = disk().string(); + _isAttached = + runDiskpart(_directory / "attach.txt", + "create vdisk file=\"" + path + "\" maximum=64 type=expandable\n" + + "select vdisk file=\"" + path + "\"\nattach vdisk\ncreate partition primary\n" + + "format fs=" + _fileSystem + " quick label=CORECPP\n" + assignment); + if (!_isAttached) + return std::nullopt; + auto root = folder ? *folder : std::filesystem::path { std::string(1, *letter) + ":\\" }; + auto error = std::error_code {}; + if (!std::filesystem::is_directory(root, error)) + return std::nullopt; + return root; + } + + private: + [[nodiscard]] std::filesystem::path disk() const { return _directory / "volume.vhdx"; } + + std::filesystem::path _directory; + std::string _fileSystem; + bool _isAttached = false; +}; + +} // namespace core::fs::test diff --git a/src/core/fs/windows/WindowsDescriptor.cpp b/src/core/fs/windows/WindowsDescriptor.cpp index 73da1c7d..d437ece5 100644 --- a/src/core/fs/windows/WindowsDescriptor.cpp +++ b/src/core/fs/windows/WindowsDescriptor.cpp @@ -51,6 +51,7 @@ #include #include #include +#include #include #include #include @@ -461,6 +462,24 @@ namespace "SetFileInformationByHandle"); } + /// Reads @p handle's access back and refuses an object that is not owner-only: a file system that + /// keeps no security descriptor (FAT, exFAT) drops the one it was created with and says nothing. + /// The refused object is deleted through @p handle, which carries `READ_CONTROL` and `DELETE`, so + /// it goes when the handle is closed and no name is ever looked up again. + /// @param context The file system, for the token's user. + /// @param handle The object just created. + /// @return Nothing where it reads owner-only; `NotPermitted` otherwise. + FsResult requireOwnerOnly(NativeContext const& context, HANDLE handle) + { + if (detail::accessFactsOf(handle, context.ownerSecurity->user()).transform(classifyAccess) + == AccessScope::OwnerOnly) + return {}; + std::ignore = deleteOpened(handle); + return std::unexpected { FsError { .code = FsErrorCode::NotPermitted, + .systemCode = 0, + .context = "the new object is not owner-only" } }; + } + FsResult truncateOpened(HANDLE handle) { auto end = FILE_END_OF_FILE_INFO {}; @@ -853,9 +872,13 @@ namespace return refuse(FsErrorCode::NotDirectory); request->options |= FILE_DIRECTORY_FILE; } - // Owner-only from the moment NtCreateFile makes it; an existing file keeps its own. + // Owner-only from the moment NtCreateFile makes it, and read back before it is used. + // DELETE, so an object that does not read owner-only goes through this handle. if (hasFlag(open, OpenFlags::OwnerOnly)) + { request->security = context->ownerSecurity->forFile(); + request->access |= DELETE; + } auto const name = detail::utf16Of(resolved->name); if (!name) return std::unexpected { name.error() }; @@ -873,6 +896,9 @@ namespace if (!child) return std::unexpected { child.error() }; auto const opened = child->handle.get(); + if (hasFlag(open, OpenFlags::OwnerOnly)) + if (auto held = requireOwnerOnly(*context, opened); !held) + return std::unexpected { held.error() }; auto const information = informationOf(opened); if (!information) return std::unexpected { information.error() }; @@ -933,17 +959,25 @@ namespace return vacant(std::move(resolved), DescriptorType::Directory); }) .and_then([&](Resolved const& resolved) { - return openFinal(*context, - resolved, - detail::NtOpenRequest { - .access = FILE_LIST_DIRECTORY, - .disposition = FILE_CREATE, - .options = FILE_DIRECTORY_FILE, - .reparse = detail::ReparseHandling::OpenThePoint, - .security = access == CreationAccess::OwnerOnly - ? context->ownerSecurity->forDirectory() - : nullptr }) - .transform([](UniqueHandle const&) {}); + auto const ownerOnly = access == CreationAccess::OwnerOnly; + return openFinal( + *context, + resolved, + detail::NtOpenRequest { + // Read back, and deleted through this handle where it does not + // read owner-only, as openAt's owner-only file is. + .access = FILE_LIST_DIRECTORY + | (ownerOnly ? ACCESS_MASK { READ_CONTROL | DELETE } : 0), + .disposition = FILE_CREATE, + .options = FILE_DIRECTORY_FILE, + .reparse = detail::ReparseHandling::OpenThePoint, + .security = + ownerOnly ? context->ownerSecurity->forDirectory() : nullptr }) + .and_then([&](UniqueHandle const& made) -> FsResult { + if (!ownerOnly) + return {}; + return requireOwnerOnly(*context, made.get()); + }); }); }); } @@ -1072,7 +1106,10 @@ namespace return openFinal(*context, resolved, attributesRequest(0)); }) .and_then([](UniqueHandle const& link) { return detail::readReparseData(link.get()); }) - .and_then([](detail::ReparseData const& data) { return detail::reportedTarget(data); }); + .and_then([](detail::ReparseData const& data) { return detail::reportedTarget(data); }) + .and_then([&](std::string target) { + return detail::refuseRootedTarget(std::move(target), *context->policy); + }); }); } @@ -1328,6 +1365,11 @@ namespace }); } + async::Task> relation(IDescriptor const& first, IDescriptor const& second) override + { + return detail::relationOf(_context, first, second); + } + private: SharedContext _context; }; @@ -1354,6 +1396,7 @@ FsResult> makeNativeDescriptorFileSystem( KernelSeparators, &detail::systemNtFiles(), std::move(security), + nullptr, nullptr)); }); } @@ -1379,6 +1422,7 @@ FsResult> detail::makeWindowsDescriptorFi KernelSeparators, &files, std::move(security), + nullptr, nullptr)); }); } From 019ee401ee56cf6591c267c32cad25053031e300 Mon Sep 17 00:00:00 2001 From: Christian Parpart Date: Fri, 27 Nov 2026 17:17:05 +0100 Subject: [PATCH 19/19] docs: document core::fs, core::http, the socket surface and the trust stores Document core::fs, core::http, the socket surface and the trust stores. Module pages for fs (the executor contract and teardown, beneath resolution and the PathPolicy rows, the rights table, owner-only creation and the per-OS access scope, and relation()'s containment rules for embedders: identities per OS, Linux mount ids and mountinfo roots, re-exposing file systems, macOS firmlinks and the mount-path hidden set, the mounts-beneath scan and its identity check at each open, the residual races, a mount made after the answer, and what Unsupported and Busy mean for a caller) and http (HTTP/1.1 only, the pure layer, Connection, HttpClient's pool and retry rule, serveHttp's bounds and close rules). async gains offload, net the resolvers, IpSocketAddress, endpoints and options and the two resolver error codes, base why net::constantTimeEquals stays on OpenSSL. The module index, the nav, AGENT.md's module table, the source map, the offload rule and the CHANGELOG's Unreleased section follow. fs.md: building a native file system runs on the calling thread; the PathPolicy table names every column of the row (target and volume separators, the stem rule); the access table's Linux row says when it is nullopt, with rows for the BSDs without ACL reading; Windows owner-only creation reads its access back; relation() on Linux needs STATX_MNT_ID (5.8). net.md: give network-bound blocking work an executor of its own. The CHANGELOG lists fastcached among the consumers checked, states the CMP0155 limit of the subproject build, and says that a chain verifier finishes on its own executor and that a full verification budget fails a handshake with ResourceExhausted, which may be driven again. Signed-off-by: Christian Parpart --- .agent/reference/source-map.md | 16 +- .agent/rules/async-and-net.md | 5 + AGENT.md | 7 +- CHANGELOG.md | 120 ++++++++++ docs/modules/async.md | 22 ++ docs/modules/base.md | 16 +- docs/modules/fs.md | 394 +++++++++++++++++++++++++++++++++ docs/modules/http.md | 142 ++++++++++++ docs/modules/index.md | 10 + docs/modules/net.md | 29 ++- mkdocs.yml | 2 + 11 files changed, 750 insertions(+), 13 deletions(-) create mode 100644 docs/modules/fs.md create mode 100644 docs/modules/http.md diff --git a/.agent/reference/source-map.md b/.agent/reference/source-map.md index c410ee9e..7ca2d494 100644 --- a/.agent/reference/source-map.md +++ b/.agent/reference/source-map.md @@ -54,7 +54,8 @@ src/core/ async/ core::async, headers but for two sources that own thread-local state: StopToken (std:: or the fallback); Task, UniqueCoroHandle, Cancellation, Awaitable, whenAll/whenAny (contour); - executors, AsyncQueue (planned, B1) + executors, AsyncQueue (planned, B1); Offload (offload: a blocking + call on an injected executor, resumed on the home one) net/ core::net_types (NetError, IoResult; header-only, everywhere), core::net (EventLoop over IoBackend, which DISPATCHES readiness to the handlers registered with it; PlatformLoop owns the default @@ -74,6 +75,19 @@ src/core/ hold. The WebAssembly subset is IoBackend, IHostScheduler, HostDrivenBackend and EventLoop with PlatformLoop and TestLoop over it; IOCP, sockets and dialling (planned, B6-B11) + fs/ core::fs: Descriptor (IDescriptorFileSystem, IDescriptor, relation), + NativeFileSystem, FsError, PathPolicy (isRootedLinkTarget), Rights + (the one rights table), AccessScope (classifyAccess); detail/ (the + path walk every resolver runs, Ancestry's decision) posix/ linux/ + (openat2, mountinfo) bsd/ darwin/ (firmlink exits) windows/ (ntdll + beneath walk, owner security, stable file id rows) are private and + CMake picks one file per concern; testing/ holds + InMemoryDescriptorFileSystem; DescriptorTestSupport.hpp is test-only + http/ core::http: Message (HttpErrorCode, Fields, the validating + factories), Framing (HttpLimits, request/responseFraming, HeadParser, + ChunkedDecoder), Body, Connection, HttpClient (the per-origin pool), + HttpServer (serveHttp, errorStatusTable); testing/ScriptedConnector; + SmugglingCorpus.hpp and HttpTestSupport.hpp are test-only tui/ core::tui_output (endo: TerminalOutput, SyncGuard, SgrBuilder, TerminalProtocols, CursorShape, Error; links base alone; with CORE_CPP_WITH_TUI_OUTPUT, which the full TUI forces on), diff --git a/.agent/rules/async-and-net.md b/.agent/rules/async-and-net.md index a637a112..c866f778 100644 --- a/.agent/rules/async-and-net.md +++ b/.agent/rules/async-and-net.md @@ -58,6 +58,11 @@ The contract is the spec's (Part I §2, rules 1 to 6), and it is short enough to `core::async::OperationCancelled`; a cancel from the resource (`close()`, `cancelRead()`, a closed listener) returns `NetErrorCode::Cancelled` as a value. If a receive already completed with bytes, the data wins. +- **A blocking OS call runs only on an injected blocking executor, through `async::offload`**; it + resumes on the home executor, and `NativeDescriptor_test.cpp`'s *native: every descriptor + operation parks on the blocking executor* holds it. The blocking executor is drained before the + home executor dies. A call that may never return (a lookup, a read of a terminal) waits through + `net::detail::ParkedCall` instead, which hands its waiter back on a stop. ## The turn, and the orderings inside it diff --git a/AGENT.md b/AGENT.md index 2b192859..9faf1506 100644 --- a/AGENT.md +++ b/AGENT.md @@ -20,6 +20,8 @@ is [the plan](docs/superpowers/plans/2026-09-18-core-cpp.md). | platform | `core::platform` | `core::platform` | base, log | | async | `core::async` | `core::async` (headers, and two sources for thread-local state) | Threads | | net | `core::net` | `core::net_types`, `core::net`, `core::net_tls` | async, platform | +| fs | `core::fs` | `core::fs` (`CORE_CPP_WITH_FS`, native only) | base, log, async, platform | +| http | `core::http` | `core::http` (`CORE_CPP_WITH_HTTP`, native only) | base, async, net | | tui | `core::tui` | `core::tui_output`, `core::tui_core`, `core::tui` | base (leaf); + tui_output, libunicode (headless `tui_core`); + platform, async, net (`tui`) | | testing | `core::testing` | `core::testing`, `core::testing_dialogs`, `core::testing_main` | base; log and Catch2 for `testing_main` | @@ -32,7 +34,10 @@ Every module exists. `Generator` is in base (Task A5b: it needs only std, and a leaf that links base alone. Task B12 composed the TUI runtime on `core::net::EventLoop`, which is why the `tui` row lists `net`; `tui_output` still links base alone, which is the point of the split. Phase B is complete: the networking half of the merge landed in `net` (Tasks B6 to B11). The module DAG is the -table in `cmake/CoreCppModules.cmake`, and configure refuses a link it does not list. +table in `cmake/CoreCppModules.cmake`, and configure refuses a link it does not list. `fs` (the +descriptor-relative file system) and `http` (HTTP/1.1 client and server) are native only, and +each has an option (`CORE_CPP_WITH_FS`, `CORE_CPP_WITH_HTTP`), which a vendored copy +without the module's directory sets OFF. Consumers: contour (vendored), endo, fastcached, tuidu, Lightweight's `dbtool`, morph (CPM). Who links what, and where each keeps its pin: [`.agent/reference/consumers.md`](.agent/reference/consumers.md). diff --git a/CHANGELOG.md b/CHANGELOG.md index 594966ab..7a7d221d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,126 @@ workflow refuses one without a section here. ## [Unreleased] +### Breaking + +- **`NetErrorCode` has two new values, `NameNotFound` and `ResolverTemporaryFailure`**, above `Last`. A + name lookup that answers that the name does not exist (`EAI_NONAME`, `WSAHOST_NOT_FOUND`) is now + `NameNotFound`, and one the resolver could not answer now (`EAI_AGAIN`, `WSATRY_AGAIN`) is + `ResolverTemporaryFailure`, where both were `AddressError`; a permanent resolver failure stays + `AddressError`. `ThreadedAddressResolver`, `InlineAddressResolver` and the dial report them. Migration: an + exhaustive `switch` over `NetErrorCode` handles the two (or adds a `default:`); code that tested for + `AddressError` after a lookup tests for all three. Consumers grepped (contour, endo, fastcached, Lightweight, morph, + tuidu): none switches exhaustively over `NetErrorCode`. +- **A full resolver budget is `ResourceExhausted`, not `WouldBlock`.** `ThreadedAddressResolver`'s full + queue and `ExecutorAddressResolver`'s `maxInFlight` refuse a lookup with `NetErrorCode::ResourceExhausted`, + as a full TLS verification budget does, so `isDeadlineExpiry()` no longer reads a refusal as a deadline's + tick. Migration: code that retried a lookup on `WouldBlock` retries on `ResourceExhausted`. +- **`ITlsContext::wrapClient(inner, executor, TlsPeer)` refuses a server name unless it is overridden.** Its + default wraps only for an empty `TlsPeer::serverName` and answers `NetErrorCode::Unsupported` otherwise, so a + context that cannot verify a per-connection name is never used as though it did. The pinned-name + `makeTlsClientContext(caPem, expectedHostName, options)` keeps that default. An `ITlsContext` outside + core-cpp that can bind a connection to a name overrides it. Consumers grepped: none implements `ITlsContext`. +- **The pinned-name `makeTlsClientContext(caPem, expectedHostName, options)` no longer falls back to the + certificate's common name**: the host is checked against the subjectAltNames alone (RFC 9525), and an + expected name in brackets or with a zone that is not an IPv6 literal is now a factory error instead of a name + nothing matches. A server whose certificate names the host only in its CN must get a subjectAltName. +- **`testing::StrictTlsPeer::client()` and `server()` take a `StrictTlsPeerOptions`** (the highest version, + ALPN, an alert to refuse or warn with) where they took a `TlsVersion`. Migration: + `StrictTlsPeer::server(socket, material, { .maximumVersion = TlsVersion::Tls12 })`. Consumers grepped: none + constructs one. +- **A vendored copy without `fs` or `http` sets `CORE_CPP_WITH_FS=OFF` or `CORE_CPP_WITH_HTTP=OFF`.** Both + default ON, and a configure whose enabled module's directory is missing stops with a message naming the + option. contour's copy, whose `MODULES` names neither, needs the two options OFF, or `fs;http` in its `MODULES`. + +### Added + +- **`core::fs`**, a new module (`CORE_CPP_WITH_FS`, ON; native only): a descriptor-relative file system + (`IDescriptorFileSystem`, `IDescriptor`, `IDirectoryStream`, `makeNativeDescriptorFileSystem()`) whose every + operation is an `async::Task` run on an injected blocking executor. A path never leaves its descriptor + (`openat2(RESOLVE_BENEATH)` on Linux, a component walker over held handles elsewhere, `NtCreateFile` relative + to a handle on Windows), names follow a per-OS `PathPolicy` row, every descriptor enforces one rights table + (`rightsTable()`, `checkOpenRights()`), errors are `FsError`/`FsResult`, and + `testing::InMemoryDescriptorFileSystem` is held to the same contract. + - `fs::OpenFlags::OwnerOnly` and `fs::CreationAccess` (taken by `createDirectoryAt`): files and directories + no other user can reach at any moment, on every OS. + - `fs::AccessScope`, `fs::DescriptorStat::access` and `fs::classifyAccess()`: who may reach an object, read + from its open handle; `nullopt` where the system cannot tell. + - `fs::Relation` and `IDescriptorFileSystem::relation()`: whether one opened directory is, contains or lies + beneath another, decided on real parents by identity, never by path text, and failing closed + (`Unsupported`) where a mount may hide one from the other, or a mount beneath either may show the other's + file system (the mount table is scanned); `NativeFileSystemOptions::maxAncestorDepth` bounds the walk. + - `fs::isRootedLinkTarget()`: whether a symbolic link's target names a root, under a `PathPolicy`. +- **`core::http`**, a new module (`CORE_CPP_WITH_HTTP`, ON; native only): HTTP/1.1 with streamed bodies, + chunked transfer coding, trailers and keep-alive. The pure layer (`Fields`, the validating `Method`, + `RequestTarget` and `ReasonPhrase`, `requestFraming()`, `responseFraming()`, `HeadParser`, + `ChunkedDecoder`, `HttpLimits`), `HttpErrorCode` (one per case of `wasi:http`'s `error-code`) with + `HttpError` and `RefusalReason`; `Connection` with `WireTimeouts`; `HttpClient` with a per-origin pool + (`maxIdlePerOrigin`, `maxConnectionsPerOrigin`, `maxConnectionsTotal`, `idleTimeout`) and a safe retry of a + stale pooled connection, `HttpTimeouts` of 600 s each by default (wasmtime's), at most 32 interim + responses, and no connection pooled that holds unread bytes; `serveHttp()`, `serveHttpConnection()`, `IHttpHandler`, `HttpServerOptions` + (every wait on a client bounded by default), `errorStatusTable()`, `errorStatusFor()`; and + `testing::ScriptedConnector`. HTTP/1.1 only, no client pipelining. +- **`core::async::offload(home, blocking, work)`**: a blocking call on an injected executor, resumed on the + home one; the stop token is read once, before the hop, and a result that was produced is never dropped. +- **`core::net::ExecutorAddressResolver`**, a resolver that owns no thread: every lookup runs on an injected + executor, bounded by `ExecutorResolverOptions::maxInFlight`. `IAddressResolver::resolveClassified()` + (defaulted, so existing resolvers compile unchanged), `resolverErrorTable()` and + `testing::ScriptedAddressResolver`. +- **`core::net::IpSocketAddress`** (`Ipv4Address`, `Ipv6Address`, `AddressFamily`), with `toEndpoint()` and + `toIpSocketAddress()`. +- **Endpoints and options on `ISocket` and `IListener`**: `localEndpoint()`, `remoteEndpoint()` (sockets), + `option()` and `setOption()` over `SocketOption` and the per-platform `socketOptionTable()`; every + decorator forwards them. +- **`core::net::ITcpSocket` and `openTcpSocket(loop, family)`**: bind, then connect or listen, with options. +- **`core::net::IAsyncDatagramSocket` and `openAsyncDatagramSocket(loop, family)`**: a UDP socket on an + `EventLoop` (readiness on POSIX, the completion port on Windows), and + `testing::InMemoryAsyncDatagramNetwork`. +- **`core::net::openStandardStreams(loop, blocking, handles, maxReadChunk)`**: the process's standard input, + output and error as coroutine streams (`IInputStream`, `IOutputStream`), waiting on the loop where the OS + allows and on the blocking executor otherwise; `processStandardHandles()`, `classifyStreamHandle()`. +- **TLS**: `ITlsContext::wrapClient()` with `TlsPeer`, which binds one client connection to the host it was + dialled for (SNI and a host check for a name, an IP-SAN check for an address literal); + `ISocket::tlsSession()`; `ITlsSession::failure()` (`TlsFailure`) and `negotiatedProtocol()`; + `TlsOptions::alpn`; `TlsClientOptions`; `TrustAnchors`, `trustAnchorsFromPem()`, `IChainVerifier` (its + `verify()` finishes on the verifier's own executor and hands only a parked wait back to the asking + socket's loop, and a stop ends the socket's wait for it, bounded by + `TlsClientOptions::maxVerificationsInFlight`, 256, past which a handshake fails `ResourceExhausted` and + may be driven again) and `TrustSource`; the verifying, fail-closed + `makeTlsClientContext(TrustSource, TlsClientOptions)`, whose `wrapClient()` refuses an empty server name; the trust + stores of `` (`ITrustStore`, `makePemTrustStore()`, `makeFileTrustStore()`, + `trustBundleLocations()`), loaded as a `Task`; and `makeSystemTlsClientContext()`, which verifies through + Security.framework on macOS and CryptoAPI on Windows, and through the file store elsewhere. No verifier + fetches a missing intermediate from a certificate's AIA URL, so an incomplete chain is refused everywhere. +- `core::net::acceptLoop()` (``): the accept loop `net::serve()` and + `http::serveHttp()` share. +- `core::constantTimeEquals()` and `core::secureZero()` in ``, for code that links no + TLS. +- `core::platform::cacheHome()`: `XDG_CACHE_HOME`, then `LOCALAPPDATA`, then the OS's row below the home + directory. +- `CORE_CPP_WITH_FS` and `CORE_CPP_WITH_HTTP` (both ON). + +### Changed + +- `core::net_tls` links Security.framework and CoreFoundation on macOS and `crypt32` on Windows, PRIVATE. +- `core::fs` links `ntdll` and `advapi32` on Windows, PRIVATE. +- `tlsSessionOf()` finds the session behind a forwarding decorator: it is `ISocket::tlsSession()`, which every + decorator forwards. +- The pinned-name `makeTlsClientContext(caPem, expectedHostName, options)` offers `TlsOptions::alpn`. + +### Fixed + +- **core-cpp configures as a subproject on a Clang without `clang-scan-deps`.** It sets CMP0155 OLD in its own + directory scope (where CMake knows the policy: 3.28 on, so the setting is guarded), so its `try_compile()` + probes no longer scan for module imports that nobody asked for; a parent's `CMAKE_CXX_SCAN_FOR_MODULES=ON` + still applies. CMake 3.25 to 3.27 scan for no modules, so they never had the problem, and the check that a + subproject asking for modules is still refused runs from 3.28 on. +- **The asynchronous resolvers refuse a host that names no host.** `ThreadedAddressResolver`, + `ExecutorAddressResolver` and `InlineAddressResolver` answer `AddressError` for an empty host (which `getaddrinfo` took as the wildcard + address), one with an embedded NUL, or one longer than 253 bytes, before any lookup + (`detail::checkLookupHost()`). +- A scoped IPv6 literal (`fe80::1%eth0`) is resolved by `getaddrinfo` on every platform: macOS's `inet_pton` + dropped the zone, so the literal fast path dialled a link-local address on no interface. + ## [0.23.0] - 2026-11-24 ### Changed diff --git a/docs/modules/async.md b/docs/modules/async.md index aba33723..fe1246ee 100644 --- a/docs/modules/async.md +++ b/docs/modules/async.md @@ -271,6 +271,28 @@ bottoms out in a `DetachedTask`. `whenAll`'s and `whenAny`'s runners carry it to coroutine type of its own between a detached root and the task that parks, and one that did not carry the answer would make every park underneath a combinator read as *somebody owns this*. +## Offloading a blocking call + +`` has `offload(home, blocking, work)`: the awaiting coroutine hops to the +`blocking` executor, calls `work` there, and hops back to `home` before it sees the result, so a +caller on a loop never runs the blocking call itself and never resumes on a pool thread. It is how +[fs](fs.md), the standard output and error streams, the trust stores and the platform chain +verifiers of [net](net.md) reach the operating system; nothing in it owns a thread. + +- **The stop token is read once, before the hop.** A stop already requested throws + `OperationCancelled` and `work` never runs. Once `work` has run, its result is returned whatever + the token says by then: a write that completed, or a handle that was opened, is never dropped + because a stop arrived while it was in flight. What `work` throws is rethrown on `home`. +- **`work`'s result is a value, never a reference** (a `static_assert`), and the executors are + pointers, because a reference parameter of a coroutine would name storage the caller may destroy + while it is suspended. Both must outlive the returned task. +- **Teardown: drain or stop `blocking` before `home` is destroyed**, so no job resumes a dead + executor. +- **A call that may never return does not belong here.** `offload` resumes only once `work` has + returned, so a read of a terminal that waits for input would hold its waiter for as long. The + resolver and the standard input wait through `net::detail::ParkedCall` instead, which hands the + waiter back on a stop and leaves the call running. + ## Strands and the current executor Written for 0.4.0 after morph's `StrandExecutor` (morph PR #806); see diff --git a/docs/modules/base.md b/docs/modules/base.md index 5c35d416..18d0a7ea 100644 --- a/docs/modules/base.md +++ b/docs/modules/base.md @@ -94,15 +94,21 @@ only on the length; inputs of different lengths compare unequal at once, since a is public. `secureZero()` writes every byte through a `volatile` pointer and ends with a memory barrier, so the stores survive even when the buffer is never read again. -- **Both are out of line, and the barriers are compiler barriers, not just calls.** The barrier is - an empty `asm volatile` under GCC and Clang (`ValueBarrierGnu.cpp`) and a `volatile` object under - MSVC's front end, cl and clang-cl (`ValueBarrierMsvc.cpp`), chosen by +- **Both are out of line, and the barriers are compiler barriers, not just calls.** Under GCC and + Clang both are an empty `asm volatile` (`ValueBarrierGnu.cpp`), the memory barrier with a `memory` + clobber. Under MSVC's front end, cl and clang-cl (`ValueBarrierMsvc.cpp`), the value barrier is a + `volatile` object and the memory barrier is `std::atomic_signal_fence(std::memory_order_seq_cst)`, + a compiler fence that emits no instruction: a `volatile` access orders only other `volatile` + accesses, so it alone would not keep the zeroing stores in place. The file is chosen by `CMAKE_CXX_COMPILER_FRONTEND_VARIANT`. Either survives inlining, link-time optimisation included. - **A unit test cannot see a timing difference**, so the test checks the answers and the guarantee is checked by reading the release disassembly: the compare loop's only branches are on the index, never on the data. -- `core::net`'s TLS layer keeps OpenSSL's `CRYPTO_memcmp` for the comparisons it makes; these are - for code that links no TLS. +- **`core::net::constantTimeEquals()` stays on OpenSSL's `CRYPTO_memcmp`**, and `core::net_tls` + does not call these. The network-facing token and fingerprint checks of core-cpp's consumers go + through it, and OpenSSL's comparison is written per architecture, in assembly where it has one, so + it does not depend on a compiler honouring a barrier; moving it here would trade that guarantee for + nothing. These are for code that links no TLS: a key cache, a MAC over a file. ## Paths and UTF-8 diff --git a/docs/modules/fs.md b/docs/modules/fs.md new file mode 100644 index 00000000..2c0d66a3 --- /dev/null +++ b/docs/modules/fs.md @@ -0,0 +1,394 @@ +# fs + +The descriptor-relative file system: directories opened as roots, and every other operation +relative to a descriptor, resolved beneath it. Namespace `core::fs`, directory `src/core/fs/`, +target `core::fs`. It links [base](base.md), [async](async.md) and [platform](platform.md), and +`ntdll` and `advapi32` on Windows. Built with `CORE_CPP_WITH_FS` (ON), natively only: Emscripten and +WASI have no descriptors to hold. + +What it is for: a host that hands a guest, a plugin or a request handler one directory and must be +sure that nothing reached through it lies outside it. Every operation is an `async::Task`, every +blocking system call runs on an executor the embedder injects, and every refusal is an `FsError` +value. + +| Header | What it has | +|---|---| +| `` | `IDescriptorFileSystem` (`openPreopen()`, `relation()`), `IDescriptor` (the byte, metadata and `*At` operations), `IDirectoryStream`; `DescriptorFlags`, `OpenFlags`, `CreationAccess`, `SymlinkPolicy`, `Advice`, `StreamEnd`, `DescriptorType`, `DescriptorStat`, `FileTime`, `NewTimestamp` (`NoChange`, `SetToNow` or a `FileTime`), `DirectoryEntry`, `MetadataHash`, `ReadChunk`, `Relation`; `hasFlag()` and `operator|` for both masks | +| `` | `makeNativeDescriptorFileSystem(home, blocking, wallClock, random, options)`, `NativeFileSystemOptions`, `BeneathStrategy`, `DefaultMaxSymlinkHops` (40), `DefaultMaxAncestorDepth` (4,096) | +| `` | `FsErrorCode` and its `toString()`, `FsError` (a category, the raw errno, Win32 error or NTSTATUS, and a context), `FsResult`; the classification tables `systemErrorTable()`, `ntStatusTable()`, `noFollowSymlinkErrnos()`, and `fsErrorFromSystemCode()`, `fsErrorFromNtStatus()` | +| `` | `PathPolicy` (`PathEncoding`, `CaseRule`, `TrailingDotsAndSpaces`), `posixPathPolicy()`, `windowsPathPolicy()`, `nativePathPolicy()`, and `isRootedLinkTarget()` | +| `` | `Operation`, `RightsRow`, `rightsTable()`, `checkRights()`, `checkOpenRights()`, `grantedFlags()` | +| `` | `AccessScope`, `AccessFacts`, `AccessEntry` and `classifyAccess()`, the pure decision of who may reach an object | +| `` | `testing::InMemoryDescriptorFileSystem` and `testing::IdentityModel`: the same contract over nodes in memory | + +## Off the loop + +epoll and kqueue cannot wait on a regular file, so "non-blocking" here means **off the loop's +thread**. `makeNativeDescriptorFileSystem()` takes two executors: every system call of the file +system's operations and of its descriptors runs on `blocking` through [`async::offload`](async.md#offloading-a-blocking-call), +and the caller resumes on `home`. Building the file system is the exception: it runs on the calling +thread and makes the few calls that set it up (on Linux the `openat2` probe and the open of +`/proc/self`), so build it before the loop runs or off it. Nothing in the module creates a thread; +`blocking` is typically an `async::ThreadPoolExecutor` the embedder owns. + +- **A stop is honoured before the hop, never after.** A flow stopped before it hops throws + `async::OperationCancelled` and nothing runs; once the call has run, its result is returned, so a + completed write's count or an opened handle is never dropped. +- **A handle is shared by every call in flight on it.** A descriptor dropped while a call of it is + parked on `blocking` keeps its native handle open until that call has returned, so the call never + reaches another file that reused the number. The close itself is queued on `blocking` too. +- **Teardown: drain or stop `blocking` before `home` is destroyed.** A close still queued when + `blocking` is destroyed runs there and then. +- `home` and `blocking` may be the same executor. Every system call then runs on the loop's + thread: a single-threaded embedder's choice, visible at construction. +- **A read is bounded by the host.** `IDescriptor::read` clamps what it is asked for to + `NativeFileSystemOptions::maxReadChunk` (1 MiB by default; 0 is refused at construction), so a + caller cannot make the host allocate what it asks for. Buffers are owned across the hop: `read` + returns a `std::vector`, `write` and `append` take one by value. +- **A directory is read in batches.** `IDescriptor::readDirectory` opens an `IDirectoryStream` that + holds one batch of entries at a time, never the whole listing. + +`NativeDescriptor_test.cpp`'s *native: every descriptor operation parks on the blocking executor* +runs every `IDescriptor` operation on a manual executor and holds that each one parks there. + +## Beneath resolution + +**The kernel never resolves a path's final component**, and never resolves anything from outside +the descriptor. Every final call is made without following (`AT_SYMLINK_NOFOLLOW`, `O_NOFOLLOW`, +or a held handle: `fstat`, `futimens`, `FileBasicInfo` by handle); where a call says +`SymlinkPolicy::Follow`, following is the walk's splice, for the last component too. + +| Input | Answer | +|---|---| +| `""` | `NoEntry` | +| `"."`, `"a/."` | the directory itself, resolved to a held handle and operated on through it | +| an absolute path; `..` above the descriptor; a symbolic link whose target is rooted (`isRootedLinkTarget()`) or leaves the descriptor; `symlinkAt` with a rooted target; a Windows reserved device name | `NotPermitted` | +| a NUL, a character the policy forbids, a trailing dot or space where the policy refuses it, a name holding what the kernel would split on (`/`; `\` and `:` on Windows) | `Invalid` | +| a name that is not UTF-8; a directory entry that cannot be represented as UTF-8 | `IllegalByteSequence` | +| `linkAt` with `SymlinkPolicy::Follow` | `Invalid`, as in wasmtime | +| more than `maxSymlinkHops` (40) links in one resolution; opening a final link with `NoFollow` | `Loop` | + +`BeneathStrategy::Best` is `openat2(RESOLVE_BENEATH | RESOLVE_NO_MAGICLINKS)` on Linux, probed once +per file system; `ComponentWalk`, one component at a time over held directory handles (`openat` with +`O_NOFOLLOW` on POSIX, `NtCreateFile` with a `RootDirectory` on Windows), is used everywhere else +and wherever the probe finds no `openat2`. Under `openat2`, `EXDEV` is `NotPermitted`, `EAGAIN` is +retried 8 times and then that call walks, and an `ENOSYS`, `EPERM` or `EINVAL` after the probe makes +that call walk too. The choice is the file-system instance's, never a global. A Linux build needs +no `openat2` in the system headers: `struct open_how`, the two `RESOLVE_` bits and system call 437 +are spelled in `linux/Openat2.hpp`, the ABI the kernel keeps, and the test checks them against +`` where it is present. + +**Name rules are data.** A `PathPolicy` is one row: the separators of a path and of a link target, +the reserved names, the volume separators, the forbidden characters, the encoding, the case rule and +the trailing dot or space rule. `nativePathPolicy()` is the build's row, overridable through +`NativeFileSystemOptions::policy`; the contract suite runs both rows on every OS. + +| | `posixPathPolicy()` | `windowsPathPolicy()` | +|---|---|---| +| Separators of a path | `/` | `/` and `\` | +| Separators of a link target | `/` | `/` and `\` | +| Volume separators | none | `:` (a first component holding one names a volume) | +| Forbidden | NUL only (refused in every text, whatever the row) | NUL, `<>:"?*`, the vertical bar and the control characters 1 to 31 | +| Reserved stems | none | `CON PRN AUX NUL COM0-9 LPT0-9 COM¹²³ LPT¹²³ CONIN$ CONOUT$`, in any case; the stem is what precedes the first dot, trailing spaces dropped (`nul.txt`, `COM1 .log`) | +| Encoding | the UTF-8 bytes | UTF-16 | +| Case | sensitive | insensitive (ASCII folded) | +| Trailing `.` or space | allowed | `Invalid` | + +`openPreopen()` takes a `std::filesystem::path` the host chose, which is not held to a policy. + +On Windows a junction, a mount point and every other reparse point that names an object by an +absolute path is a link that is never followed (`NotPermitted`), and `readlinkAt` of one is +`NotPermitted` too, so no host path is handed out; the full list of Windows differences is the doc +comment of `makeNativeDescriptorFileSystem()`. + +### Rooted link targets + +`isRootedLinkTarget(target, policy)` answers whether a symbolic link's target names a root rather +than a place relative to the link: it starts with one of the policy's target separators, or its +first component holds one of its volume separators. Every link a walk follows, every `symlinkAt` and +every `readlinkAt` asks it, so the rule has one definition: a rooted target the host planted is read +by nobody (`NotPermitted`, as WASI 0.3.2's `readlink-at` answers), in the in-memory model as natively. + +| Target | POSIX rules | Windows rules | +|---|---|---| +| `/etc`, `/x` | rooted | rooted | +| `\x` | relative | rooted | +| `C:`, `C:x`, `C:\x` | relative | rooted | +| `\\server\share`, `\\?\C:\` | relative | rooted | +| `a/b`, `a\b`, `../x`, `..\x` | relative | relative | +| `""` | not rooted | not rooted | + +A relative target that climbs out (`../x`) is not rooted; resolution refuses it where it leaves. + +## Rights + +A descriptor carries `DescriptorFlags`, and **every implementation enforces them**, the in-memory +one included, from one table: `rightsTable()` names, per `Operation`, the flags the descriptor it is +called on must carry one of. A refusal is `NotPermitted`, before anything is touched. + +| Needs | Operations | +|---|---| +| nothing | `advise`, `sync`, `syncData`, `stat`, `type`, `metadataHash` | +| `Read` | `read`, `readDirectory`, `openAt`, `statAt`, `readlinkAt`, `metadataHashAt` | +| `Write` | `write`, `append`, `setSize` | +| `Write` or `MutateDirectory` | `setTimes` (a file has only the first to offer, a directory only the second) | +| `MutateDirectory` | `createDirectoryAt`, `setTimesAt`, `linkAt` and `renameAt` (on both directories), `removeDirectoryAt`, `symlinkAt`, `unlinkFileAt` | + +`checkOpenRights(parent, open, child)` bounds what a child opened by `openAt` may carry: `Read` +needs the parent's `Read`; `Write` or `MutateDirectory`, and `Create`, `Truncate`, `Exclusive` or +`OwnerOnly`, need the parent's `MutateDirectory`; the three sync flags are a mode, not a right. Then, +as wasmtime orders it: `Directory` with `Create`, `Truncate`, `Exclusive` or `OwnerOnly` is +`Invalid`, a directory never carries `Write` (`IsDirectory`), and `OwnerOnly` without both `Create` +and `Exclusive` is `Invalid`. `grantedFlags()` drops `MutateDirectory` from a descriptor that turns +out to be a file. + +**A descriptor of another implementation, or of another instance, is foreign.** `linkAt` and +`renameAt` with one answer `CrossDevice`, `isSameObject` answers `false`, and `relation()` answers +`CrossDevice`. No raw handle crosses the interface; a decorator passes its inner descriptor. + +## Owner-only creation and access scope + +For a cache or a key that no other user may read, at any moment: + +- `openAt(…, OpenFlags::Create | OpenFlags::Exclusive | OpenFlags::OwnerOnly, …)` creates a file + no other user can reach under its final name or before it; `OwnerOnly` without `Create` and + `Exclusive` is `Invalid`. +- `createDirectoryAt(path, CreationAccess::OwnerOnly)` does the same for a directory; + `CreationAccess::Default` is what the system gives (POSIX `0777` less the umask, Windows the + inherited DACL). + +| OS | How | +|---|---| +| Linux | mode `0600`/`0700` given to `openat`/`mkdirat` itself; a default ACL cannot widen it, since each entry it hands down is capped by the mode | +| macOS, FreeBSD | an inherited ACL could widen it, so the object is made inside a fresh staging directory beside it (created `0700`, its inherited ACL stripped and its access verified before anything is made in it), stripped and verified itself, then linked (a file) or renamed over an empty placeholder (a directory) to its final name, which fails where something exists | +| Windows | owned by the process token's user, with a protected DACL (nothing inherited) granting that user alone, given to `NtCreateFile` itself; a directory's entry is inheritable. The access is read back through the new object's own handle: a file system that keeps no security descriptor (FAT, exFAT) drops it silently, and the object is then deleted through that handle | + +Nothing has been written to the object when the call returns. Where a step fails, what was made is +removed through the parent's handle and the call fails: `NotPermitted` where the access read back +is not `OwnerOnly`, else what refused the step. + +**`DescriptorStat::access` says who may reach an object**, read from the handle the stat was made +through. Each OS has a reader that fills one OS-neutral `AccessFacts`, and `classifyAccess()` is the +one decision, pure and tested with every OS's rows on every OS: + +| OS | Read from the handle | `OwnerOnly` | `ForeignOwner` | `Shared` | `nullopt` | +|---|---|---|---|---|---| +| Linux | `fstat`, and `fstatfs` and the NFSv4 ACL attributes | owned by the effective uid, `mode & 077 == 0` (POSIX ACL entries are bounded by the group bits) | another uid owns it | any group or other bit | an NFS or SMB mount, an object with an NFSv4 ACL (ZFS `acltype=nfsv4`); every `statAt` | +| OpenBSD, DragonFly | `fstat` | as Linux | another uid owns it | any group or other bit | never | +| NetBSD, other POSIX | nothing (their ACLs are not read) | never | never | never | always, so owner-only creation is refused | +| FreeBSD | `fstat`, the NFSv4 ACL | as Linux, and the ACL absent or trivial | another uid owns it | a mode bit, or a non-trivial ACL | the ACL cannot be read; every `statAt` | +| macOS | `fstat`, the extended ACL | as Linux, and no extended ACL entry | another uid owns it | a mode bit, or any extended ACL entry | the ACL read fails; every `statAt` | +| Windows | owner and DACL, on a handle opened with `READ_CONTROL`; the token's user | owned by the user, and every ALLOW entry, explicit or inherited, names the user, LocalSystem or BUILTIN\Administrators | another owner, BUILTIN\Administrators included | a NULL DACL; an ALLOW entry granting any right to another SID; an entry of unknown type | the DACL withholds `READ_CONTROL` | + +DENY entries never widen access and are ignored. **`Shared` is zero, and `nullopt` means "cannot +judge"**: a consumer guarding a secret refuses `nullopt` as it refuses `Shared`. Nothing here is +decided by name; the facts are read off the handle the caller then uses. + +`core::constantTimeEquals()` and `core::secureZero()`, which such a consumer also needs, are in +[base](base.md#constant-time). + +## Containment: `relation()` + +`IDescriptorFileSystem::relation(first, second)` answers whether one opened directory is, contains +or lies beneath another: `Same`, `FirstContainsSecond`, `SecondContainsFirst` or `Unrelated`. It is +what a host needs to refuse a grant that would expose a directory it keeps for itself (a key +directory under a granted home directory), and it decides **on the opened handles, never on path +text**: a symbolic link or a junction on either path, or a rename after the open, changes nothing; +what counts is where each directory is now. + +`Same` is zero, so a zero-initialized `Relation` refuses in a guard that admits only `Unrelated`. +Both descriptors are read before the task first suspends; neither needs to outlive it. + +### How it decides + +Each directory's real parents are walked up to the root of the process's view and compared by +identity: + +- **POSIX**: `(st_dev, st_ino)`. Each parent is `openat(current, "..", O_DIRECTORY | O_NOFOLLOW)` + (`O_PATH` where the system has it, so a directory the user may search but not read is walked + through), until `..` is the directory itself. The kernel's own `..` crosses mounts upward, bind + mounts included. +- **Windows**: volume serial number and 128-bit file id (`FILE_ID_INFO`). `NtCreateFile` has no + `..` relative to a handle, so the walk is by name: the handle's final path by volume GUID, every + junction and link resolved, then each ancestor prefix opened for its attributes only, without + following a reparse point. At a volume's root the walk goes on from each folder the volume is + mounted on; a drive letter is a root. Identities count only on NTFS and ReFS + (`StableFileIdRows.cpp`); FAT, exFAT, every share and every other file system, and a zero id, are + `Unsupported`. +- **The in-memory model**: its nodes' parent links; `IdentityModel::Unavailable` answers + `Unsupported`, so a consumer tests its fail-closed path on every OS. + +Each walk stops after `NativeFileSystemOptions::maxAncestorDepth` (4,096) parents with `Loop`, and +grows its chain per step, so a deep tree costs what it walks. **A containment the walks meet is +always real.** An `Unrelated`, though, is only as good as the walks' view of the tree, and the +mounts a walk leaves are where that view has holes. + +### Mounts that hide directories + +A mount that shows only a subtree of its file system hides that file system's directories above +the subtree from a walk that leaves it: the kernel's `..` at the mount's root goes to the directory +it is mounted on. A bind mount of `/data/a` at `/m` is the plain case: a walk from `/m/x` reaches +`/`, never `/data`, so `/data` and `/m/x` would look unrelated while one contains the other. Every +mount a walk leaves is therefore kept, and an `Unrelated` stands only where none of them could hide +the other directory; otherwise the answer is `Unsupported`. + +**Linux** (5.8 or later, for `STATX_MNT_ID`; an older kernel names no mount, and every relation that +leaves one is `Unsupported`) names the mount of each directory by `statx(STATX_MNT_ID)` and looks it up in +`/proc/self/mountinfo`, read through a handle on `/proc/self` opened when the file system was built: + +- the file system is the mount's superblock device (mountinfo's `major:minor`), never `st_dev`, + which a btrfs subvolume changes; +- what the mount shows is mountinfo's *root* column: `/` for the whole file system, a path for a + subtree (a bind mount of a subdirectory, a btrfs subvolume); +- Linux's `..` leaves a mount only at its root. + +So an `Unrelated` across a mount left at its root stands where the mount shows its whole file system; +where the other directory is on that same mount; where it is on another file system; or where it is +reached through another mount of the same file system whose root is **not above** the left mount's +root. Two btrfs subvolumes mounted at `/` (root `/root`) and `/home` (root `/home`) decide against +each other; the bind mount above (root `/data/a`, the other directory under a mount of root `/`) +is `Unsupported`. A mount missing from mountinfo, or a line that does not parse, is known by its id +alone, a mountinfo over 16 MiB is not read, and `/proc/self` that could not be opened makes every +relation `Unsupported`. + +**macOS and the BSDs** name a mount by `fstatfs`: its file system id and where it is mounted +(`f_mntonname`); the file system is `st_dev`. These systems say nowhere which subtree a mount +shows, so another mount of the same file system never decides: an `Unrelated` stands where the +other directory is on the mount left, or on another file system. + +**A file system that may show another's directories as its own** has no identity that says what it +shows, so a walk that leaves one, or a directory on one, decides only on that same mount and is +otherwise `Unsupported`. The types are a table per system: + +| System | Types that may re-expose another file system | +|---|---| +| Linux | `overlay`, `aufs`, `shiftfs`, every `fuse*` type (sshfs, bindfs, a passthrough), every `nfs*` type, `cifs`, `smb3` | +| macOS, BSDs | `nullfs`, `unionfs`, every `fuse*` type, `macfuse`, `osxfuse`, `bindfs`, every `nfs*` type (fuse-t reports `nfs`), `smbfs`, `afpfs`, `webdav` | + +A network share is in the table because it may be a loopback export of this machine. A type that +cannot be read counts as one. sshfs fails closed with the rest. + +**macOS firmlinks.** `/Users`, `/private` and the other firmlinks lead from the system volume into +the Data volume below its root, and their `..` is the system volume's root. A walk from +`/Users/me/x` therefore leaves the Data volume below its root, and skips (a) the Data volume's +directories above the one it left from and (b) every directory on the Data volume's mount point +path: `/System`, `/System/Volumes` and `/System/Volumes/Data` (the volume's root as that path +reaches it). A directory is its mount's root only where its identity is that of what `f_mntonname` +names (`ATTR_DIR_MOUNTSTATUS` is asked first); otherwise the step left below the root, and the +skipped set (b) is read by `(st_dev, st_ino)`, each component of the mount point path opened +without following from the root handle. Where the directory left from is a child of the volume's +root, (b) is all that was skipped; otherwise the volume's own directories between are unknown. +Unless the other directory's walk passed through the directory left from (it then lies at or below +it, and is none of what was skipped), the answer is `Unsupported` where nothing could be read, +where the other directory is one of the skipped set, or, where more than the set may have been +skipped, where it is on the Data volume. A home directory against `/private/tmp` stays decided; a +grant of `/System/Volumes` against a directory in the home directory is `Unsupported`. This rule is +checked before every shortcut, since a skipped directory on the mount point path is on another +volume. + +Any other POSIX system knows a mount by its device alone: every step that changes device is taken +to leave below the root, from a type that may re-expose, and every `Unrelated` past a change of +device is `Unsupported`. Windows walks by final path and through every folder a volume is mounted +on, so it needs none of this. + +### Mounts beneath a directory + +A walk goes up, so it never sees a mount **beneath** either directory, and such a mount can put the +other directory inside it: a bind mount of `/secret` at `/home/me/work/m` puts `/secret/key` beneath +a grant of `/home/me/work`, though neither walk meets the other. So before an `Unrelated` stands, +the mount table is read and every mount point strictly beneath either directory is opened; the +answer is `Unsupported` where one of them is of the other directory's file system, of a type that +may re-expose another (the table above), where the other directory's own file system may, or where +either file system cannot be named. + +- **The table**: Linux's `/proc/self/mountinfo` (its mount point column), refused whole if one line + does not parse; macOS and the BSDs' `getfsstat` (never `getmntinfo`, whose buffer every thread + shares). Any other POSIX system lists no mounts, so no `Unrelated` stands there at all. +- **Beneath, by identity**: each mount point's path is followed from the root one component at a + time, never through a link. A component is told apart by `(st_dev, st_ino)` from `fstatat` before + it is entered, which needs search permission on its parent alone: the path stays on the + directory's own walked ancestry until it reaches the directory itself, and the first component + that is neither ends the check without entering it -- so a mount under another user's private + directory costs nothing. A component told apart is entered only as that directory: `fstat` on the + handle `openat` returned must give the identity `fstatat` did, and a rename between the two is + `Busy`. A component beneath the directory that cannot be opened is refused. +- **The mount that opens**: the path must open onto the mount the table named (Linux: its mount id; + macOS and the BSDs: its file system id and `f_mntonname`). One made over it, a row that moved, or + a mount stacked under another at one place, is `Unsupported`. +- **The table is read again** once both scans are done, and a difference is `Busy`. + +A mount at the directory itself is not beneath it: an opened directory shows what it showed when it +was opened, and a mount made over its path later is not reached through the handle. + +### Races + +**Each answer is checked after the walk.** On POSIX both directories are walked twice, and any +difference between the passes is `Busy`; on Windows every handle's and every ancestor's final path +is read again once the walks are done, and a change, or a failure on the way a change could +explain, is `Busy`. What remains, documented rather than detected: + +- **ABA on POSIX.** A directory moved away and back between the two passes is not seen; each chain + is still one that existed. +- **A mount path changed after the second pass.** The other directory's mount is read once both + passes are done; a remount, or a rename of a component of a mount point path, between the second + pass and that read is not seen. On macOS that path is on the sealed system volume, so this needs + root with System Integrity Protection off. +- **A mount beneath a directory whose path no longer reaches it.** The scan follows each mount + point's path from the root, so a mount the path cannot reach -- made beneath a directory before + another mount was made over that directory's path, or beneath a second path a bind mount shows the + same directory at -- is not seen from that path. Making either needs the privilege to mount. +- **A mount made after the answer.** The scan sees the mount table as it was while it ran; a mount + made beneath either directory afterwards is not seen, and no answer can foresee one. A host asks + at the moment it grants and holds the grant to that answer: Isoline's preopen grant (P14a) + evaluates the relation at grant time. +- **The directory the Data volume is mounted over** (the system volume's own `/System/Volumes/Data`) + is not in the macOS skipped set, which reads what the mount point path reaches: the Data volume's + root. It cannot be opened once the volume is mounted over it at boot, so no descriptor names it. + +### What the answer means for a caller + +| Answer | Meaning | What a guard does | +|---|---|---| +| `Same`, `FirstContainsSecond`, `SecondContainsFirst` | the containment is real | refuses the grant it guards against | +| `Unrelated` | neither lies beneath the other, no mount left on the way can hide one from the other, and no mount beneath either can show the other | admits | +| `Unsupported` | this layout cannot be decided: no stable identities (FAT, a share, `IdentityModel::Unavailable`), a mount of a subtree that may hide one from the other, a mount beneath one that may show the other's file system, a re-exposing file system, or a fact the system would not give | refuses. It is a property of the layout, not a transient: asking again gives the same answer, so say which grant could not be checked | +| `Busy` | a rename during the walk could have changed the answer | may ask again; refuses if it cannot | +| `Loop` | more than `maxAncestorDepth` parents | refuses | +| `NotDirectory` | either is not a directory | refuses | +| `CrossDevice` | a descriptor of another file system instance | refuses | +| `Access` and other system errors | a parent the user may not search, or what refused opening one | refuses | + +Only `Unrelated` admits. A guard written as `if (relation == Relation::Unrelated) admit();` over a +`FsResult` that holds a value fails closed on every other answer, and on a +zero-initialized one. + +## The in-memory model + +`testing::InMemoryDescriptorFileSystem(home, blocking, clock, policy, maxReadChunk, identities, +maxAncestorDepth)` is held to the same contract as the native one, through the same code where +there is code to share: paths are planned and links spliced by the walker's own functions under the +policy it is given, rights come from `rightsTable()` and `checkOpenRights()`, and the policy's case +rule decides whether two names are one. Every operation suspends through `async::offload`, as the +native one does, so a cancellation or teardown case over it sees the parked state it is about. +`addDirectory()`, `addFile()` and `addSymlink()` build a tree; `setAccessFacts()` models any OS's +owner and ACL. A write or a size beyond 1 GiB is `FileTooLarge`. + +## Limits + +- **No change notification, no advisory lock, no memory map**: `IDescriptor` has none. +- `statAt` on macOS and FreeBSD reports `access` as `nullopt`: an ACL is read from a handle or not + at all. +- Windows needs `SeCreateSymbolicLinkPrivilege` for `symlinkAt`, refuses `renameAt` of a directory + over an existing empty one where POSIX replaces it, and refuses a reparse point a filter serves by + redirecting the open elsewhere (a container's placeholders). + +## Tests + +| Test | Binary | Labels | What | +|---|---|---|---| +| `core-cpp.fs` | `core-cpp-fs-test` | `core-cpp`, `fs` | the contract suite over both the native and the in-memory file system, under both path policies; the escape table and the mid-walk swap (`DescriptorEscape_test.cpp`); every operation parking on the blocking executor; the access-scope rows; `relation()` natively per OS, Linux mounts in a user namespace of their own and the macOS firmlinks included | +| `core-cpp.fs-alloc`, `core-cpp.fs-memory`, `core-cpp.fs-relation-memory` | `core-cpp-fs-alloc-test`, `core-cpp-fs-memory-test`, `core-cpp-fs-relation-memory-test` | `core-cpp`, `fs` | with the global allocation functions replaced: a queued close that cannot be allocated, and what a directory stream and a relation walk hold. POSIX only, and not under a sanitizer | + +The Linux mount rows (`linux/Relation_test.cpp`) run in a user and mount namespace of their own +and SKIP where the system refuses one; CI sets `CORE_TEST_REQUIRE_USERNS=1`, which turns that skip +into a failure. diff --git a/docs/modules/http.md b/docs/modules/http.md new file mode 100644 index 00000000..e4039c90 --- /dev/null +++ b/docs/modules/http.md @@ -0,0 +1,142 @@ +# http + +HTTP/1.1 (RFC 9110, RFC 9112) as coroutines: the message vocabulary, the framing rules, a +connection with streamed bodies and trailers, a client that keeps connections alive, and a +keep-alive server. Namespace `core::http`, directory `src/core/http/`, target `core::http`. It links +[base](base.md) and [net](net.md) (and [async](async.md) through it). Built with +`CORE_CPP_WITH_HTTP` (ON), natively only. + +**HTTP/1.1 only.** No HTTP/2 or 3, no client pipelining, no upgrade (a `101` is a `ProtocolError` +on the client), and the server answers pipelined requests one at a time. `core::net`'s older +`serve()` in `` is a separate, minimal server and is unchanged; the two +share only `net::acceptLoop()`. + +| Header | What it has | +|---|---| +| `` | `HttpErrorCode` (one code per case of `wasi:http`'s `error-code`, in its order) and its `toString()`, `HttpError` (the code, the payload its case carries, a detail and a `RefusalReason`), `HttpResult`; `HttpVersion`; `Field`, `Fields`; the validating `Method::parse()`, `RequestTarget::parse()` (`RequestTargetForm`) and `ReasonPhrase::parse()`; `RequestHead`, `ResponseHead` | +| `` | `HttpLimits`; `MessageRole`, `BodyFraming`, `Persistence`, `Framing`; `requestFraming()`, `responseFraming()`, `isFramingField()`; `HeadParser` (`Progress`, `FeedResult`), `ChunkedDecoder` (`ChunkStep`), `chunkHeader()`, `lastChunk()` | +| `` | `IBodyReader`, `IBodySource`, `BufferBodySource`, `BodyChunk`, `BodyEnd`, `TrailerIntent`, `framingFor()` | +| `` | `Connection`, `WireTimeouts`, `Reuse` | +| `` | `HttpClient`, `HttpClientOptions`, `HttpTimeouts`, `Origin`, `Scheme`, `defaultPort()`, `OutgoingRequest`, `IncomingResponse` | +| `` | `serveHttp()`, `serveHttpConnection()`, `IHttpHandler`, `IncomingRequest`, `OutgoingResponse`, `HttpServerOptions`, `defaultServerLimits()`, `ErrorStatusRow`, `errorStatusTable()`, `errorStatusFor()`, `statusPhrase()` | +| `` | `testing::ScriptedConnector`, an `net::IConnector` whose connections are in-memory socket pairs, and `testing::ScriptedDial` | + +## The pure layer + +`Message.hpp` and `Framing.hpp` hold no socket; every rule is tested from a table, and the request +smuggling corpus (`SmugglingCorpus.hpp`) is run by both `Framing_test.cpp` and `HttpServer_test.cpp`. + +- **No value that could split a message reaches the wire.** A field name must be a token; a value + holds no CR, LF, NUL or other control character but HTAB, and no leading or trailing whitespace. + `Method`, `RequestTarget` and `ReasonPhrase` exist only through their validating `parse()`. +- **The connection writes the framing.** `Transfer-Encoding`, `Content-Length`, `Connection`, + `Keep-Alive`, `TE` and `Upgrade` (`isFramingField()`), and the client's `Host`, are refused from a + caller. +- **`requestFraming()` refuses what a smuggler sends**: `Transfer-Encoding` with `Content-Length`, + `Transfer-Encoding` in HTTP/1.0, `chunked` twice or not last, a malformed coding list, a + `Content-Length` that is not one decimal value; and a request coding other than exactly + `chunked` (a server answers `501`). Every refusal is fatal to the connection. +- **`HeadParser` holds one line at a time** and refuses past `HttpLimits`: a bare LF or CR, space + before a colon, an obs-fold in a request, two `Host` fields, an invalid one, or none in HTTP/1.1. + `ChunkedDecoder` is a transition table; a chunk size has at most 16 hex digits. +- **`HttpLimits` bounds everything a peer sends**: the head (64 KiB), a field (16 KiB), the number + of fields (100), the trailers (16 KiB), a chunk line (1 KiB), a read (64 KiB, also the + connection's read buffer) and, optionally, the body. Nothing a peer sends makes the host hold more. + +## Connection + +`Connection` is one HTTP/1.1 connection over an `net::ISocket`, either end; its `MessageRole` is +what it reads. Bodies stream in both directions, a chunk at a time, with trailers. + +- **The read side runs head, reader, head.** After a head the caller frames it and asks + `bodyReader()` for its body before the next head read. +- **The request role is serial.** Request N+1's head is read only once response N is written in + full; asked earlier, the read answers `ProtocolError` as a value, consuming nothing. +- **Failures are kept per direction.** A read failure leaves the write side free to answer (400, + 408); a refusal before the first wire byte leaves the connection as it was; a failure after it + breaks that direction. +- **`WireTimeouts`**: `firstByte`, `betweenBytes`, `write`, `head` (from a head's first byte to its + last, a budget of its own) and `body`; **zero means no deadline**. A read deadline retires the + read through `cancelRead()` and keeps the socket open, so a socket decorator that does not forward + `cancelRead` disables the read deadlines. + +## HttpClient + +`HttpClient(loop, connector, tls, options)` sends one request at a time on each connection and +keeps connections alive between requests. + +- **Every step has its own codes.** Checked before the dial (`RequestUriInvalid`, + `ProtocolError`, `ConfigurationError` for `https` without a TLS context); the dial through the + injected `net::IConnector` (`DnsError`, `ConnectionRefused`, `DestinationUnavailable`, + `ConnectionTimeout`); TLS; the exchange. +- **TLS fails closed.** For `Scheme::Https` the client calls `net::ITlsContext::wrapClient()` with + the origin's host, then runs the handshake before any request byte. A context that cannot bind a + connection to a name, every context from the pinned-name `makeTlsClientContext(caPem, + expectedHostName, options)` included, answers `ConfigurationError`; use + `net::makeTlsClientContext(TrustSource, TlsClientOptions)` or `net::makeSystemTlsClientContext()`. + A refused handshake is `TlsCertificateError`, `TlsProtocolError` or `TlsAlertReceived`, with the + `net::TlsFailure` attached. +- **The pool.** Idle connections are kept per origin (scheme, host case-insensitively, effective + port): at most `maxIdlePerOrigin` (4) each, for `idleTimeout` (30 s); at most + `maxConnectionsPerOrigin` (16) open to one origin and `maxConnectionsTotal` (256) to all, idle + ones included. Past a cap, an idle connection of any origin is closed to make room, or the request + is `ConnectionLimitReached` at once, without a dial and without waiting. +- **Interim responses are bounded.** Up to 32 interim (1xx) heads are skipped before the final one; + a 33rd is `ProtocolError`, so a server cannot keep a request reading heads for ever. +- **A connection holding unread bytes is never pooled.** Bytes a server sent past the end of its + response (after a HEAD's `Content-Length` answer, say) answer no request this client sent, so the + connection is closed rather than handed to the next request. +- **A stale pooled connection is retried once**, on a fresh dial, and only where that cannot repeat + an effect: an idempotent method with no body. +- **`send()` completes only once the whole request body is written.** An early final response (a + 413 to an upload) is not returned while the server stops reading, and a body source that waits on + the response body deadlocks. `HttpTimeouts::firstByte` runs from the start of the exchange and the + upload counts toward it, as `wasi:http`'s first-byte timeout does in wasmtime. +- `HttpTimeouts::connect` bounds the dial and then the handshake, each on its own; **zero means no + deadline**, here and in every other timeout. Each of `connect`, `firstByte` and `betweenBytes` + defaults to **600 s**, wasmtime's `wasi:http` default, so a client built with no options still + bounds every wait. + +## serveHttp + +`serveHttp(loop, listener, handler, options)` serves every connection the listener accepts in a +flow of its own, each through `serveHttpConnection()`. The handler is one request in and one +response out (`IHttpHandler::handle()`), its body streamed both ways. + +- **Every wait on a client is bounded by default** (`HttpServerOptions`): the wait for a request's + first byte (`idleTimeout`, 5 s, past which the connection closes unanswered), the head from its + first byte (`headTimeout`, 10 s, then `408`), between body reads (`bodyBetweenBytes`, 10 s), a body + as a whole (`bodyTotal`, 60 s) and each write (`writeTimeout`, 30 s). A body is bounded to 64 MiB + (`defaultServerLimits()`), at most 512 connections are served at once (`admission`), and 1000 + requests per connection. +- **Pipelined requests are served in order, one at a time.** Request N+1 is read once response N is + written in full; the handler never sees two requests of one connection at once. +- **Refusals are one table.** `errorStatusTable()` maps a refused request to `400`, `408`, `411`, + `413`, `414`, `431`, `501`, `505` or `500`; a code with no row (the client went away, a write + failed) and a timeout before any byte of a request are not answered: the connection closes. +- **The connection closes**, with `Connection: close` where the response can still say so, after a + request that asked for it or HTTP/1.0 without keep-alive, the last request of + `maxRequestsPerConnection`, a body over `maxDrainBytes` left unread, `Expect: 100-continue` + answered without the handler reading, a body reader still alive when the response is written, and + any failure. Every close lingers (`net::closeLingering()`). +- **Connections outlive the accept loop.** Closing the listener ends `serveHttp()`, not the + connections it started; they end with their client, their deadlines or the loop. + +## Limits + +- HTTP/1.1 only, no client pipelining, no upgrade, no proxy support; the server is serial per + connection. +- `HttpClient::send()` returns the response head only after the request body is written (above). +- The client does not wait for a connection to come free: past a cap it closes an idle one or + refuses. +- Trust is loaded as a `Task` (`net::ITrustStore::load()`, `net::makeSystemTlsClientContext()`), and + on macOS and Windows a platform verifier, not OpenSSL's store, decides (see [net](net.md)). `http` + itself links no OpenSSL: it reaches TLS only through `net::ITlsContext*` and + `net::ISocket::tlsSession()`. + +## Tests + +| Test | Binary | Labels | What | +|---|---|---|---| +| `core-cpp.http` | `core-cpp-http-test` | `core-cpp`, `http` | the pure layer and the smuggling corpus, `Connection`, `HttpClient` and the server, over `net::testing`'s in-memory pairs on a test loop; TLS through a scripted context, so the binary links no `net_tls` | +| `core-cpp.http_loopback` | `core-cpp-http_loopback-test` | `core-cpp`, `http`, `loopback` | `Connection` and the server over real sockets on every backend this platform builds, and one `HttpClient` round trip against `serveHttp()`, each case under a watchdog | diff --git a/docs/modules/index.md b/docs/modules/index.md index efb92fb4..a15276a0 100644 --- a/docs/modules/index.md +++ b/docs/modules/index.md @@ -14,6 +14,8 @@ namespace is its directory (`src/core/net/` is `core::net`; headers directly in | [platform](platform.md) | `core::platform` | `core::platform` | static | base, log | available | | [async](async.md) | `core::async` | `core::async` | static (shared with `CORE_CPP_BUILD_SHARED`); nearly all headers | Threads | `StopToken`, `Task`, `whenAll`, `whenAny`, `DetachedTask`, `syncRun`, `ParkedWork`, `IExecutor`, `ResumeOn`, `ThreadPoolExecutor` and `AsyncQueue` | | [net](net.md) | `core::net` | `core::net_types`, `core::net`, `core::net_tls` | header-only, static, static | async, platform; OpenSSL for `net_tls` | contour's event loop, sockets, TLS and HTTP server available; the merge with fastcached's: Tasks B2 to B11 | +| [fs](fs.md) | `core::fs` | `core::fs` | static | base, log, async, platform; ntdll and advapi32 on Windows | descriptor-relative file system, native only, with `CORE_CPP_WITH_FS` | +| [http](http.md) | `core::http` | `core::http` | static | base, async, net | HTTP/1.1 messages, framing, client and server, native only, with `CORE_CPP_WITH_HTTP` | | [tui](tui.md) | `core::tui` | `core::tui_output`, `core::tui` | static | `tui_output`: base; `tui`: also platform, async, net, libunicode, stb (optional) | endo's terminal UI available, native only; its runtime is composed on `core::net::EventLoop` (Task B12) | | [testing](testing.md) | `core::testing` | `core::testing`, `core::testing_dialogs`, `core::testing_main` | static, object, static | base; log and Catch2 for `testing_main` | available | @@ -42,6 +44,13 @@ graph BT platform --> log net --> async net --> platform + fs --> base + fs --> log + fs --> async + fs --> platform + http --> base + http --> async + http --> net tui_output --> base tui --> base tui --> tui_output @@ -80,6 +89,7 @@ subset builds, and CI runs its tests under node: | async | everything except `ThreadPoolExecutor.hpp` | | platform | Types (with `NativeHandle`), PlatformError, Clock, StringUtils, PathUtils, GlobMatch, FileUri, and the POSIX `ProcessEnvironment`, `FileInfoProvider` and `WorkingDirectory` behind `nativeProcessEnvironment()`, `nativeFileInfoProvider()` and `nativeWorkingDirectory()` | | net | `net_types` today; `IoBackend`, `EventLoop`, timers, `DeadlineTimer`, `WithTimeout`, the host-driven backend and the test doubles from Tasks B3 to B5; never sockets, DNS, TLS or HTTP | +| fs, http | never | | testing | fully (the Windows parts are no-ops) | | tui | never | diff --git a/docs/modules/net.md b/docs/modules/net.md index da353c3c..147d243d 100644 --- a/docs/modules/net.md +++ b/docs/modules/net.md @@ -7,7 +7,7 @@ directory `src/core/net/`. Three targets: |---|---|---|---| | `core::net_types` | header-only | `NetError`, `NetErrorCode`, `IoResult` | everywhere, Emscripten included | | `core::net` | static | everything else below | Linux, macOS, the BSDs, Windows; under single-threaded WebAssembly, the `IoBackend` contract, the host-driven backend, the event loop and its timers | -| `core::net_tls` | static | the TLS socket and its session, OpenSSH public keys and SSHSIG verification, the ssh-agent client | with `CORE_CPP_WITH_TLS`, natively | +| `core::net_tls` | static | the TLS socket and its session, the trust stores and the platform chain verifiers, OpenSSH public keys and SSHSIG verification, the ssh-agent client. Links OpenSSL, and Security.framework and CoreFoundation on macOS or `crypt32` on Windows, all PRIVATE | with `CORE_CPP_WITH_TLS`, natively | !!! note "Status" contour's `src/net` at `6777ff05`, merged with fastcached's async and networking layer @@ -42,10 +42,15 @@ directory `src/core/net/`. Three targets: | `` | `IoBackend`, the injected blocking wait the loop drives and the readiness dispatcher behind it: `ReadinessHandler` (a handle, an owner and the callbacks a backend invokes), `Interest`, `HandleKind`, `Readiness`, `selectReadinessCallback()`, `BackendKind`, `WaitResult`; and the factories `makeDefaultBackend()`, `makeBackend(BackendKind)` and `preferredBackendKind()`. Every backend's own header is private, so the factories are how a program gets one: poll(2) on POSIX, epoll on Linux, kqueue on macOS and the BSDs, and on Windows an I/O completion port, which `preferredBackendKind()` answers since Task B7b and which is Windows' only backend since 0.5.0: the `WSAEventSelect` + `WaitForMultipleObjects` one it replaced was removed ([core-cpp#6](https://github.com/contour-terminal/core-cpp/issues/6)). `completionPort()` answers non-null on a completion-based backend and `nullptr` on every other, which is how a socket factory knows whether to hand out a socket that issues overlapped operations or one that parks on readiness; `EventLoop::completionPort()` asks it for them. `HandleKind::Completion` is a park on an overlapped operation an owner issued, which is how a completion reaches the loop's turn | | `` | `IHostScheduler::callAfter()`, the one thing a host event loop has to lend core-cpp's, and `HostCallback` | | `` | `HostDrivenBackend`: the backend for a loop that is PUMPED rather than one that blocks. It has no readiness (`attach` and `setInterest` answer `Unsupported`), its `wait()` never blocks, `wake()` and `armWakeAt()` ask the host for a pump and coalesce, and `isHostDriven()` is true. Portable, and the browser is only one of its hosts | -| ``, `` | the transport interfaces. `read`, `readWithFd`, `write`, `writeVectored`, `waitReadable`, `handshakeIfNeeded`, `cancelRead`, `shutdownWrite`, `setReceiveDeadline`, `tlsSession` (null but for a TLS socket, forwarded by every decorator), `close`; `accept`, `boundPort`, `close` and `closeToken` -- a listener's `close()` is the base class's, fires the token (as its destructor does) and runs the implementation's `doClose()`. Every operation is a frame-free, stop-aware awaitable, not a `Task` | +| ``, `` | the transport interfaces. `read`, `readWithFd`, `write`, `writeVectored`, `waitReadable`, `handshakeIfNeeded`, `cancelRead`, `shutdownWrite`, `setReceiveDeadline`, `tlsSession` (null but for a TLS socket, forwarded by every decorator), `localEndpoint`, `remoteEndpoint`, `option`/`setOption` (a `SocketOption`; `Unsupported` where a transport has none), `close`; `accept`, `boundPort`, `localEndpoint`, `option`/`setOption`, `close` and `closeToken` -- a listener's `close()` is the base class's, fires the token (as its destructor does) and runs the implementation's `doClose()`. Every operation is a frame-free, stop-aware awaitable, not a `Task` | | `` | `ResultAwaitable` and its byte-count alias `IoAwaitable`: what a socket operation resolves through, and why it allocates nothing. `core::async::asTask` is the escape hatch for a caller that must store one | | `` | `core::net::contract` — the socket contract's tripwires: `claimReadSlot` and `claimWriteSlot`, which end the process in every build, and the Debug assertions `requireReadBuffer` and `assertTeardownIsSerialisedWithDispatch`; public so a transport outside this library gets them too | | `` | `listen()`, `connect()`, `listenUnix()`, `connectUnix()`, `adoptFd()`, `appendReadChunk()` | +| `` | `ResolvedEndpoint`, the platform's own socket address bytes; `IAddressResolver` with `resolve()` (a failure in words) and `resolveClassified()` (a `NetError`; its default classifies every failure as `AddressError`), `SystemAddressResolver` (`getaddrinfo`, classified through `resolverErrorTable()`: a name that does not exist is `NameNotFound`, a resolver that cannot answer now `ResolverTemporaryFailure`), `defaultAddressResolver()`, `formatPeerAddress()` | +| `` | `IAsyncAddressResolver` (a coroutine `resolve(host, port, loop)` answering a `ResolveResult`) and `InlineAddressResolver`, which calls the blocking resolver inline and never suspends | +| `` | `ThreadedAddressResolver`, which resolves on a pool of its own (`ThreadedResolverOptions`), and `defaultAsyncResolver()` | +| `` | `ExecutorAddressResolver(blocking, inner, ExecutorResolverOptions)`, which owns no thread: every lookup runs on the injected executor, a literal never reaches it, a lookup past `maxInFlight` is `ResourceExhausted` at once, a stop hands the waiter back (`OperationCancelled`) and leaves the lookup its slot until the blocking call returns, and a lookup the executor drops unrun answers `Cancelled`. A stopped `ThreadPoolExecutor` runs what is submitted inline, so stop resolving before stopping its pool | +| `` | `IpSocketAddress` (an `Ipv4Address` or `Ipv6Address`, the port, and IPv6's flow label and scope, all in host order), `AddressFamily`, and the only code that knows the layouts: `toEndpoint()` and `toIpSocketAddress()` (`Unsupported` for any other family) | | `` | `readLine()`, `readUntil()`, `readExactly()` over an `ISocket`, each buffered byte scanned once | | `` | the single writer per connection: whole frames in order, bounded by bytes, with superseding by tag | | `` | one duplex `ISocket` from two simplex halves | @@ -67,11 +72,13 @@ directory `src/core/net/`. Three targets: | ``, `` | `DatagramBus`, a network segment in one process with scripted loss, and the text-to-payload helpers | | `` | `InMemoryAsyncDatagramNetwork`: `IAsyncDatagramSocket`s that exchange datagrams in memory, behind the real socket's state machine, so every refusal is the real one's. Options are `Unsupported`; loss is a full inbox, a datagram to nobody, or one a connected receiver does not accept | | `` | `FailingListener`, an `IListener` decorator whose first accepts answer scripted `NetError`s and then accept from the listener it decorates, owned or not; `repeatedFailures()` | +| `` | `ScriptedAddressResolver`, an `IAddressResolver` that answers scripted names, fails in words (`failWith`) or with a classified error (`failWithCode`), and holds lookups between `hold()` and `release()`; it owns no thread | +| `` (`core::net_tls`) | `StrictTlsPeer` (`client()`, `server()`), one TLS endpoint over the far end of a socket pair, pumped by hand, with `StrictTlsPeerOptions` (the highest version, ALPN, an alert to refuse or warn with) and what it saw (`receivedServerName()`, `negotiatedProtocol()`); `certificateMatchesHost()`, `certificateMatchesIp()`, `expiredCopyOf()` | | ``, `` | `SocketDecorator`, which forwards every verb so a double overrides only the one it stages; `ParkingReadableSocket` and `ParkingWritableSocket`, which park until the test decides and count how each parked operation ended | | `` | `setDiagnosticSink()`: where a failure nobody can be handed goes (a wait that fails mid-sweep); discarded by default | -| `` (`core::net`) | `ITlsContext`, the seam a TLS implementation plugs in behind -- `wrap()`, and `wrapClient(inner, loop, TlsPeer)`, which binds one client connection to the host it was dialled for and whose default refuses a name (`Unsupported`) rather than drop it -- and `wrapTls(socket, context, loop)`, which hands a socket back unchanged for a null context -- so an accept path compiles identically in a build without TLS | -| `` (`core::net_tls`) | a TLS `ISocket` over any other, driven through memory BIOs on the same loop, with an eager `handshakeIfNeeded()`, a `waitReadable()` that tells `close_notify` from data and a `shutdownWrite()` that sends `close_notify` before the FIN; `makeTlsServerContext()` and `makeTlsServerContextFromFiles()` (a chain and its key), `makeSelfSignedServerContext(SelfSignedOptions)`, `makeTlsClientContext()` (a pinned CA and a host name, or trust on first use), `makeTlsClientContext(TrustSource, TlsClientOptions)` (a verifying client that fails closed: SNI and a host check for a DNS `TlsPeer`, an IP-SAN check and no SNI for an address literal, the chain alone for an empty name; no option disables it). `TrustSource` is `TrustAnchors`, which OpenSSL checks during the handshake, or an `IChainVerifier`, asked after the handshake and before any application byte moves, once the leaf's name has passed the same RFC 9525 check, the socket staying unestablished (and its `ITlsSession` answering as unfinished) until it answers, `trustAnchorsFromPem()`, `generateSelfSignedCertificate(SelfSignedOptions)`, `certificateFingerprint()`, `constantTimeEquals()`; `TlsOptions` (a minimum protocol version, and the ALPN names a server selects from or a client offers), `TlsClientOptions`, `tlsSessionOf()`, which is `ISocket::tlsSession()`, and `sshStyleFingerprint()`, a SHA-256 as `SHA256:` | -| `` (`core::net_tls`) | where a verifying client's trust comes from, failing closed: `ITrustStore::load()`, `makePemTrustStore()`, `makeFileTrustStore(files, environment, home, blocking)` (`SSL_CERT_FILE`, then `SSL_CERT_DIR` as one hashed directory, then the first existing `trustBundleLocations()` row; a named but missing file, an empty store, an unreadable file, a malformed bundle, a bundle over `MaxTrustBundleBytes` or a directory over `MaxTrustDirectoryBytes` (16 MiB each) is an error; files read through `async::offload`), `TrustBundleLocation`/`TrustBundleKind`, and `makeSystemTlsClientContext()`: the platform verifier on macOS (`SecTrustEvaluateWithError`) and Windows (`CertGetCertificateChain` + `CERT_CHAIN_POLICY_SSL`), the file store elsewhere, chosen by one CMake-selected `SystemTrust.cpp` | +| `` (`core::net`) | `ITlsContext`, the seam a TLS implementation plugs in behind -- `wrap()`, and `wrapClient(inner, executor, TlsPeer)`, which binds one client connection to the host it was dialled for and whose default refuses a name (`Unsupported`) rather than drop it -- and `wrapTls(socket, context, loop)`, which hands a socket back unchanged for a null context -- so an accept path compiles identically in a build without TLS | +| `` (`core::net_tls`) | a TLS `ISocket` over any other, driven through memory BIOs on the same loop, with an eager `handshakeIfNeeded()`, a `waitReadable()` that tells `close_notify` from data and a `shutdownWrite()` that sends `close_notify` before the FIN; `makeTlsServerContext()` and `makeTlsServerContextFromFiles()` (a chain and its key), `makeSelfSignedServerContext(SelfSignedOptions)`, `makeTlsClientContext()` (a pinned CA and a host name, or trust on first use), `makeTlsClientContext(TrustSource, TlsClientOptions)` (a verifying client that fails closed: SNI and a host check for a DNS `TlsPeer`, an IP-SAN check and no SNI for an address literal; an empty name is refused, since the chain alone says nothing about who the peer is; no option disables it). `TrustSource` is `TrustAnchors`, which OpenSSL checks during the handshake, or an `IChainVerifier`, asked after the handshake and before any application byte moves, once the leaf's name has passed the same RFC 9525 check, the socket staying unestablished (and its `ITlsSession` answering as unfinished) until it answers, `trustAnchorsFromPem()`, `generateSelfSignedCertificate(SelfSignedOptions)`, `certificateFingerprint()`, `constantTimeEquals()`; `TlsOptions` (a minimum protocol version, and the ALPN names a server selects from or a client offers), `TlsClientOptions`, `tlsSessionOf()`, which is `ISocket::tlsSession()`, and `sshStyleFingerprint()`, a SHA-256 as `SHA256:` | +| `` (`core::net_tls`) | where a verifying client's trust comes from, failing closed: `ITrustStore::load()`, `makePemTrustStore()`, `makeFileTrustStore(files, environment, home, blocking)` (`SSL_CERT_FILE`, then `SSL_CERT_DIR` as one hashed directory, then the first existing `trustBundleLocations()` row; a named but missing file, an empty store, an unreadable file, a malformed bundle, a bundle over `MaxTrustBundleBytes` or a directory over `MaxTrustDirectoryBytes` (16 MiB each) is an error; files read through `async::offload`), `TrustBundleLocation`/`TrustBundleKind`, and `makeSystemTlsClientContext()`: the platform verifier on macOS (`SecTrustEvaluateWithError`) and Windows (`CertGetCertificateChain` + `CERT_CHAIN_POLICY_SSL`), the file store elsewhere, chosen by one CMake-selected `SystemTrust.cpp`. An incomplete chain is refused on every system: no verifier fetches a missing intermediate from the AIA URL a server's certificate names (OpenSSL never does; Windows builds chains with `CERT_CHAIN_DISABLE_AIA`, macOS evaluates with `SecTrustSetNetworkFetchAllowed(false)`), so a server must send its intermediates | | `` (`core::net`) | `ITlsSession`: what a finished handshake answers -- `channelBinding()` (RFC 9266, TLS 1.3 only), `peerCertificateDigest()` (the raw SHA-256, empty without a peer certificate) `negotiatedVersion()` (empty before the handshake), `negotiatedProtocol()` (ALPN) and `failure()`, the first TLS failure as a `TlsFailure` (`Certificate`, `AlertReceived` with the alert byte, or `Protocol`) -- and `TlsVersion` | | `` (`core::net_tls`) | OpenSSH public keys and SSHSIG verification: `SshPublicKey`, `parseSshPublicKey()`, `parseSshPublicKeyBlob()`, `parseAuthorizedKeysLine()`, `sshFingerprintOf()`, `verifySshSignature()`, `sshsigSignedData()`, `assembleSshsig()`; `ssh-ed25519`, `ecdsa-sha2-nistp256` and their `sk-` forms | | `` (`core::net_tls`) | the ssh-agent client: `ISshAgent` (`identities()`, `sign()`), `makeSshAgent()` and its `SshAgentError`; one connection per request | @@ -97,13 +104,15 @@ switch with no `default`, which is what makes a compiler name it when a code is | `ConnRefused` | `connection refused` | The peer actively refused a connect | | `AddressInUse` | `address in use` | A bind found the endpoint taken | | `AddressNotAvail` | `address not available` | A bind found the address not available locally | -| `AddressError` | `address error` | Address resolution or parsing failed | +| `AddressError` | `address error` | Address resolution or parsing failed; for a lookup, a permanent resolver failure (`EAI_FAIL`) and any failure nothing classified further | | `HostUnreach` | `host unreachable` | The network reports the destination as unreachable | | `PermissionDenied` | `permission denied` | The OS refused the operation — a low-numbered port without privileges, a firewall's `EACCES` | | `Unsupported` | `unsupported` | The operation is not supported on this platform or transport | | `MessageTooLarge` | `message too large` | A framed unit (line, PDU, datagram) exceeded its configured bound | | `SystemError` | `system error` | An OS error nothing classified further; read `NetError::systemCode`. It may be permanent | | `ResourceExhausted` | `resource exhausted` | The process or the system ran out of descriptors, buffer space or memory (`EMFILE`, `ENFILE`, `ENOBUFS`, `ENOMEM`, `ENOSR`, `WSAEMFILE`, `WSAENOBUFS`, `WSA_NOT_ENOUGH_MEMORY`). Transient: the same call can succeed once something is released. After `SystemError`, so no earlier code was renumbered when it was added in 0.6.0 | +| `NameNotFound` | `name not found` | A name lookup answered that the name does not exist, or has no address (`EAI_NONAME`, `WSAHOST_NOT_FOUND`). Asking again gives the same answer | +| `ResolverTemporaryFailure` | `resolver temporarily unavailable` | The resolver could not answer now, a name server not reachable or not responding (`EAI_AGAIN`, `WSATRY_AGAIN`). Asking again later may succeed. A permanent resolver failure stays `AddressError` | | `Last` | `unknown error` | Not a code: the number of codes above it, so a table or a test covers every one without restating the list. Never constructed, never returned | A new code goes **above** `Last`, never below. One appended after it still satisfies the @@ -265,6 +274,14 @@ From contour's `src/net/README.md` at `6777ff05`, as far as they hold here: ## Limits +**Give network-bound blocking work an executor of its own.** A resolver's lookup and a platform chain +verifier's evaluation block a thread for as long as a name server or the trust evaluation takes, and +a stop ends only the wait for them, never the call. On a blocking executor shared with the file +system, a slow DNS server or a stalled evaluation holds threads file reads queue behind. Hand +`ExecutorAddressResolver` and the verifiers a dedicated, bounded `ThreadPoolExecutor`; their in-flight +caps (`ExecutorResolverOptions::maxInFlight`, `TlsClientOptions::maxVerificationsInFlight`) bound what +can queue there. + These are contour's, carried as they are: - `connect()`, `connectUnix()` and `readUntil()` are coroutines that take a `std::string_view`. diff --git a/mkdocs.yml b/mkdocs.yml index 2373cce1..66638c03 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -109,6 +109,8 @@ nav: - platform: modules/platform.md - async: modules/async.md - net: modules/net.md + - fs: modules/fs.md + - http: modules/http.md - tui: modules/tui.md - testing: modules/testing.md - Design notes: