Motivation:
A number of NIO APIs are asynchronous and return futures but have
synchronous implementations. If a caller wants to operate on this they
need to register a callback with the future and then operate on the
result. However, now that we have an isolated view on the event loop
future we can provide a fast path: just check whether the result is
already present.
This is particularly helpful for channel initializers which are
typically synchronous. Using the fast path means calls can avoid an
escaping closure from registering a callback on the future.
Modifications:
Add three new APIs to the isolated event loop future:
- `result` which returns the underlying `Result<Value, Error>` or `nil`
if it hasn't been completed yet
- `value` which call `try result.get()`, and
- `isComplete`
Result:
APIs for accessing the result of an ELF from its isolated view if it's
already completed
### Motivation:
`CNIOWindows_sendmmsg` was a stub that asserted and then called
`abort()`, so any code path reaching it took the whole process down:
```
Assertion failed: !"sendmmsg not implemented", file Sources\CNIOWindows\shim.c, line 26
```
### Modifications:
Winsock has no `sendmmsg`, so emulate it by sending the messages one at
a time — exactly what the Darwin shim does for the same reason.
Error semantics match the Darwin implementation: a failure on the
first message is reported to the caller.
### Result:
Further progress on windows.
Windows-only; no other platform is affected.
---------
Co-authored-by: Fabian Fett <fabianfett@apple.com>
Motivation:
The module map for glibc is broken which can lead libc symbols being
attributed to the wrong module. In NIO, SocketAddresses.swift imports
CNIOLinux (and friends) but, as far as I can tell, doesn't use any of
their symbols directly. The result is that various libc symbols
incorrectly get attributed to CNIOLinux and compilation can fail for
downstream packages with member import visibility checks enabled.
See also: https://github.com/swiftlang/swift/issues/85427
Modifications:
- Remove the CNIO* imports from SocketAddresses.swift as they appear to
be unused
- Simplify the imoport block
Result:
Can build grpc with member import visibility checks enabled.
Co-authored-by: Cory Benfield <lukasa@apple.com>
### Motivation:
`System.enumerateDevices()` crashes on Windows, which in turn makes
`UtilitiesTest.testEnumeratingDevices` and the whole of
`SocketOptionProviderTest` (whose `setUp` enumerates devices) unrunnable
there; both are currently skipped.
`GetAdaptersAddresses` reports the size its output requires in *bytes*,
but the buffer was allocated as `Int(ulSize) /
MemoryLayout<IP_ADAPTER_ADDRESSES>.stride` *elements*. That integer
division truncates, so the buffer was always smaller than what the OS
asked for, and the OS then wrote its linked list of variably sized
records (adapter names, sockaddrs, unicast address entries) past the end
of it, corrupting the heap.
### Modifications:
- Size the allocation in bytes, starting from the 15KB initial
allocation the
[documentation](https://learn.microsoft.com/en-us/windows/win32/api/iphlpapi/nf-iphlpapi-getadaptersaddresses)
recommends, and retry on `ERROR_BUFFER_OVERFLOW` — the set of adapters
can change between the sizing call and the filling call.
- Remove the corresponding skips in
`UtilitiesTest.testEnumeratingDevices` and `SocketOptionProviderTest`.
- Running `SocketOptionProviderTest` for the first time on Windows
showed that `testPassingInvalidSizeToSetComplexSocketOptionFails` needs
a Windows-specific expectation. Winsock's `SO_RCVTIMEO` takes a `DWORD`
rather than a `timeval`, so the `Int` the test passes is in fact large
enough and `setsockopt` correctly accepts it. On Windows the test now
passes a single byte, which is too small for any option, and asserts the
`WSAEFAULT` that Winsock reports.
No behaviour change on any other platform; everything is behind `#if
os(Windows)`.
### Result:
`System.enumerateDevices()` works on Windows, and 13 previously skipped
tests run there.
Verified on a Windows ARM64 VM (Swift 6.3.2): a full unfiltered `swift
test` passes — 2354 tests, 0 failures.
### Motivation:
The WSAPoll selector traps with `preconditionFailure("Invalid fd
supplied.")` whenever `WSAPoll` reports `POLLNVAL`, and that is
reachable from ordinary shutdown, so
`MultiThreadedEventLoopGroupTests.testShuttingDownFailsRegistration` is
currently skipped on Windows.
The root cause is not in the selector. `SelectableEventLoop.deregister`
guards on `isOpen`, which is false both when the loop is closed *and*
when it has merely stopped accepting **new** registrations. The latter
is precisely the state the loop is in during `Selector.closeGently`,
which closes each remaining channel — so those channels skip
deregistration entirely and then close their sockets anyway.
The epoll and kqueue backends tolerate that, because there a
registration lives in the kernel and is dropped along with the
descriptor. The WSAPoll backend keeps its registrations in an array of
its own, so it is left holding a stale entry for a closed socket, and
the next `WSAPoll` correctly reports `POLLNVAL` for it.
Traced on a Windows ARM64 VM by instrumenting the selector and the event
loop:
```
register0 fd=704 idx=1
EL.deregister SKIPPED state=runningButNotAcceptingNewRegistrations
EL.deregister SKIPPED state=runningButNotAcceptingNewRegistrations
POLLNVAL fd=704 i=1 revents=4 events=256 dereg=[] indexes=[704: 1, 712: 2, 728: 3]
Fatal error: Invalid fd supplied.
```
### Modifications:
- Guard `deregister` on the *selector's* lifecycle rather than on
`isOpen`. Deregistering an existing channel while the loop is closing is
valid, because the selector itself is still open at that point.
- Remove the skip on
`MultiThreadedEventLoopGroupTests.testShuttingDownFailsRegistration`.
`POLLNVAL` deliberately keeps trapping. Like `EBADF`, which NIO already
treats as an unacceptable errno, it means we have lost track of a
descriptor; Windows recycles `SOCKET` handles, so continuing against a
possibly-reused handle would misroute I/O to the wrong channel. An
earlier version of this patch mapped `POLLNVAL` to `.error` instead —
that silently retained the stale entry and gave up that guarantee, so it
was dropped in favour of fixing the cause.
**Note for reviewers:** unlike most of the Windows porting patches this
touches shared code rather than sitting behind `#if os(Windows)`. The
observable behaviour on Linux/Darwin is unchanged, but they will now
issue one `epoll_ctl(EPOLL_CTL_DEL)`/kevent delete per channel during
event loop shutdown where previously they issued none.
### Result:
The WSAPoll selector no longer traps during event loop shutdown, and
`testShuttingDownFailsRegistration` runs on Windows.
Verified:
- Windows ARM64 (Swift 6.3.2), full unfiltered `swift test`: 2354 tests,
0 failures.
- macOS, full `swift test` with and without this change: identical
results (2451 tests, same 28 pre-existing failures caused by the network
mount used for this port, none in NIOPosix).
Co-authored-by: Fabian Fett <fabianfett@apple.com>
Saturate the `ByteCount` unit factories so large counts no longer trap
on overflow.
### Motivation:
`ByteCount` exposes unit factories such as `kilobytes`, `megabytes`,
`gigabytes`, `kibibytes`, `mebibytes`, and `gibibytes`. Each one
computed the byte total with a plain multiplication, for example `1024 *
1024 * 1024 * count` in `gibibytes`. When a caller passes a very large
count, that multiplication overflows `Int64` and traps, crashing the
process. This is exactly what issue #2877 reports:
`ByteCount(contentsOf:maximumSizeAllowed: .gibibytes(.max))` crashes
with an arithmetic overflow inside `gibibytes`, even though passing a
huge value is a natural way to express "effectively no limit".
### Modifications:
I added a small `fileprivate` saturating multiplication helper on
`Int64` and routed every unit factory through it. The helper uses
`multipliedReportingOverflow(by:)` and, on overflow, clamps to
`Int64.max` for positive counts or `Int64.min` for negative counts.
Counts that fit continue to produce the exact same value as before, so
there is no behavior change for normal inputs. I extended
`ByteCountTests` with positive and negative overflow cases, and applied
the identical change to both copies of `ByteCount.swift` (`NIOFS` and
`_NIOFileSystem`) to keep them in sync, matching the convention used by
recent changes to those targets.
### Result:
Passing extreme values such as `.gibibytes(.max)` saturates to
`Int64.max` instead of trapping, so disabling a size limit via a large
value no longer crashes. I verified this by running `swift test --filter
ByteCountTests`, which passes after the change. To confirm the tests are
load bearing I reverted the source fix and re-ran the new tests, which
crashed with signal 5 (the overflow trap) exactly as the issue
describes, and they pass again with the fix in place. `swift format lint
--strict` reports no issues on the changed files.
Fixes#2877
### Motivation:
`Selector.description` prints `self.selectorFD`, which only the epoll,
kqueue and io_uring backends ever assign. On Windows it therefore always
reads `descriptor = -1` — the value that by convention means the
selector has been closed — even while the selector is open and perfectly
usable.
That made
`MultiThreadedEventLoopGroupTests.testStructuredConcurrencyMTELGStartStop`
unrunnable on Windows, since it asserts that a running event loop does
*not* describe itself as having descriptor -1, and that a shut down one
does.
### Modifications:
The WSAPoll backend has no single descriptor standing for the selector
itself, but the read end of its wakeup socket pair has exactly the same
lifetime: it is created in `initialiseState0` and reset to
`NIOBSDSocket.invalidHandle` in `close0`, under the same
`externalSelectorFDLock` that this description already takes. Report
that on Windows, mapping the invalid handle to -1 so the established
meaning of -1 is preserved.
Remove the corresponding skip.
The change is behind `#if os(Windows)`; other platforms keep printing
`selectorFD` exactly as before.
### Result:
A running event loop on Windows now describes its selector accurately,
and `testStructuredConcurrencyMTELGStartStop` runs there.
Verified on a Windows ARM64 VM (Swift 6.3.2): a full unfiltered `swift
test` passes — 2354 tests, 0 failures.
This change clarifies the documentation of
`replaceItem(at:withItemAt:)`. It explicitly states that this operation
is identical to a move, and that the item at `existingPath` will be
moved to the new location and no longer exist at its original path.
For small fixed-size allocations, we can use stack instead of heap.
### Motivation:
Allocations are costly. Stack allocations are much cheaper than heap
allocations.
### Modifications:
Use `withUnsafeTemporaryAllocation(of:capacity:_:)` instead of
allocating an `Array`.
`withUnsafeTemporaryAllocation` allocates on the stack for up to 1000
bytes.
### Result:
Better performance.
Motivation:
The schedule callback mechanism on `EventLoop` has an equivalent on an
isolated `EventLoop`. The default isolated implementation puts the
hander in a loop bound box and calls the non-isolated version.
This is okay but introduces a number of additional "in event loop"
checks which are required for correctness in the general case (i.e. not
called from an isolated event loop).
Modifications:
- Implement the customisation point directly to avoid the additional
checks (the are unecessary by definition of being on the isolated event
loop).
- Add benchmarks
Result:
On the isolated event loop, in micro benchmarks:
- scheduleTask is ~1.6x faster
- scheduleCallback is ~2x faster
This PR addresses **#3613** where writing to `/dev/stdout` fails with
`ENXIO (6) Device not configured` when running in a terminal environment
instead of a pipe.
Currently, `SystemFileHandle` checks for `errno == .illegalSeek`
(ESPIPE) when deciding whether to fall back from positional
`pwrite`/`pread` to non-positional `write`/`read` for unseekable files
like pipes. However, macOS/Darwin returns `ENXIO`
(`Errno.noSuchDeviceOrAddress`) instead of `ESPIPE` when attempting a
positional write/read on a terminal device.
**Changes:**
- Added `.noSuchDeviceOrAddress` to the fallback conditions in
`SystemFileHandle.swift` for both `readChunk` and `write`.
- Updated `FileSystemError+Syscall.swift` to map
`.noSuchDeviceOrAddress` to `.unsupported` alongside `.illegalSeek`.
- Replicated these changes across both the `_NIOFileSystem` and `NIOFS`
modules.
This allows `FileSystem.shared.withFileHandle` and other APIs to work
transparently with terminal devices like `/dev/stdout`!
### Motivation:
Currently, EventLoopFuture.flatMap requires the inner eventloop to have
a Sendable type. This makes sense, because the value might move between
eventloops, if the inner and outer future are not on the same EventLoop.
However, this makes it impossible for users to use non Sendable values
even when they _know_ they're on the right eventloop
### Modifications:
Add a new `flatMapIsolated` function which can be used in this case. It
requires users to return an EventLoopFuture.Isolated to prove that they
are on the same eventloop
### Example:
```swift
class T { // Not Sendable
init() {
}
}
func test(eventLoop: any EventLoop) -> EventLoopFuture<T> {
let a = eventLoop.submit { T() }
let b = eventLoop.submit { T() }
return a.flatMap { _ in b }
}
```
The above example gives a warning on the final line, because flatMap
requires the inner future (`b`) to have a Sendable type. That is because
it doesn't know that a and b are on the same EventLoop.
```swift
func test(eventLoop: any EventLoop) -> EventLoopFuture<T> {
let a = eventLoop.submit { T() }
let b = eventLoop.submit { T() }
return a.flatMapIsolated { _ in b.assumeIsolated() }
}
```
Here, it compiles without warnings. We can write assumeIsolated inside
the flatMapIsolated closure because we know that the eventloops are the
same. And therefore the new flatMapIsolated function does not have a
Sendable requirement on its value
Co-authored-by: Cory Benfield <lukasa@apple.com>
## Motivation
Follow-up to #3649 (all non-test targets now build on Windows). This
gets the bulk of the **test** targets compiling on Windows so we can
start moving toward running them in CI.
Of the 16 test targets, 6 already compiled unchanged. This brings **8
more** to a clean compile, leaving only two as dedicated follow-ups:
- `NIOPosixTests` — large, many distinct Winsock/POSIX issues; deserves
its own PR.
- `NIOFoundationCompatTests` — a `missing required module 'CNIOPosix'`
issue to investigate separately.
The changes are **compile-only** — they don't aim to make the tests
*pass* on Windows yet. Verified by building each target on a Windows
ARM64 VM; not yet wired into CI (CI still builds products only, since
the two deferred targets would fail `--build-tests`).
## What's here
Three commits:
1. **Make `Posix.close` available on Windows** — it was gated out only
because it sat inside the socket-syscalls `#if !os(Windows)` block (next
to `shutdown`), even though its body already handled Windows. Define
`sysClose = _close` and lift `close(descriptor:)` out of that block. No
behavior change off Windows.
2. **Compile the low-hanging test targets** — a
gate-out-plus-minimal-shim approach:
- A tiny `#if os(Windows)` `usleep` shim (backed by `Sleep`), once per
affected target, plus a Windows branch for the `#error` C-library check.
- Real Windows implementations for the temp-file/pipe test helpers
rather than stubs: `withPipe` → `_pipe`, `openTemporaryFile` →
`_mktemp_s` + `_sopen_s`, `createTemporaryDirectory` → a GUID +
`CreateDirectoryW`.
- Gate out genuinely-unavailable test logic behind `#if !os(Windows)`:
`System.enumerateInterfaces`, `ChannelOptions.socket(IPPROTO_IP,
IP_TTL)`, `mkfifo`-based tests, the POSIX-`stat`-shaped `FileInfoTests`,
the `S_IFSOCK`/`DT_*` conversion tests, and the `openat` oflag-bit test.
- Two Windows-only shim tweaks make the NIOFS `OpenOptions` gap values
and `Errno.noData` `@_spi(Testing) public`, matching how swift-system
exposes the equivalents elsewhere (the tests reach them via an SPI
import).
- The `NIOHTTP1Tests` and `NIOPosixTests` copies of `TestUtils.swift`
are intentional duplicates and get identical Windows helper
implementations to stay in sync.
3. **Document why `SocketOption`'s integer API is unavailable on
Windows** — comment-only: WinSDK imports the socket option level/name
constants as enumeration cases, not plain integers, so they don't fit
the integer `SocketOptionLevel`/`SocketOptionName` typealiases.
## Notes for reviewers
- No behavior change off Windows: every change is behind `#if
os(Windows)` / `#if !os(Windows)`; the one shared edit (a test buffer
typed `CChar` instead of `CInterop.PlatformChar`) is identical on POSIX.
- The `usleep` shim is duplicated per target rather than shared: there's
no test-only support target these all depend on (the shared deps,
`NIOCore`/`NIOTestUtils`, are shipping libraries). It can be centralised
later if desired.
---------
Co-authored-by: George Barnett <gbarnett@apple.com>
## Motivation
This continues the incremental Windows port of SwiftNIO. `NIOPosix`
already builds on Windows (on Winsock2 with a POSIX-shim mapping); this
PR gets the **L4 NIOFileSystem family** to **compile** on Windows:
- `_NIOFileSystem`
- `NIOFS`
- `NIOFileSystem`
- `_NIOFileSystemFoundationCompat`
- `NIOFSFoundationCompat`
With these compiling, **all non-test targets now build on Windows**, so
the Windows CI job is simplified to a bare `swift build` (which builds
the whole non-test graph) rather than an explicit per-target list.
## Scope — compile-only
**This PR gets the targets compiling; it does not yet make them
functional.** The POSIX file-system syscalls that don't exist (or aren't
exposed by swift-system) on Windows are provided as `fatalError("…
unavailable on Windows")` **stubs** with the correct signatures, so the
library type-checks and links. Real Win32 implementations, and bringing
the test targets online in CI to validate them, are deliberately left to
follow-up PRs.
The intent is to land the smallest reviewable slice first and **get
feedback on the overall shape and organization** before building on it.
## What this does
All changes are behind `#if os(Windows)` / `#if defined(_WIN32)`, with
**zero behavior change on Darwin/Linux/BSD**:
- **`Sources/*/Internal/System Calls/SystemPackage+Windows.swift`**
(new, one per tree): a module-scope compatibility shim supplying the
pieces the rest of the target expects on Windows —
- the swift-system-gap extensions swift-system doesn't provide on
Windows
(`FileDescriptor.OpenOptions.{noFollow,closeOnExec,nonBlocking,directory}`,
`Errno.noData`);
- `CInterop.Stat`/`DirEnt`/`FTS`/`FTSEnt` Windows stand-ins and the
`S_IF*`/`DT_*`/`FTS_*`/`UTIME_*` constants the call sites reference;
- `fatalError` stubs for the bare-libc syscalls (`openat`,
`stat`/`lstat`/`fstat`, `readdir`/`fdopendir`/`closedir`, `fts_*`,
`futimens`, `rename`, `symlink`, xattr-adjacent helpers, `getcwd`,
pthread TLS keys, …), matching the exact signatures the existing
`system_*` / `libc_*` wrappers call, so those wrappers and their
non-Windows call sites need no changes.
- Small `#elseif os(Windows)` branches in the existing platform switches
(`FileInfo`, `FileType`, `Errno`, `Mocking`, `Syscall(s)`,
`SystemFileHandle`, `FileSystem`) — including `fatalError` stubs for
`_copyRegularFile` / `_copySymbolicLink` /
file-materialization-via-rename.
- A tiny `CNIOWindows` addition: `errno` accessors (`CNIOWindows_errno`
/ `CNIOWindows_set_errno`, typed `errno_t` via
`_get_errno`/`_set_errno`) so the Swift errno indirection can bridge the
CRT `errno` macro.
- `CNIOWindows` added to the `NIOFS` / `_NIOFileSystem` target
dependencies in `Package.swift`.
`NIOFS` and `_NIOFileSystem` are lockstep near-duplicates, so every
Windows change is applied identically to both.
## Verification
Verified by source review and by confirming a clean `swift build` on
`aarch64-unknown-windows-msvc`. Since the syscalls are stubbed, there is
no runtime behavior to test yet.
## What I'm looking for
Feedback on the **high-level organization and shape** of the NIOFS
Windows shim before the real implementations follow:
1. Is the layering right — a single module-scope
`SystemPackage+Windows.swift` gap-shim, with the upstream `system_*` /
`libc_*` call sites left untouched?
2. When the implementations land, is emulating the POSIX seams (a
`fts(3)`-shaped tree walk, POSIX directory streams) the right approach,
or should Windows fork at a higher layer (e.g. a Windows-specific
enumerator in `DirectoryEntries`) rather than reimplementing
`fts`/`readdir`?
3. Anything about the swift-system-gap extensions or the `CInterop.*`
Windows stand-ins that should be shaped differently.
## Next steps
Follow-up PRs will replace the stubs with real Win32 implementations,
then bring the NIOFileSystem **test targets** building and running in CI
— where these shims get real validation and we start gaining deeper
confidence in Windows support across the stack.
---------
Co-authored-by: George Barnett <gbarnett@apple.com>
### Motivation:
On the server side, `HTTPResponseEncoder` chooses a response's body
framing only from the response status
(`HTTPResponseStatus.mayHaveResponseBody`): it has no knowledge of the
request method as it's an outbound-only handler. But HTTP requires that
a response to a HEAD request (and a 2xx response to CONNECT) carry no
message body, regardless of status or framing headers.
As a result, a response to a HEAD request with a status that allows a
body (like 200) and no `Content-Length` gets framed as
`Transfer-Encoding: chunked`, and the encoder emits the chunked
terminator (`0\r\n\r\n`). This is illegal.
A conformant client won't read those bytes when receiving a HEAD
response, so on a keep-alive connection they get misinterpreted as the
start of the next response, corrupting the connection. This surfaces as
intermittent, hard-to-diagnose failures (e.g. "I/O on closed channel")
on the following request.
### Modifications:
Made the server response framing method-aware without changing any
public API:
- The request decoder now hands each decoded request's method to the
response encoder.
- `HTTPResponseEncoder` consults the method and, for responses to
HEAD/CONNECT requests, omits the body and the terminator.
- This is wired up in `configureHTTPServerPipeline`. When the encoder is
constructed and used on its own, its behaviour is unchanged (framing is
still derived solely from the status), so there is no behavioural or API
change for users who may be creating this handler manually.
### Result:
Responses to `HEAD` and `CONNECT` requests are no longer emitted with a
message body, keeping keep-alive connections well-formed and
RFC-compliant. No public API changes.
Motivation:
GHSA-ffw9-jrfx-pfvc raised a question about whether `setBytes(_:at:)`,
`setInteger(_:at:...)`, and `setString(_:at:)` correctly validate an
out-of-range `index`. On review, this turned out to be
working-as-intended: these APIs trap on an invalid index by design,
unlike the `get*` family, which validates via `rangeWithinReadableBytes`
and returns `nil` instead. That asymmetry wasn't previously called out
in the doc comments, which made it easy to mistake for an unmitigated
validation gap rather than documented behavior.
Modifications:
Added a `- Precondition:` note to the doc comments of `setBytes(_:at:)`
(all overloads), `setInteger(_:at:...)`, and `setString(_:at:)` in
NIOCore, making the trapping behavior explicit and noting that callers
must validate any externally-derived `index` before use.
Result:
No behavior changes. The trapping contract on these `set*` write APIs is
now documented, matching the existing convention used by `get*`'s
optional-return documentation.One line description of your change
### Motivation:
The old NIOCrashTester doesn't work on Windows and would be hard to
port. Also, Swift Testing has wonderful 'exit test' ability, let's use
that!
### Modifications:
- Rewrite all NIOCrashTester tests in Swift Testing
### Result:
- Less code to maintain
- (hopefully) works on Windows
- fixes#3657
Add the two remaining non-test, non-NIOFS targets to the Windows CI
build list.
NIOPerformanceTester builds and runs on Windows. The only obstacle was
the `setbuf(stdout, nil)` call: `stdout` is a macro on the Windows CRT
that Swift cannot reference directly. Add a
`CNIOWindows_setStdoutUnbuffered()` wrapper so the C compiler expands
the macro (keeping us correct if its definition ever changes), and call
it on Windows.
NIOCrashTester cannot function on Windows: its OutputGrepper captures a
child process's output through a pipe channel (`NIOPipeBootstrap`),
which deliberately `fatalError`s on Windows, and relies on
`Foundation.Pipe` fd conversion plus Unix-signal crash detection. Extend
the existing `!canImport(Darwin) || os(macOS)` guard with `&&
!os(Windows)` across the target so it compiles to a no-op on Windows,
just as it already does on the non-macOS Darwin platforms.
This PR gets TCP (Servers) on Windows mostly working. I'll annotate my
PR for clarity.
**The one bug:**
If you open a TCP client connection to a Windows TCP server, it doesn't
read/write yet until a second connection comes in. This happens because
`reregister0` is called after `WSAPoll` is called - but WSAPoll isn't
woken up to know this so it doesn't know the new socket requests
read/writes/...
Also the EventLoop cannot be woken up during `el.execute { .. }` because
`SleepEx` isn't running. WSAPoll doesn't respond to this signal it
seems.
This makes the TCP server functionality not yet usable, but I thought
with this draft we could figure out what I'm missing.
Alternative considered: We can make `WSAPoll` limited to wake up every 1
ms for example, that way we can still get to these events at _some_
point.
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
Co-authored-by: Fabian Fett <fabianfett@apple.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: Oliver Drobnik <oliver@cocoanetics.com>
Co-authored-by: Jake Petroules <jake.petroules@apple.com>
Co-authored-by: George Barnett <gbarnett@apple.com>
Co-authored-by: Gabriele Mondada <gab@ijk.ch>
### Motivation:
NIO's historic limit was that the maximum header block was limited to 80
kB which is a sensible limit and originates from Nginx's http_parser.c.
The history of the changes:
- commit e67fc995: Introduces the 80 kB limit
- commit 69180342: Accidentally removes the limit entirely
- commit b24872d3: Introduced the 2 MB / 256 headers limit
I would argue that 2MB & 256 headers is a bad limit:
- 2MB is way too big, that allows pretty powerful slowloris-style
attacks forcing NIO to hold on to 2 MB per connection
- 256 headers is too little for software that may be a proxy
- in HTTP, the number of headers is _non-semantic_
- A: `a: 1\r\n a: 2\r\n a: 3\r\n a: 4\r\n a: 5\r\n a: 6\r\n[...]\r\na:
257\r\n`
- B: `a: 1, 2, 3, 4, 5, ..., 257\r\n`
- A & B are _equivalent_. Yet, A would be rejected and B accepted.
That's not right.
### Modifications:
Restore the old limits.
### Result:
- More compatible (because we allow more than 256 headers)
- More secure (because the default goes back to 80kB)
Motivation:
Users can write arbitrary code in their deinits, and that arbitrary code
_may_ end up hitting Objective-C autoreleases. We don't want to leak
those objects into the per-thread autoreleasepool, as that may not be
popped for a very long time, if ever, so we need to to ensure that
deiniting the task objects has an autoreleasepool.
Modifications:
Add an autoreleasepool around the task drop, and tests to validate that
we do things correctly.
Result:
Better memory management around deinit
### Motivation
`HTTPResponseEncoder` writes hand-optimised status lines for the
well-known `HTTPResponseStatus` values instead of going through the
general `default` path that formats `HTTP/<version> <code>
<reasonPhrase>`. Several of those fast paths had drifted out of sync
with `HTTPResponseStatus.reasonPhrase`, so the exact bytes on the wire
depended on whether a status happened to have a fast path:
* **HTTP/1.0 + 511** emitted the wrong HTTP version (`HTTP/1.1 511 ...`)
— a wire-format correctness bug, not just cosmetic.
* **HTTP/1.1 + 431** emitted the reason phrase `Range Not Satisfiable`
instead of `Request Header Fields Too Large`.
* **HTTP/1.1 + 416** emitted `Request Range Not Satisified` (also
misspelled) instead of `Range Not Satisfiable`.
* **HTTP/1.0 and HTTP/1.1 + 307** emitted `Tempory Redirect`
(misspelled) instead of `Temporary Redirect`.
Resolves#3630.
### Modifications
* Correct the five diverging status lines in `HTTPResponseEncoder` so
they match `HTTPResponseStatus.reasonPhrase` and carry the correct HTTP
version.
* Add a regression test that, for every well-known status at both
HTTP/1.0 and HTTP/1.1, asserts the encoded status line equals the
canonical `HTTP/<version> <code> <reasonPhrase>` form, keeping the fast
paths in lockstep with `reasonPhrase`.
### Result
The encoder now produces correct, consistent status lines for all
well-known statuses regardless of whether they use a fast path. The new
test fails on the pre-fix code (the 511 case fails on the version, the
431/416/307 cases on the reason phrase) and passes after the fix.
---------
Co-authored-by: George Barnett <gbarnett@apple.com>
Off-by-one in the QUIC variable-length integer length boundaries.
### Motivation:
`bytesNeededForInteger` classifies an integer into the 1/2/4/8 byte QUIC
encoding using half-open ranges (`0..<63`, `0..<16383`,
`0..<1_073_741_823`, `0..<4_611_686_018_427_387_903`). Those upper
bounds are the *largest* value each size can hold (2^6-1, 2^14-1, 2^30-1
and 2^62-1 per RFC 9000 § 16), so each maximum is wrongly excluded:
- 63, 16383 and 2^30-1 report one byte too many, so the encoder writes
them with a larger encoding than needed.
- 2^62-1, the largest value the encoding can represent, falls through to
the `fatalError` and crashes the encoder.
The existing one-byte write test only iterates `0..<63`, so the 63 case
was never exercised.
### Modifications:
- Switch the four ranges in `bytesNeededForInteger` to inclusive bounds.
- Extend the one-byte write test to include 63, and add boundary checks
plus a 2^62-1 round-trip test.
### Result:
Boundary values encode in the minimal number of bytes and 2^62-1
round-trips instead of crashing.
Co-authored-by: Cory Benfield <lukasa@apple.com>
This PR is just a cleanup of the source code.
### Motivation:
The `CNIOFreeBSD` source code contains inconsistent trailing
whitespaces, which hinders future modifications.
### Modifications:
Removed all trailing whitespaces from `CNIOFreeBSD`.
### Result:
The source code remains exactly the same; only the trailing whitespace
has been removed.
Co-authored-by: Cory Benfield <lukasa@apple.com>
We are running into some issues when doing:
```swift
let writeOptions: OpenOptions.Write =
byteOffset > 0 ? .modifyFile(createIfNecessary: true) : .newFile(replaceExisting: true)
try await FileSystem.shared.withFileHandle(
forWritingAt: FilePath(outputFilePath),
options: writeOptions
) { fileHandle in
```
which results in crashes on some Android devices where `renameat2` is
not available:
```
('renameat2' system call failed with '(38) Function not implemented'.)
```
This PR adds functionality similar to what is already done for `EINVAL`
on Linux, such that both lead to the same recovery: stat the
destination, then plain rename() if absent.
And for non-exclusive renames where it also fails to function not
implemented, it falls back to plain `rename`.
Error instead of silently truncating oversized `NonBlockingFileIO`
reads.
### Motivation:
A `ByteBuffer` can hold at most `UInt32.max` bytes, so a read for more
than that can never be satisfied. Today the read functions clamp the
requested `byteCount` to `Int32.max` and then read at most that many
bytes, returning a short buffer with no error and no end-of-file. That
silently breaks the documented contract that the returned `ByteBuffer`
is only shorter than `byteCount` when end-of-file is reached. It also
means a request between 2 GiB and 4 GiB returns fewer bytes than the
caller asked for.
Resolves#2591.
### Modifications:
- `read0` (both the `EventLoopFuture` and the `async` overload) now
fails with an `IOError` (`EINVAL`) when `byteCount` is larger than
`UInt32.max` instead of clamping. The guard runs before any allocation.
On 32-bit platforms `Int.max` is smaller than `UInt32.max` so the guard
is never hit there, and behaviour is unchanged.
- `readSync` now caps the size of each individual `read`/`pread` syscall
at `Int32.max` rather than capping the total `byteCount`. The OS returns
`EINVAL` for a single read larger than `Int32.max`, and the surrounding
loop already reads repeatedly until the whole request is satisfied or
end-of-file is reached, so a request up to `UInt32.max` is now read in
full.
- Added tests covering the future and async read variants for a
`byteCount` larger than a `ByteBuffer` can hold.
I went with `IOError(errnoCode: EINVAL, ...)` rather than a new
`NonBlockingFileIO.Error` case to keep this non API-breaking, matching
the existing `IOError(errnoCode: ENOTDIR, ...)` use in the same file.
Happy to switch to a typed error case if you would prefer that.
### Result:
A read that cannot fit in a `ByteBuffer` fails clearly, and reads
between 2 GiB and 4 GiB are no longer truncated. No public API changes.
`ByteBuffer` exposes `read`, `write`, and (since the peek work landed)
`peek`
variants of `MultipleIntegers`, but not the absolute-index `get`/`set`
pair that
every other integer accessor on `ByteBuffer` has. This fills that gap,
which is
what #2736 originally asked for.
The thread on #2736 settled on adding `peek*` first so that the common
"look without consuming" use case has a non-mutating, index-free
spelling, and
that is now in place. `get`/`set` remain useful for the niche cases that
genuinely need to address an arbitrary index, so this completes the set
of four
for `MultipleIntegers` to match `getInteger`/`setInteger`.
Both methods are generated from `dev/generate-bytebuffer-multi-int.sh`,
the same
script that produces the read/write/peek variants, so they stay in
lockstep with
the rest of the file across all arities (2 through 15):
- `getMultipleIntegers(at:endianness:as:)` reads at an explicit index
without
moving the reader index and returns `nil` when the requested bytes are
not
readable, exactly like `getInteger(at:)`.
- `setMultipleIntegers(_:at:endianness:as:)` writes at an explicit index
without
moving the writer index and returns the number of bytes written, exactly
like
`setInteger(_:at:)`.
The new tests mirror the existing read/write and peek tests: a
round-trip across
both endiannesses, a check that the bytes written by `set` are
byte-for-byte
identical to `writeMultipleIntegers`, coverage of every arity, a check
that
neither method moves the reader or writer index, and the out-of-bounds /
before-reader-index cases that must return `nil`.
Resolves#2736
RFC 6455 §5.2 specifies that when the payload length indicator byte is
127, the following 8 bytes hold a 64-bit unsigned integer and the most
significant bit of that integer must be 0. The maximum legal value is
therefore 0x7FFFFFFFFFFFFFFF, which equals Int.max on all 64-bit
platforms Swift supports.
WSParser.parseStep read the raw UInt64 and passed it directly to Int()
without a bounds check. Swift's Int initializer performs a checked
conversion and traps on overflow, so any remote peer that sends a single
WebSocket frame with the MSB of the 8-byte length set will cause a fatal
error in the receiving process. No authentication is required; the frame
is processed before any application handler runs.
The fix adds a guard that rejects the frame with
NIOWebSocketError.invalidFrameLength before the conversion, which is the
same error path used for frames that exceed maxFrameSize. The call site
in decode() is updated to propagate the throw.
A regression test covers the exact byte sequence that previously caused
the fatal trap.
Co-authored-by: g0w6y <g0w6y@users.noreply.github.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
ByteBuffer.readInlineArray reads each element through getInteger(at:).
The index parameter of getInteger(at:) is an absolute index into the
buffer, the same one readInteger passes self.readerIndex into. The loop
in readInlineArray instead passed stride * index, which starts at zero
and never accounts for the reader index.
As long as the buffer has a reader index of zero this absolute index
lines up with the bytes the caller expects, which is why the current
tests pass: they all read from a freshly written buffer. On any buffer
whose reader index has already moved (the normal case once some bytes
have been consumed, for example reading a length prefix before the
array), getInteger(at:) is given an index below the reader index.
rangeWithinReadableBytes rejects it, getInteger returns nil, and the
force-unwrap on the result traps. So a public read API crashes the
process on entirely valid input.
The fix snapshots the reader index before building the array and offsets
each element index by it, so getInteger(at:) gets the correct absolute
index. The multiplication stays bounded by bytesRequired as before, and
adding the reader index cannot overflow because the result stays within
the writer index.
I added a regression test that writes a short prefix, reads it off so
the reader index is non-zero, then reads an InlineArray and checks both
the element values and the resulting reader index. It traps before this
change and passes after it. The three existing InlineArray tests, the
full ByteBufferTest suite (275 tests), and ByteBufferSpanTests all still
pass.
Reopening the change from #3604, which I closed inadvertently. The
original branch and fork were deleted, so this is a fresh PR with the
identical commit.
Don't fatalError in
NIOTypedHTTPServerUpgraderStateMachine.findingUpgraderCompleted` when
the state is `.finished`.
### Motivation:
There is a race where the connection can be closed and the
NIOTypedHTTPServerUpgraderHandler can be removed setting the state to
`.finished` while we are still finding upgraders. And then when
`findingUpgraderCompleted` gets called it would fatalError.
### Modifications:
- Return `nil` as an action if the state is `.finished` when
`findingUpgraderCompleted` is called.
- Added a new set of tests which test the
`NIOTypedHTTPServerUpgraderStateMachine` directly instead of relying on
`HTTPServerUpgraderTests`. I used Swift Testing for these, not sure what
NIO policy on new tests are?
### Result:
No more crashes and better testing for
NIOTypedHTTPServerUpgraderStateMachine
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
### Motivation
We want our tests to pass in reasonable time.
### Changes
- Disable test
`ByteBufferCrashTests.setBytesWithoutContigiousStorageMoreThanUInt32maxBytes`
- Do not initialize data in `ByteBufferCrashTests.
takingOwnershipOfPointerThatsToLarge`
### Result
Tests are faster again.
Add configurable HTTP/1 decoder parsing limits
### Motivation:
The HTTP/1 decoder previously enforced a single hardcoded limit (80 KB per header field) and placed no cap on the total header-block size or the number of header fields per message. That made resource use unpredictable on requests with very many or very large headers, and there was no way for users to tune the limits for their workload.
### Modifications:
- Introduce a new public `NIOHTTPDecoderLimitConfiguration` exposing three parsing limits:
- maxHeaderFieldSize — maximum size of a single header field (name + value). Default: 80 KB.
- maxHeaderListSize — maximum total bytes of all header field names and values combined per message. Default: 2 MB.
- maxHeaderFieldCount — maximum number of header fields per message, including trailers. Default: 256.
- Plumb the configuration through `HTTPDecoder` / `HTTPRequestDecoder` / `HTTPResponseDecoder` initializers. The existing initializers continue to work unchanged via convenience overloads that fall back to
default limits.
- Expose the configuration on `NIOUpgradableHTTPServerPipelineConfiguration` and `NIOUpgradableHTTPClientPipelineConfiguration` so users of the typed pipeline setup can override the defaults.
- Track per-message totals in `BetterHTTPParser` and reject with `HTTPParserError.headerOverflow` when a limit is exceeded; counters reset at each new message so HTTP/1 pipelined connections behave
correctly.
- Add tests covering the success and error paths for each limit, the default behaviors, and that trailer fields count toward the field-count cap.
### Result:
Users can configure the HTTP/1 decoder's per-field-size, total-list-size, and field-count limits. Existing call sites continue to compile and run unchanged, now with bounded defaults across all three dimensions instead of just one.
## Summary
Trivial typo fix in the Swift Concurrency user-facing documentation.
In
[`Sources/NIOCore/Docs.docc/swift-concurrency.md`](https://github.com/apple/swift-nio/blob/main/Sources/NIOCore/Docs.docc/swift-concurrency.md),
the NIOAsyncChannel websocket-upgrade walkthrough reads:
> switch over the the `upgradeResult`. Importantly, we have to `await`
the
Drops the duplicate "the".
## Test plan
- [x] `grep -rEn '\b(the the|of of|in in|and and|that that|is is|to
to)\b' --include='*.swift' --include='*.md' Sources` — exit 1 after the
fix (was the only hit before).
## Scope
One-character change in one Markdown file. No code, no behavior, no API.
Co-authored-by: Cory Benfield <lukasa@apple.com>
The `getifaddrs` is only available on Android API 24+. So, to make
`swift-nio` compile on API 23, we need to add `@available` annotations
to the functions that use it. Which are just the two interface enumerate
functions.
### Result:
`swift-nio` can be compiled for Android 23.
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
### Motivation:
When connecting to services with multiple DNS records (e.g. Kubernetes
headless services), getaddrinfo returns addresses in a deterministic
order, causing all connections to go to the same backend. SwiftNIO now
provides a RandomizedDNSResolver that shuffles results.
### Modifications:
Add a dnsResolver property to HTTPClient.Configuration with two options:
.system (default, current behavior) and randomized (uses NIO's
RandomizedDNSResolver to shuffle DNS results). Apply the resolver to
ClientBootstrap during connection creation.
### Result:
Users can opt into randomized DNS resolution by setting
config.dnsResolver = .randomized, enabling load distribution across
multiple backend IPs while preserving the default behavior.
---------
Co-authored-by: Pavan sai kumar alladi <p_alladi@apple.com>
Allow concurrent calls of `_createDirectory()` for file paths with
shared ancestors.
### Motivation:
The current implementation of
`_createDirectory(withIntermediateDirectories: true)` does not catch and
continue during execution when the intermediate directory path it is
trying to create already exists.
The current loop looks like this:
```swift
// Successfully made a directory, construct its children.
while let subdirectory = droppedComponents.popLast() {
path.append(subdirectory)
switch Syscall.mkdir(at: path, permissions: permissions) {
case .success:
continue
case let .failure(errno):
return .failure(.mkdir(errno: errno, path: path, location: .here()))
}
}
```
If we are concurrently trying to create directories `/foo/bar/dir1` and
`foo/bar/dir2`, we can fail with an error like `directory /foo already
exists` because one of the two task's `mkdir` syscall on line 928
errored with a `fileExists` error.
### Modifications:
The code adds the same logic already present on lines 894-907 of
`FileSystem.swift` to the failure case while iterating over the
subdirectory paths:
If the syscall errors because the directory already exists, (but didn't
exist during the loop on lines 886-923), we can safely continue. Another
task must have beaten our task to creating the directory, but that is
ok.
### Result:
Without this change, it would be difficult to actually call the
`FileSystem.createDirectory(withIntermediateDirectories: true)` function
in concurrent tasks, because if you were creating directories with
common ancestors, at least one of the 2 tasks would error due to the
race condition on directory creation. With this change, the
`createDirectory()` function can now be called concurrently without this
race issue potentially causing an error. I added the change to both the
`NIOFS` and `_NIOFileSystem` directories since they seem to be copies of
each other.
Co-authored-by: David Stern <d_stern@apple.com>
Add missing helpers for reading length-prefixed strings and bytes with
customizable encodings for the length.
### Motivation:
There are already some APIs for writing length-prefixed strings and
bytes with a custom strategy for encoding the length, but there weren't
helpers to read them.
### Modifications:
- Add missing helpers for reading length-prefixed strings and bytes with
customizable encodings for the length
- Add tests for the new APIs
- Fix DocC comments and improve the related article
### Result:
New APIs are added for reading length-prefixed strings and bytes with a
custom strategy for encoding the length.
This PR is a step towards having full support for FreeBSD in SwiftNIO.
It builds on #3494 to enable full compilation of the NIOCore target.
### Motivation:
Currently, SwiftNIO doesn't not compile on FreeBSD. This PR ensures that
at least the **NIOCore** module compiles correctly on FreeBSD.
### Modifications:
* Make `swift build --target NIOCore` work on FreeBSD.
### Result:
Using the available Swift FreeBSD x86_64 toolchain, it is now possible
to run `swift build --target NIOCore` successfully.
Strip Transfer-Encoding when Content-Length is present in HTTPEncoder
### Motivation
When `correctlyFrameTransportHeaders()` detected a `Content-Length`
header, it returned `.contentLength` without removing any existing
`Transfer-Encoding` header.
### Changes
- Remove `Transfer-Encoding` header, if a `Content-Length` header is
present
### Result
NIO sends either a `Content-Length` header or a `Transfer-Encoding`
header, but not both.
### Motivation:
Internally, `FTSInfo` always casted up to `CInt` from `UInt16` but for
some reason it only accepted `UInt16`. Let's add a `CInt` constructor
too.
### Modifications:
- Make internal `FTSInfo` constructible from `CInt` and `UInt16`.
### Result:
- Slightly better platform compatibility
- Possibly fewer casts
Split FoundationEssentials extensions from NIOFoundationCompat
### Motivation:
Resolves#3038
### Modifications:
Split NIOFoundationCompat into two and only import FoundationEssentials
and NIOFoundationEssentialsCompat where appropriate.
### Result:
ByteBuffer/Codable extensions can be used without vendoring the code or
linking to Foundation.
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
Co-authored-by: Fabian Fett <fabianfett@apple.com>
As observed by @weissi https://github.com/apple/swift-nio/issues/3382
### Motivation:
When `getaddrinfo` fails, SwiftNIO throws `SocketAddressError.unknown`
which discards the error code. This makes it impossible for callers to
distinguish between different failure reasons (e.g., `EAI_NONAME` vs
`EAI_AGAIN`), which is needed for retry logic and diagnostics.
### Modifications:
- Add `SocketAddressError.UnknownHost` struct that carries `host`,
`port`, `errorCode` (from `getaddrinfo`), and `errorDescription` (from
`gai_strerror`).
- Update `SocketAddress.makeAddressResolvingHost` and
`GetaddrinfoResolver` to throw/fail with the new error type on both
POSIX and Windows paths.
- Update existing test catch blocks to use the new error type.
- Add `testGetaddrinfoErrorCodeIsPreserved` to verify the error code is
captured.
### Result:
Callers can now inspect the `getaddrinfo` error code when host
resolution fails, enabling more specific error handling. Resolves
https://github.com/apple/swift-nio/issues/3382
### Questions for reviewer
1. **Should `case unknown(host:port:)` be deprecated?** — This enum case
is no longer thrown after this PR. Callers catching `.unknown` will
silently stop matching. Should I add
`@available(*, deprecated, renamed: "UnknownHost")` to provide a
migration path?
2. **Should the doc comment on `makeAddressResolvingHost` be updated?**
— The `- Throws:` line still references `SocketAddressError.unknown`
instead of the new
`SocketAddressError.UnknownHost`.
---------
Co-authored-by: Si Beaumont <beaumont@apple.com>
## Summary
- NIOFileSystem's `open` syscall error mapping only handled `EACCES`
(`.permissionDenied`) but not `EPERM` (`.notPermitted`), causing EPERM
errors (e.g., on network volumes) to be classified as "unknown" instead
of `permissionDenied`
- Added `.notPermitted` alongside `.permissionDenied` in the `open()`
switch case in `FileSystemError+Syscall.swift` (both `NIOFS` and
`_NIOFileSystem` modules)
- Added corresponding test expectation for the new errno mapping
## Motivation
Other syscall handlers in the same file (`remove`, `symlink`, `unlink`,
`futimens`) already correctly handle both `.permissionDenied` and
`.notPermitted` as `permissionDenied`. The `open` handler was missing
this treatment.
Fixes#3559
## Test plan
- [x] Updated `testErrnoMapping_open` to verify `.notPermitted` maps to
`.permissionDenied`
- [ ] CI will validate on all supported Swift versions
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Motivation:
Similar to MultiThreadedEventLoopGroup, it is useful in some NUMA
circumstances to be able to pin thread pools to specific CPUs. This can
minimise the overheads of moving memory around across NUMA nodes.
Modifications:
Added a pinned CPUs initializer to NIOThreadPool
Result:
Users have more flexibility.