Skip to content

feat: descriptor-relative file system, sockets, HTTP/1.1 and trust stores for WASI 0.3 - #105

Merged
christianparpart merged 19 commits into
masterfrom
feature/wasi-prerequisites
Nov 27, 2026
Merged

christianparpart merged 19 commits into
masterfrom
feature/wasi-prerequisites

Conversation

@christianparpart

@christianparpart christianparpart commented Nov 26, 2026 •

Copy link
Copy Markdown
Member

Prerequisites for Isoline's WASI 0.3 host (Isoline roadmap P13). Coroutine-first throughout: every new I/O API returns core::async::Task; no hidden threads.

  • core::fs: descriptor-relative, non-blocking file system that cannot escape a preopened directory (openat2 / component walker / NT walker), rights propagation, streaming directory reads.
  • Sockets: event-loop-driven UDP, endpoint accessors with ports, bind-before-connect, hop limit and buffer sizes, a thread-free injectable resolver, non-pollable stdio.
  • core::http: HTTP/1.1 client (keep-alive pool) and server with streamed bodies, chunked encoding and trailers; request-smuggling refusals.
  • TLS: per-connection server name and verification, ALPN, platform trust verification (macOS/Windows) and file bundles elsewhere.
  • Time zones (platform), for wasi:clocks/timezone.

Draft while the tasks land; opened early so Windows and macOS CI run on every push. Consumer impact and CHANGELOG come with the final task.

Constant-time disassembly record

The guarantee of core::constantTimeEquals() and core::secureZero() is one of generated code, so it is checked by reading the code each toolchain generates. What each listing must show:

  • constantTimeEquals: the only conditional branches are the public length check before the loop and the loop's own index test; none depends on the bytes, so a difference never ends the loop early. The value barrier is either a call into valueBarrier (out of line) or, where LTO inlined it, leaves the accumulated difference unknown to the compiler.
  • secureZero: a store of zero for every byte, and the memory barrier after them, so the stores survive although nothing reads the buffer again.

Summary

Toolchain Length branch before the loop Barrier every iteration Back edge on the index only Branch, cmov/csel or memcmp on data Result set after the loop secureZero stores kept
cl x64 19.51 jne (lengths), je (empty) call valueBarrier cmp rbx,rdi; jne none test al,al; sete al mov byte ptr [rax+r8],0 per byte, then jmp memoryBarrier
clang-cl x64 22.1.8 jne (lengths), je (empty) callq valueBarrier (REL32) cmpq %r14,%rbx; jne none sete %al unrolled by eight, every path reaches memoryBarrier (REL32)
Clang 22.1.8 x86-64, full LTO constant 32 bytes, folded inlined empty asm volatile; the difference stays in a register (movl %ecx,%edx) cmpq $0x20,%rax; jne none testb %cl,%cl; setne %al (main returns 1 on a difference) all 32 movb $0x0 remain, buffer dead after them
AppleClang 17.0.0 arm64 cmp x1,x3; b.ne (lengths), cbz x1 (empty) bl valueBarrier subs x20,x20,#1; b.ne (the remaining count) none cmp w0,#0; cset w0,eq strb wzr,[x8],#1 per byte, then b memoryBarrier

cl x64 (Microsoft (R) C/C++ Optimizing Compiler Version 19.51.36256 for x64, msvc-wine, /O2 /MD /std:c++latest, dumpbin /disasm)

