Repository navigation
feat: descriptor-relative file system, sockets, HTTP/1.1 and trust stores for WASI 0.3 - #105
Merged
Merged
Conversation
christianparpart
force-pushed
the
feature/wasi-prerequisites
branch
12 times, most recently
from
November 27, 2026 14:25
99c2e91 to
aca8ac2
Compare
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
force-pushed
the
feature/wasi-prerequisites
branch
from
November 27, 2026 18:45
3586138 to
61d94c7
Compare
…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
force-pushed
the
feature/wasi-prerequisites
branch
from
November 27, 2026 20:05
61d94c7 to
042b7f5
Compare
…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
force-pushed
the
feature/wasi-prerequisites
branch
from
November 27, 2026 21:38
042b7f5 to
019ee40
Compare
christianparpart
marked this pull request as ready for review
November 27, 2026 22:33
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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.core::http: HTTP/1.1 client (keep-alive pool) and server with streamed bodies, chunked encoding and trailers; request-smuggling refusals.platform), forwasi: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()andcore::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 intovalueBarrier(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
cmov/cselormemcmpon datasecureZerostores keptjne(lengths),je(empty)call valueBarriercmp rbx,rdi; jnetest al,al; sete almov byte ptr [rax+r8],0per byte, thenjmp memoryBarrierjne(lengths),je(empty)callq valueBarrier(REL32)cmpq %r14,%rbx; jnesete %almemoryBarrier(REL32)asm volatile; the difference stays in a register (movl %ecx,%edx)cmpq $0x20,%rax; jnetestb %cl,%cl; setne %al(main returns 1 on a difference)movb $0x0remain, buffer dead after themcmp x1,x3; b.ne(lengths),cbz x1(empty)bl valueBarriersubs x20,x20,#1; b.ne(the remaining count)cmp w0,#0; cset w0,eqstrb wzr,[x8],#1per byte, thenb memoryBarriercl x64 (
Microsoft (R) C/C++ Optimizing Compiler Version 19.51.36256 for x64, msvc-wine,/O2 /MD /std:c++latest,dumpbin /disasm)The loop (0x30-0x44) loads, xors and ors each byte, calls
valueBarrier, and branches only onrbx != rdi, the index;jne 0x62before it is the length check.secureZerostores zero to each byte (0x10-0x1B) and tail-callsmemoryBarrier, whoseatomic_signal_fenceemits no instruction.clang-cl x64 (
clang version 22.1.8 (Fedora 22.1.8-4.fc44),/O2 /MD,llvm-objdump -d -r)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.secureZerounrolls its zeroing by eight and reachesmemoryBarrierfrom every path (thejeat 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)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 emptyasm volatileleft the difference opaque, so no early exit appeared. All 32 zeroing stores (0x201676-0x201711) remain although the buffer is dead after them; theleaq -0x48(%rsp), %rcxis 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, theappleclang-releasepreset,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, sootool -tvVprintsbl 0x40andbl 0x5cas calls to themselves andb 0x8cas a branch to itself;otool -rvnames their targets (below the listing).The loop (0x2C-0x48) loads both bytes, combines them into the accumulated difference, calls
valueBarrierand counts down the remaining length: its one back edge,b.ne 0x2c, tests that count and nothing else. Before it,b.ne 0x50is the length check andcbz x1the empty case, both on the public length. After it,valueBarrieronce more andcset w0, eq, with no branch on the difference.secureZerostores zero to every byte (strb wzr, 0x80-0x88) and tail-callsmemoryBarrier, which is a bareret: the asm statement emits nothing, but the call is opaque at this object's level and the stores before it must remain.