?constantTimeEquals@core@@YA_NV?$span@$$CBW4byte@std@@$0?0@std@@0@Z (bool __cdecl core::constantTimeEquals(class std::span<enum std::byte co
  0000000000000000: 40 57              push        rdi
  0000000000000002: 48 83 EC 20        sub         rsp,20h
  0000000000000006: 48 8B 79 08        mov         rdi,qword ptr [rcx+8]
  000000000000000A: 32 C0              xor         al,al
  000000000000000C: 48 3B 7A 08        cmp         rdi,qword ptr [rdx+8]
  0000000000000010: 75 50              jne         0000000000000062
  0000000000000012: 48 85 FF           test        rdi,rdi
  0000000000000015: 74 3E              je          0000000000000055
  0000000000000017: 48 89 5C 24 30     mov         qword ptr [rsp+30h],rbx
  000000000000001C: 33 DB              xor         ebx,ebx
  000000000000001E: 48 89 6C 24 38     mov         qword ptr [rsp+38h],rbp
  0000000000000023: 48 8B 29           mov         rbp,qword ptr [rcx]
  0000000000000026: 48 89 74 24 40     mov         qword ptr [rsp+40h],rsi
  000000000000002B: 48 8B 32           mov         rsi,qword ptr [rdx]
  000000000000002E: 66 90              nop
  0000000000000030: 0F B6 0C 33        movzx       ecx,byte ptr [rbx+rsi]
  0000000000000034: 32 0C 2B           xor         cl,byte ptr [rbx+rbp]
  0000000000000037: 0A C8              or          cl,al
  0000000000000039: E8 00 00 00 00     call        ?valueBarrier@detail@core@@YAEE@Z
  000000000000003E: 48 FF C3           inc         rbx
  0000000000000041: 48 3B DF           cmp         rbx,rdi
  0000000000000044: 75 EA              jne         0000000000000030
  0000000000000046: 48 8B 74 24 40     mov         rsi,qword ptr [rsp+40h]
  000000000000004B: 48 8B 6C 24 38     mov         rbp,qword ptr [rsp+38h]
  0000000000000050: 48 8B 5C 24 30     mov         rbx,qword ptr [rsp+30h]
  0000000000000055: 0F B6 C8           movzx       ecx,al
  0000000000000058: E8 00 00 00 00     call        ?valueBarrier@detail@core@@YAEE@Z
  000000000000005D: 84 C0              test        al,al
  000000000000005F: 0F 94 C0           sete        al
  0000000000000062: 48 83 C4 20        add         rsp,20h
  0000000000000066: 5F                 pop         rdi
  0000000000000067: C3                 ret

?secureZero@core@@YAXV?$span@W4byte@std@@$0?0@std@@@Z (void __cdecl core::secureZero(class std::span<enum std::byte,-1>)):
  0000000000000000: 48 8B 51 08        mov         rdx,qword ptr [rcx+8]
  0000000000000004: 33 C0              xor         eax,eax
  0000000000000006: 4C 8B 01           mov         r8,qword ptr [rcx]
  0000000000000009: 48 85 D2           test        rdx,rdx
  000000000000000C: 74 0F              je          000000000000001D
  000000000000000E: 66 90              nop
  0000000000000010: 42 C6 04 00 00     mov         byte ptr [rax+r8],0
  0000000000000015: 48 FF C0           inc         rax
  0000000000000018: 48 3B C2           cmp         rax,rdx
  000000000000001B: 75 F3              jne         0000000000000010
  000000000000001D: 49 8B C8           mov         rcx,r8
  0000000000000020: E9 00 00 00 00     jmp         ?memoryBarrier@detail@core@@YAXPEBX@Z

?memoryBarrier@detail@core@@YAXPEBX@Z (void __cdecl core::detail::memoryBarrier(void const *)):
  0000000000000000: 48 89 4C 24 08     mov         qword ptr [rsp+8],rcx
  0000000000000005: 48 8B 44 24 08     mov         rax,qword ptr [rsp+8]
  000000000000000A: C3                 ret

?valueBarrier@detail@core@@YAEE@Z (unsigned char __cdecl core::detail::valueBarrier(unsigned char)):
  0000000000000000: 88 4C 24 08        mov         byte ptr [rsp+8],cl
  0000000000000004: 0F B6 44 24 08     movzx       eax,byte ptr [rsp+8]
  0000000000000009: C3                 ret

The loop (0x30-0x44) loads, xors and ors each byte, calls valueBarrier, and branches only on rbx != rdi, the index; jne 0x62 before it is the length check. secureZero stores zero to each byte (0x10-0x1B) and tail-calls memoryBarrier, whose atomic_signal_fence emits no instruction.

clang-cl x64 (clang version 22.1.8 (Fedora 22.1.8-4.fc44), /O2 /MD, llvm-objdump -d -r)

out/fw-disasm/clangcl-ConstantTime.obj:	file format coff-x86-64
Disassembly of section .text:
0000000000000000 <bool __cdecl core::constantTimeEquals(class std::span<enum std::byte const, -1>, class std::span<enum std::byte const, -1>
       0:      	pushq	%r14
       2:      	pushq	%rsi
       3:      	pushq	%rdi
       4:      	pushq	%rbx
       5:      	subq	$0x28, %rsp
       9:      	movq	0x8(%rcx), %rbx
       d:      	cmpq	0x8(%rdx), %rbx
      11:      	jne	0x50 <bool __cdecl core::constantTimeEquals(class std::span<enum std::byte const, -1>, class std::span<enum std::byte co
      13:      	testq	%rbx, %rbx
      16:      	je	0x54 <bool __cdecl core::constantTimeEquals(class std::span<enum std::byte const, -1>, class std::span<enum std::byte con
      18:      	movq	%rdx, %rsi
      1b:      	movq	%rcx, %rdi
      1e:      	xorl	%eax, %eax
      20:      	xorl	%r14d, %r14d
      23:      	nopw	%cs:(%rax,%rax)
      30:      	movq	(%rsi), %rdx
      33:      	movq	(%rdi), %rcx
      36:      	movzbl	(%rcx,%r14), %ecx
      3b:      	xorb	(%rdx,%r14), %cl
      3f:      	orb	%al, %cl
      41:      	callq	0x46 <bool __cdecl core::constantTimeEquals(class std::span<enum std::byte const, -1>, class std::span<enum std::byte 
		0000000000000042:  IMAGE_REL_AMD64_REL32	?valueBarrier@detail@core@@YAEE@Z
      46:      	incq	%r14
      49:      	cmpq	%r14, %rbx
      4c:      	jne	0x30 <bool __cdecl core::constantTimeEquals(class std::span<enum std::byte const, -1>, class std::span<enum std::byte co
      4e:      	jmp	0x56 <bool __cdecl core::constantTimeEquals(class std::span<enum std::byte const, -1>, class std::span<enum std::byte co
      50:      	xorl	%eax, %eax
      52:      	jmp	0x62 <bool __cdecl core::constantTimeEquals(class std::span<enum std::byte const, -1>, class std::span<enum std::byte co
      54:      	xorl	%eax, %eax
      56:      	movl	%eax, %ecx
      58:      	callq	0x5d <bool __cdecl core::constantTimeEquals(class std::span<enum std::byte const, -1>, class std::span<enum std::byte 
		0000000000000059:  IMAGE_REL_AMD64_REL32	?valueBarrier@detail@core@@YAEE@Z
      5d:      	testb	%al, %al
      5f:      	sete	%al
      62:      	addq	$0x28, %rsp
      66:      	popq	%rbx
      67:      	popq	%rdi
      68:      	popq	%rsi
      69:      	popq	%r14
      6b:      	retq
Disassembly of section .text:
0000000000000000 <void __cdecl core::secureZero(class std::span<enum std::byte, -1>)>:
       0:      	movq	%rcx, %rax
       3:      	movq	(%rcx), %rcx
       6:      	movq	0x8(%rax), %r8
       a:      	testq	%r8, %r8
       d:      	je	0x13 <void __cdecl core::secureZero(class std::span<enum std::byte, -1>)+0x13>
		000000000000000f:  IMAGE_REL_AMD64_REL32	?memoryBarrier@detail@core@@YAXPEBX@Z
      13:      	movl	%r8d, %edx
      16:      	andl	$0x7, %edx
      19:      	cmpq	$0x8, %r8
      1d:      	jae	0x24 <void __cdecl core::secureZero(class std::span<enum std::byte, -1>)+0x24>
      1f:      	xorl	%r9d, %r9d
      22:      	jmp	0x6d <void __cdecl core::secureZero(class std::span<enum std::byte, -1>)+0x6d>
      24:      	andq	$-0x8, %r8
      28:      	xorl	%r9d, %r9d
      2b:      	nopl	(%rax,%rax)
      30:      	movb	$0x0, (%rcx,%r9)
      35:      	movb	$0x0, 0x1(%rcx,%r9)
      3b:      	movb	$0x0, 0x2(%rcx,%r9)
      41:      	movb	$0x0, 0x3(%rcx,%r9)
      47:      	movb	$0x0, 0x4(%rcx,%r9)
      4d:      	movb	$0x0, 0x5(%rcx,%r9)
      53:      	movb	$0x0, 0x6(%rcx,%r9)
      59:      	movb	$0x0, 0x7(%rcx,%r9)
      5f:      	addq	$0x8, %r9
      63:      	cmpq	%r9, %r8
      66:      	jne	0x30 <void __cdecl core::secureZero(class std::span<enum std::byte, -1>)+0x30>
      68:      	testq	%rdx, %rdx
      6b:      	je	0x8d <void __cdecl core::secureZero(class std::span<enum std::byte, -1>)+0x8d>
      6d:      	addq	%r9, %rcx
      70:      	xorl	%r8d, %r8d
      73:      	nopw	%cs:(%rax,%rax)
      80:      	movb	$0x0, (%rcx,%r8)
      85:      	incq	%r8
      88:      	cmpq	%r8, %rdx
      8b:      	jne	0x80 <void __cdecl core::secureZero(class std::span<enum std::byte, -1>)+0x80>
      8d:      	movq	(%rax), %rcx
      90:      	jmp	0x95 <void __cdecl core::secureZero(class std::span<enum std::byte, -1>)+0x95>
		0000000000000091:  IMAGE_REL_AMD64_REL32	?memoryBarrier@detail@core@@YAXPEBX@Z
out/fw-disasm/clangcl-ValueBarrierMsvc.obj:	file format coff-x86-64
Disassembly of section .text:
0000000000000000 <unsigned char __cdecl core::detail::valueBarrier(unsigned char)>:
       0:      	pushq	%rax
       1:      	movb	%cl, 0x7(%rsp)
       5:      	movzbl	0x7(%rsp), %eax
       a:      	popq	%rcx
       b:      	retq
Disassembly of section .text:
0000000000000000 <void __cdecl core::detail::memoryBarrier(void const *)>:
       0:      	pushq	%rax
       1:      	movq	%rcx, (%rsp)
       5:      	movq	(%rsp), %rax
       9:      	popq	%rax
       a:      	retq

The loop (0x30-0x4C) calls valueBarrier (relocation at 0x42) and branches only on the index (cmpq %r14, %rbx); the branches at 0x11 and 0x16 are the length check and the empty case. secureZero unrolls its zeroing by eight and reaches memoryBarrier from every path (the je at 0x0D is a conditional tail call, its relocation at 0x0F).

Clang x86-64 with full LTO (clang version 22.1.8 (Fedora 22.1.8-4.fc44), -O2 -flto -fuse-ld=lld, both functions reached from another translation unit)

0000000000201620 <main>:
  201620:      	movd	%edi, %xmm0
  201624:      	punpcklbw	%xmm0, %xmm0    # xmm0 = xmm0[0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7]
  201628:      	pshuflw	$0x0, %xmm0, %xmm0      # xmm0 = xmm0[0,0,0,0,4,5,6,7]
  20162d:      	pshufd	$0x44, %xmm0, %xmm0     # xmm0 = xmm0[0,1,0,1]
  201632:      	movdqa	%xmm0, -0x38(%rsp)
  201638:      	movdqa	%xmm0, -0x48(%rsp)
  20163e:      	pxor	%xmm0, %xmm0
  201642:      	movdqa	%xmm0, -0x18(%rsp)
  201648:      	movdqa	%xmm0, -0x28(%rsp)
  20164e:      	xorl	%edx, %edx
  201650:      	xorl	%eax, %eax
  201652:      	nopw	%cs:(%rax,%rax)
  201660:      	movzbl	-0x28(%rsp,%rax), %ecx
  201665:      	xorb	-0x48(%rsp,%rax), %cl
  201669:      	orb	%dl, %cl
  20166b:      	incq	%rax
  20166e:      	movl	%ecx, %edx
  201670:      	cmpq	$0x20, %rax
  201674:      	jne	0x201660 <main+0x40>
  201676:      	movb	$0x0, -0x48(%rsp)
  20167b:      	movb	$0x0, -0x47(%rsp)
  201680:      	movb	$0x0, -0x46(%rsp)
  201685:      	movb	$0x0, -0x45(%rsp)
  20168a:      	movb	$0x0, -0x44(%rsp)
  20168f:      	movb	$0x0, -0x43(%rsp)
  201694:      	movb	$0x0, -0x42(%rsp)
  201699:      	movb	$0x0, -0x41(%rsp)
  20169e:      	movb	$0x0, -0x40(%rsp)
  2016a3:      	movb	$0x0, -0x3f(%rsp)
  2016a8:      	movb	$0x0, -0x3e(%rsp)
  2016ad:      	movb	$0x0, -0x3d(%rsp)
  2016b2:      	movb	$0x0, -0x3c(%rsp)
  2016b7:      	movb	$0x0, -0x3b(%rsp)
  2016bc:      	movb	$0x0, -0x3a(%rsp)
  2016c1:      	movb	$0x0, -0x39(%rsp)
  2016c6:      	movb	$0x0, -0x38(%rsp)
  2016cb:      	movb	$0x0, -0x37(%rsp)
  2016d0:      	movb	$0x0, -0x36(%rsp)
  2016d5:      	movb	$0x0, -0x35(%rsp)
  2016da:      	movb	$0x0, -0x34(%rsp)
  2016df:      	movb	$0x0, -0x33(%rsp)
  2016e4:      	movb	$0x0, -0x32(%rsp)
  2016e9:      	movb	$0x0, -0x31(%rsp)
  2016ee:      	movb	$0x0, -0x30(%rsp)
  2016f3:      	movb	$0x0, -0x2f(%rsp)
  2016f8:      	movb	$0x0, -0x2e(%rsp)
  2016fd:      	movb	$0x0, -0x2d(%rsp)
  201702:      	movb	$0x0, -0x2c(%rsp)
  201707:      	movb	$0x0, -0x2b(%rsp)
  20170c:      	movb	$0x0, -0x2a(%rsp)
  201711:      	movb	$0x0, -0x29(%rsp)
  201716:      	xorl	%eax, %eax
  201718:      	testb	%cl, %cl
  20171a:      	setne	%al
  20171d:      	leaq	-0x48(%rsp), %rcx
  201722:      	retq

LTO inlined both functions and both barriers into main, the probe that calls them on a 32-byte stack buffer. The compare loop (0x201660-0x201674) still loads and combines every byte and branches only on the index (cmpq $0x20, %rax): the empty asm volatile left the difference opaque, so no early exit appeared. All 32 zeroing stores (0x201676-0x201711) remain although the buffer is dead after them; the leaq -0x48(%rsp), %rcx is the memory barrier's operand, the asm statement's only trace.

AppleClang arm64 (Apple clang version 17.0.0 (clang-1700.0.13.5), macos-15-arm64, the appleclang-release preset, otool -tvV)

From the "Disassemble the constant-time functions" step of the macos (appleclang) job on PR #105's head 61d94c7 (CI run 46051815441, job 140684728286; the same code as run 46047049425). An object's calls are unresolved before the link, so otool -tvV prints bl 0x40 and bl 0x5c as calls to themselves and b 0x8c as a branch to itself; otool -rv names their targets (below the listing).

__ZN4core6detail12valueBarrierEh:
0000000000000000	and	w0, w0, #0xff
0000000000000004	ret
__ZN4core6detail13memoryBarrierEPKv:
0000000000000008	ret

__ZN4core18constantTimeEqualsENSt3__14spanIKSt4byteLm18446744073709551615EEES4_:
0000000000000000	cmp	x1, x3
0000000000000004	b.ne	0x50
0000000000000008	stp	x22, x21, [sp, #-0x30]!
000000000000000c	stp	x20, x19, [sp, #0x10]
0000000000000010	stp	x29, x30, [sp, #0x20]
0000000000000014	add	x29, sp, #0x20
0000000000000018	mov	x20, x1
000000000000001c	cbz	x1, 0x58
0000000000000020	mov	x19, x2
0000000000000024	mov	x21, x0
0000000000000028	mov	w0, #0x0
000000000000002c	ldrb	w8, [x21], #0x1
0000000000000030	ldrb	w9, [x19], #0x1
0000000000000034	eor	w8, w9, w8
0000000000000038	and	w9, w0, #0xff
000000000000003c	orr	w0, w8, w9
0000000000000040	bl	0x40
0000000000000044	subs	x20, x20, #0x1
0000000000000048	b.ne	0x2c
000000000000004c	b	0x5c
0000000000000050	mov	w0, #0x0
0000000000000054	ret
0000000000000058	mov	w0, #0x0
000000000000005c	bl	0x5c
0000000000000060	cmp	w0, #0x0
0000000000000064	cset	w0, eq
0000000000000068	ldp	x29, x30, [sp, #0x20]
000000000000006c	ldp	x20, x19, [sp, #0x10]
0000000000000070	ldp	x22, x21, [sp], #0x30
0000000000000074	ret
__ZN4core10secureZeroENSt3__14spanISt4byteLm18446744073709551615EEE:
0000000000000078	cbz	x1, 0x8c
000000000000007c	mov	x8, x0
0000000000000080	strb	wzr, [x8], #0x1
0000000000000084	subs	x1, x1, #0x1
0000000000000088	b.ne	0x80
000000000000008c	b	0x8c

Relocation information (__TEXT,__text) 3 entries
address  pcrel length extern type    scattered symbolnum/value
0000008c True  long   True   BR26    False     __ZN4core6detail13memoryBarrierEPKv
0000005c True  long   True   BR26    False     __ZN4core6detail12valueBarrierEh
00000040 True  long   True   BR26    False     __ZN4core6detail12valueBarrierEh

The loop (0x2C-0x48) loads both bytes, combines them into the accumulated difference, calls valueBarrier and counts down the remaining length: its one back edge, b.ne 0x2c, tests that count and nothing else. Before it, b.ne 0x50 is the length check and cbz x1 the empty case, both on the public length. After it, valueBarrier once more and cset w0, eq, with no branch on the difference. secureZero stores zero to every byte (strb wzr, 0x80-0x88) and tail-calls memoryBarrier, which is a bare ret: the asm statement emits nothing, but the call is opaque at this object's level and the stores before it must remain.

@christianparpart
christianparpart force-pushed the feature/wasi-prerequisites branch 12 times, most recently from 99c2e91 to aca8ac2 Compare November 27, 2026 14:25
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 <christian@parpart.family>
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 <christian@parpart.family>
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 <christian@parpart.family>
@christianparpart
christianparpart force-pushed the feature/wasi-prerequisites branch from 3586138 to 61d94c7 Compare November 27, 2026 18:45
…indows, 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 <christian@parpart.family>
@christianparpart
christianparpart force-pushed the feature/wasi-prerequisites branch from 61d94c7 to 042b7f5 Compare November 27, 2026 20:05
…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<T>, 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 <christian@parpart.family>
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 <christian@parpart.family>
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 <christian@parpart.family>
…ed 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 <christian@parpart.family>
…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 <christian@parpart.family>
… 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 <christian@parpart.family>
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 <christian@parpart.family>
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 <christian@parpart.family>
… 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 <christian@parpart.family>
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 <christian@parpart.family>
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 <christian@parpart.family>
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 <christian@parpart.family>
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 <christian@parpart.family>
…oted 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 <christian@parpart.family>
… 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 <christian@parpart.family>
@christianparpart
christianparpart force-pushed the feature/wasi-prerequisites branch from 042b7f5 to 019ee40 Compare November 27, 2026 21:38
@christianparpart
christianparpart marked this pull request as ready for review November 27, 2026 22:33
@christianparpart
christianparpart merged commit 4c3da5a into master Nov 27, 2026
38 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant