From cacadaa4f15d23797a9adcbec2007230c4334c97 Mon Sep 17 00:00:00 2001 From: renerocksai Date: Sun, 13 Sep 2026 19:00:47 +0200 Subject: [PATCH 1/3] Support explicit IPv4 listener addresses --- README.md | 18 ++++++++- docs/ARCHITECTURE.md | 4 +- docs/USING.md | 9 +++++ docs/whitepaper.html | 4 +- docs/whitepaper.template.html | 4 +- src/main.zig | 11 ++++-- src/server.zig | 34 +++++++++++++++-- src/transport.zig | 29 +++++++++++++- src/transport_linux.zig | 6 ++- src/transport_macos.zig | 6 ++- src/transport_windows.zig | 44 +++++++++++++++++++--- tests/integration.py | 71 ++++++++++++++++++++++++++++++++++- 12 files changed, 215 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index 567d651..61c9785 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ This is the M4 implementation informed by the adjacent The first goal is a working ownership and pending/resume model that we can measure and change. This is not a production qualification or a TechEmpower -ranking. It listens on **IPv4 loopback only**, speaks plain HTTP/1.1, and has no +ranking. It defaults to **IPv4 loopback**, accepts explicit IPv4 binding, speaks plain HTTP/1.1, and has no TLS, proxy protocol, upgrade/tunnel implementation or general file server. Run these commands from the repository root with the exact `zig` compiler on @@ -63,12 +63,26 @@ zig build -Doptimize=ReleaseSafe On Windows, use `.\zig-out\bin\bounded-http.exe` from PowerShell. Windows defaults to one I/O shard; `--shards 3` enables three independent IOCP owners. One listener distributes socket ownership through startup-bounded queues. +Choose an IPv4 listener address explicitly for LAN clients: + +```sh +./zig-out/bin/bounded-http --bind-address 0.0.0.0 --port 8080 --connections 128 +``` + +`0.0.0.0` binds all IPv4 interfaces. A specific local IPv4 address binds only that address. +Clients connect to the host's actual address, not `0.0.0.0`. +The CLI accepts four decimal octets, with no hostname lookup or IPv6 parsing. +Embedded applications set `Config.bind_address = .{ 0, 0, 0, 0 }`. +`Config.parseBindAddress(text)` provides the same allocation-free startup parser. +The default remains `127.0.0.1`. Binding does not change connection limits, resource budgets, or backpressure. +Linux shard listeners and the Windows acceptor receive the same configured address. + See the [architecture guide](docs/ARCHITECTURE.md#windows-socket-handoff) and [native shard receipt](reports/2026-09-06-windows-shards.md). The version must print `0.16.0`. The server prints `READY` to stderr after startup. Linux and macOS accept SIGINT or SIGTERM; Windows consoles accept Ctrl-C or Ctrl-Break. `--duration-ms 30000` requests -shutdown after a finite run. `--port 0` asks the OS for an available loopback +shutdown after a finite run. `--port 0` asks the OS for an available port, reported in `READY`. The HTML file is loaded before serving starts. | Route | Behavior | diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 622750d..3be1996 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -7,7 +7,9 @@ macOS uses nonblocking sockets and `kqueue`. Windows uses overlapped sockets and an I/O completion port (IOCP), which delivers operation results to the owner. The server remains experimental. -The listener accepts IPv4 loopback connections only. +The listener defaults to IPv4 loopback. +`Config.bind_address` selects another local IPv4 address or wildcard `0.0.0.0`. +The address is fixed at startup and does not change admission or storage bounds. The implementation has no Transport Layer Security (TLS), protocol upgrade, or tunnel support. See [using the server](USING.md) for embedding instructions. diff --git a/docs/USING.md b/docs/USING.md index 5951066..5747bc9 100644 --- a/docs/USING.md +++ b/docs/USING.md @@ -504,3 +504,12 @@ A client can limit measured throughput. Closed-loop request measurements do not establish an open-loop latency guarantee. Use [recorded reports](../reports) for existing experiments and their exact scope. Use the [roadmap](../ROADMAP.md) to identify remaining qualification work. + +## Listener address + +`Config.bind_address` contains four IPv4 octets. The default is `.{ 127, 0, 0, 1 }`. +Use `.{ 0, 0, 0, 0 }` for all IPv4 interfaces, or supply a specific local address. +`Config.parseBindAddress(text)` parses four decimal octets without allocation or hostname lookup. +The standalone CLI exposes this setting as `--bind-address A.B.C.D`. +An unavailable local address fails at startup. Each shard uses the same address. +Changing the address does not change connection admission, storage limits, or backpressure. diff --git a/docs/whitepaper.html b/docs/whitepaper.html index 9b44ddc..d6aad15 100644 --- a/docs/whitepaper.html +++ b/docs/whitepaper.html @@ -51,7 +51,7 @@

Fast by design.
Explicit about limits.

  • macOSkqueueNonblocking sockets
  • WindowsIOCPOverlapped operations
  • -

    EXACT ZIG 0.16.0ASSERTIONS ENABLEDLOOPBACK EXPERIMENT

    +

    EXACT ZIG 0.16.0ASSERTIONS ENABLEDEXPERIMENTAL HTTP/1.1

    0Extra application threads
    Default configuration
    128Connections served
    Default simultaneous limit
    @@ -824,7 +824,7 @@

    Reserve output before application side effects.

    Ownership remains uncertainThe process terminates instead of freeing storage with outstanding borrows. An inline callback never returnsThe framework cannot preempt that callback. An external watchdog must supervise a violating application.
    -

    The current server binds IPv4 loopback and serves plain HTTP. Transport Layer Security (TLS) and production deployment qualification remain pending.

    +

    The server defaults to IPv4 loopback and serves plain HTTP. Set --bind-address 0.0.0.0 for all IPv4 interfaces, or select a specific local IPv4 address. Connection and memory limits still apply. Transport Layer Security (TLS) and production deployment qualification remain pending.

    The Windows shard receipt records native x64 distribution, admission, and shutdown tests. Windows performance remains unmeasured.

    Winsock creates socket resources during admission. Fixed framework storage does not bound provider allocations or delayed kernel cleanup.

    Dynamic borrow-release notifications and per-request worker offload remain pending. Applications cannot safely invent those ownership mechanisms around the current API.

    diff --git a/docs/whitepaper.template.html b/docs/whitepaper.template.html index 0890220..b011ae3 100644 --- a/docs/whitepaper.template.html +++ b/docs/whitepaper.template.html @@ -51,7 +51,7 @@

    Fast by design.
    Explicit about limits.

  • macOSkqueueNonblocking sockets
  • WindowsIOCPOverlapped operations
  • -

    EXACT ZIG 0.16.0ASSERTIONS ENABLEDLOOPBACK EXPERIMENT

    +

    EXACT ZIG 0.16.0ASSERTIONS ENABLEDEXPERIMENTAL HTTP/1.1

    0Extra application threads
    Default configuration
    128Connections served
    Default simultaneous limit
    @@ -227,7 +227,7 @@

    Reserve output before application side effects.

    Ownership remains uncertainThe process terminates instead of freeing storage with outstanding borrows. An inline callback never returnsThe framework cannot preempt that callback. An external watchdog must supervise a violating application.
    -

    The current server binds IPv4 loopback and serves plain HTTP. Transport Layer Security (TLS) and production deployment qualification remain pending.

    +

    The server defaults to IPv4 loopback and serves plain HTTP. Set --bind-address 0.0.0.0 for all IPv4 interfaces, or select a specific local IPv4 address. Connection and memory limits still apply. Transport Layer Security (TLS) and production deployment qualification remain pending.

    The Windows shard receipt records native x64 distribution, admission, and shutdown tests. Windows performance remains unmeasured.

    Winsock creates socket resources during admission. Fixed framework storage does not bound provider allocations or delayed kernel cleanup.

    Dynamic borrow-release notifications and per-request worker offload remain pending. Applications cannot safely invent those ownership mechanisms around the current API.

    diff --git a/src/main.zig b/src/main.zig index 07b15a8..5a3b953 100644 --- a/src/main.zig +++ b/src/main.zig @@ -58,14 +58,16 @@ pub fn main(init: std.process.Init) !void { while (args.next()) |flag| { if (std.mem.eql(u8, flag, "--help")) { std.debug.print("bounded-http: bounded experimental Linux io_uring / macOS kqueue / Windows IOCP HTTP/1.1\n" ++ - "--port N --connections N --execution workers|inline --workers N --max-body N --max-header N\n" ++ + "--bind-address A.B.C.D --port N --connections N --execution workers|inline --workers N --max-body N --max-header N\n" ++ "--timeout-ms N --duration-ms N --send-chunk N --gather-send 0|1 --stall-ms N\n" ++ "--response-batch-limit N --socket-send-buffer N --output-bytes N --max-response N --memory-budget N --index FILE\n" ++ "--borrow-copy-threshold N --callbacks-per-turn N --callback-timing 0|1 --deadline-sweep-ms N --shards N\n", .{}); return; } const value = args.next() orelse return error.MissingArgument; - if (std.mem.eql(u8, flag, "--port")) { + if (std.mem.eql(u8, flag, "--bind-address")) { + config.bind_address = try framework.Config.parseBindAddress(value); + } else if (std.mem.eql(u8, flag, "--port")) { config.port = try std.fmt.parseInt(u16, value, 10); } else if (std.mem.eql(u8, flag, "--connections")) { config.connections = try std.fmt.parseInt(u16, value, 10); @@ -155,8 +157,9 @@ pub fn main(init: std.process.Init) !void { }; try cluster.start(); budget.sealed.store(true, .release); - std.debug.print("READY port={d} backend={s} connections={d} workers={d} execution={s} gather_send={d} response_batch_limit={d} shards={d} callbacks_per_turn={d} optimize={s}\n", .{ - cluster.port(), framework.backend_name, config.connections, config.workers, @tagName(config.execution), @intFromBool(config.gather_send), config.effectiveBatchLimit(), shards, cluster.shards[0].stats.callbacks_per_turn, @tagName(@import("builtin").mode), + std.debug.print("READY port={d} backend={s} connections={d} workers={d} execution={s} gather_send={d} response_batch_limit={d} shards={d} callbacks_per_turn={d} optimize={s} bind_address={d}.{d}.{d}.{d}\n", .{ + cluster.port(), framework.backend_name, config.connections, config.workers, @tagName(config.execution), @intFromBool(config.gather_send), config.effectiveBatchLimit(), shards, cluster.shards[0].stats.callbacks_per_turn, @tagName(@import("builtin").mode), + config.bind_address[0], config.bind_address[1], config.bind_address[2], config.bind_address[3], }); cluster.run() catch |err| { // A stuck callback or uncertain kernel submission still owns memory. diff --git a/src/server.zig b/src/server.zig index 55b724e..4623ba6 100644 --- a/src/server.zig +++ b/src/server.zig @@ -32,6 +32,8 @@ pub const Config = struct { /// Finished responses retained per connection before a drain; each is a /// range of the connection's output arena plus an optional borrowed span. response_batch_limit: u16 = 128, + /// IPv4 listener octets. Wildcard 0.0.0.0 listens on all IPv4 interfaces. + bind_address: [4]u8 = .{ 127, 0, 0, 1 }, port: u16 = 8080, connections: u16 = 128, workers: u16 = 0, @@ -79,6 +81,20 @@ pub const Config = struct { pub const max_callbacks_per_turn_auto: u32 = 8192; + /// Parse four decimal IPv4 octets at startup. No allocation or name lookup. + pub fn parseBindAddress(text: []const u8) error{InvalidBindAddress}![4]u8 { + var address: [4]u8 = undefined; + var octets = std.mem.splitScalar(u8, text, '.'); + for (&address) |*octet| { + const part = octets.next() orelse return error.InvalidBindAddress; + if (part.len == 0 or part.len > 3) return error.InvalidBindAddress; + for (part) |digit| if (digit < '0' or digit > '9') return error.InvalidBindAddress; + octet.* = std.fmt.parseInt(u8, part, 10) catch return error.InvalidBindAddress; + } + if (octets.next() != null) return error.InvalidBindAddress; + return address; + } + pub fn wireBytes(self: Config) !usize { const body = try std.math.mul(usize, self.max_body, 2); return std.math.add(usize, try std.math.add(usize, body, self.max_header), 4096); @@ -445,10 +461,10 @@ pub const Server = struct { const self = try allocator.create(Server); errdefer allocator.destroy(self); var backend = if (builtin.os.tag == .windows) switch (accept_mode) { - .direct => try transport.Backend.init(allocator, config.connections, config.port, config.reuse_port), - .distribute => try transport.Backend.initAcceptor(allocator, config.connections, config.port), + .direct => try transport.Backend.initBound(allocator, config.connections, config.bind_address, config.port, config.reuse_port), + .distribute => try transport.Backend.initAcceptorBound(allocator, config.connections, config.bind_address, config.port), .receive => try transport.Backend.initDestination(allocator, config.connections), - } else try transport.Backend.init(allocator, config.connections, config.port, config.reuse_port); + } else try transport.Backend.initBound(allocator, config.connections, config.bind_address, config.port, config.reuse_port); errdefer backend.deinit(); if (config.gather_send) try backend.enableGather(); const slots = try allocator.alloc(Slot, config.connections); @@ -2703,6 +2719,18 @@ fn vectorString(vec: c.iovec_const) []const u8 { return vec.base[0..vec.len]; } +test "bind address parsing accepts only four bounded decimal octets" { + try std.testing.expectEqual([4]u8{ 127, 0, 0, 1 }, (Config{}).bind_address); + try std.testing.expectEqual([4]u8{ 0, 0, 0, 0 }, try Config.parseBindAddress("0.0.0.0")); + try std.testing.expectEqual([4]u8{ 192, 168, 1, 255 }, try Config.parseBindAddress("192.168.1.255")); + try std.testing.expectEqual([4]u8{ 127, 0, 0, 1 }, try Config.parseBindAddress("127.000.0.001")); + for ([_][]const u8{ "", "localhost", "::1", "127.1", "127.0.0", "127.0.0.1.2", "127..0.1", ".127.0.1", "127.0.0.", "256.0.0.1", "-1.0.0.1", "+1.0.0.1", "1_0.0.0.1", "0x7f.0.0.1", "127.0.0.1 ", " 127.0.0.1", "0000.0.0.1", "127.0.0.1:8080" }) |invalid| { + try std.testing.expectError(error.InvalidBindAddress, Config.parseBindAddress(invalid)); + } + const configured: Config = .{ .bind_address = .{ 192, 168, 1, 2 } }; + try std.testing.expectEqual(configured.bind_address, Cluster.shardConfig(configured, 2, 1, 8080).bind_address); +} + test "configuration rejects combined resource overcommit and impossible worker limits" { try (Config{}).validate(); try std.testing.expectError(error.InvalidConfiguration, (Config{ .execution = .workers, .workers = 0 }).validate()); diff --git a/src/transport.zig b/src/transport.zig index ac6d17d..2962a19 100644 --- a/src/transport.zig +++ b/src/transport.zig @@ -52,7 +52,13 @@ pub fn setSendBuffer(backend: *Backend, socket: Socket, bytes: u32) !void { // framework connection admission; it cannot establish application admission. // With `reuse_port`, several owners may bind the same address; on Linux the // kernel distributes connections across them. -pub fn listen(port_number: u16, max_connections: u16, nonblocking: bool, reuse_port: bool) !struct { socket: Socket, port: u16 } { +const Listener = struct { socket: Socket, port: u16 }; + +pub fn listen(port_number: u16, max_connections: u16, nonblocking: bool, reuse_port: bool) !Listener { + return listenBound(.{ 127, 0, 0, 1 }, port_number, max_connections, nonblocking, reuse_port); +} + +pub fn listenBound(bind_address: [4]u8, port_number: u16, max_connections: u16, nonblocking: bool, reuse_port: bool) !Listener { if (max_connections == 0 or max_connections > 16383) return error.InvalidConnectionLimit; const fd = c.socket(c.AF.INET, c.SOCK.STREAM, 0); if (fd < 0) return error.SocketFailed; @@ -65,7 +71,7 @@ pub fn listen(port_number: u16, max_connections: u16, nonblocking: bool, reuse_p } var address: c.sockaddr.in = .{ .port = std.mem.nativeToBig(u16, port_number), - .addr = std.mem.nativeToBig(u32, 0x7f000001), + .addr = @bitCast(bind_address), }; if (c.bind(fd, @ptrCast(&address), @sizeOf(@TypeOf(address))) != 0) return error.BindFailed; if (c.listen(fd, @intCast(max_connections)) != 0) return error.ListenFailed; @@ -285,3 +291,22 @@ test "two reuse-port listeners share one loopback port" { defer second.deinit(); try std.testing.expectEqual(first.port(), second.port()); } + +test "listener binds the configured IPv4 address and preserves loopback default" { + if (builtin.os.tag == .windows) return error.SkipZigTest; + var address: c.sockaddr.in = undefined; + for ([_][4]u8{ .{ 0, 0, 0, 0 }, .{ 127, 0, 0, 1 } }) |expected| { + const configured = try listenBound(expected, 0, 1, true, false); + defer closeFd(configured.socket); + var length: c.socklen_t = @sizeOf(@TypeOf(address)); + try std.testing.expectEqual(@as(c_int, 0), c.getsockname(configured.socket, @ptrCast(&address), &length)); + try std.testing.expectEqual(expected, @as([4]u8, @bitCast(address.addr))); + try std.testing.expect(configured.port != 0); + } + + const default = try listen(0, 1, true, false); + defer closeFd(default.socket); + var length: c.socklen_t = @sizeOf(@TypeOf(address)); + try std.testing.expectEqual(@as(c_int, 0), c.getsockname(default.socket, @ptrCast(&address), &length)); + try std.testing.expectEqual(std.mem.nativeToBig(u32, 0x7f000001), address.addr); +} diff --git a/src/transport_linux.zig b/src/transport_linux.zig index c33936e..46a77a4 100644 --- a/src/transport_linux.zig +++ b/src/transport_linux.zig @@ -35,6 +35,10 @@ pub const Backend = struct { transient_retries: u64 = 0, pub fn init(allocator: std.mem.Allocator, max_connections: u16, port_number: u16, reuse_port: bool) !Backend { + return initBound(allocator, max_connections, .{ 127, 0, 0, 1 }, port_number, reuse_port); + } + + pub fn initBound(allocator: std.mem.Allocator, max_connections: u16, bind_address: [4]u8, port_number: u16, reuse_port: bool) !Backend { if (max_connections == 0 or max_connections > 16383) return error.InvalidConnectionLimit; const capacity = common.cellCount(max_connections); const entries = try std.math.ceilPowerOfTwo(u16, @intCast(capacity)); @@ -53,7 +57,7 @@ pub const Backend = struct { const operations = try allocator.alloc(Operation, capacity); errdefer allocator.free(operations); @memset(operations, .{}); - const listener = try common.listen(port_number, max_connections, false, reuse_port); + const listener = try common.listenBound(bind_address, port_number, max_connections, false, reuse_port); errdefer common.closeFd(listener.socket); const result = linux.eventfd(0, linux.EFD.CLOEXEC | linux.EFD.NONBLOCK); if (linux.errno(result) != .SUCCESS) return error.WakeDescriptorFailed; diff --git a/src/transport_macos.zig b/src/transport_macos.zig index abf8dc1..4eae302 100644 --- a/src/transport_macos.zig +++ b/src/transport_macos.zig @@ -40,6 +40,10 @@ pub const Backend = struct { bound_port: u16, pub fn init(allocator: std.mem.Allocator, max_connections: u16, port_number: u16, reuse_port: bool) !Backend { + return initBound(allocator, max_connections, .{ 127, 0, 0, 1 }, port_number, reuse_port); + } + + pub fn initBound(allocator: std.mem.Allocator, max_connections: u16, bind_address: [4]u8, port_number: u16, reuse_port: bool) !Backend { if (max_connections == 0 or max_connections > 16383) return error.InvalidConnectionLimit; const capacity = common.cellCount(max_connections); const operations = try allocator.alloc(Operation, capacity); @@ -47,7 +51,7 @@ pub const Backend = struct { @memset(operations, .{}); const ready = try allocator.alloc(u32, capacity); errdefer allocator.free(ready); - const listener = try common.listen(port_number, max_connections, true, reuse_port); + const listener = try common.listenBound(bind_address, port_number, max_connections, true, reuse_port); errdefer common.closeFd(listener.socket); const queue = c.kqueue(); if (queue < 0) return error.KqueueFailed; diff --git a/src/transport_windows.zig b/src/transport_windows.zig index c255cfd..c2866d5 100644 --- a/src/transport_windows.zig +++ b/src/transport_windows.zig @@ -171,21 +171,29 @@ pub const Backend = struct { } pub fn init(allocator: std.mem.Allocator, max_connections: u16, port_number: u16, reuse_port: bool) !Backend { + return initBound(allocator, max_connections, .{ 127, 0, 0, 1 }, port_number, reuse_port); + } + + pub fn initBound(allocator: std.mem.Allocator, max_connections: u16, bind_address: [4]u8, port_number: u16, reuse_port: bool) !Backend { if (reuse_port) return error.ReusePortUnsupported; - return initMode(allocator, max_connections, port_number, .direct); + return initMode(allocator, max_connections, bind_address, port_number, .direct); } /// The listener owns acceptance. The collected socket awaits its first association. pub fn initAcceptor(allocator: std.mem.Allocator, max_connections: u16, port_number: u16) !Backend { - return initMode(allocator, max_connections, port_number, .acceptor); + return initAcceptorBound(allocator, max_connections, .{ 127, 0, 0, 1 }, port_number); + } + + pub fn initAcceptorBound(allocator: std.mem.Allocator, max_connections: u16, bind_address: [4]u8, port_number: u16) !Backend { + return initMode(allocator, max_connections, bind_address, port_number, .acceptor); } /// Creates a destination port without binding or opening a listener socket. pub fn initDestination(allocator: std.mem.Allocator, max_connections: u16) !Backend { - return initMode(allocator, max_connections, 0, .destination); + return initMode(allocator, max_connections, .{ 127, 0, 0, 1 }, 0, .destination); } - fn initMode(allocator: std.mem.Allocator, max_connections: u16, port_number: u16, mode: Mode) !Backend { + fn initMode(allocator: std.mem.Allocator, max_connections: u16, bind_address: [4]u8, port_number: u16, mode: Mode) !Backend { if (max_connections == 0 or max_connections > 16383) return error.InvalidConnectionLimit; var wsa_data: WsaData = undefined; if (win32.WSAStartup(0x0202, &wsa_data) != 0) return error.WinsockStartupFailed; @@ -214,7 +222,7 @@ pub const Backend = struct { const one: i32 = 1; // No SO_REUSEADDR: Windows interprets that option differently from POSIX. if (win32.setsockopt(listener, ws.SOL.SOCKET, ~@as(i32, ws.SO.REUSEADDR), &one, @sizeOf(i32)) != 0) return error.SocketOptionFailed; - var address: ws.sockaddr.in = .{ .port = std.mem.nativeToBig(u16, port_number), .addr = std.mem.nativeToBig(u32, 0x7f000001) }; + var address: ws.sockaddr.in = .{ .port = std.mem.nativeToBig(u16, port_number), .addr = @bitCast(bind_address) }; if (win32.bind(listener, @ptrCast(&address), @sizeOf(@TypeOf(address))) != 0) return error.BindFailed; if (win32.listen(listener, @intCast(max_connections)) != 0) return error.ListenFailed; var length: i32 = @sizeOf(@TypeOf(address)); @@ -935,3 +943,29 @@ test "IOCP startup worker wakes the owner without borrowing a caller token" { try std.testing.expectEqual(@as(usize, 0), try backend.poll(&out, 1000)); try std.testing.expect(win32.GetTickCount64() - started < 900); } + +test "IOCP direct and acceptor listeners bind the configured IPv4 address" { + for ([_]bool{ false, true }) |acceptor| { + for ([_][4]u8{ .{ 0, 0, 0, 0 }, .{ 127, 0, 0, 1 } }) |expected| { + var backend = if (acceptor) + try Backend.initAcceptorBound(std.testing.allocator, 1, expected, 0) + else + try Backend.initBound(std.testing.allocator, 1, expected, 0, false); + defer backend.deinit(); + var address: ws.sockaddr.in = undefined; + var length: i32 = @sizeOf(@TypeOf(address)); + try std.testing.expectEqual(@as(i32, 0), win32.getsockname(backend.listener, @ptrCast(&address), &length)); + try std.testing.expectEqual(expected, @as([4]u8, @bitCast(address.addr))); + try std.testing.expect(backend.port() != 0); + } + var default = if (acceptor) + try Backend.initAcceptor(std.testing.allocator, 1, 0) + else + try Backend.init(std.testing.allocator, 1, 0, false); + defer default.deinit(); + var address: ws.sockaddr.in = undefined; + var length: i32 = @sizeOf(@TypeOf(address)); + try std.testing.expectEqual(@as(i32, 0), win32.getsockname(default.listener, @ptrCast(&address), &length)); + try std.testing.expectEqual([4]u8{ 127, 0, 0, 1 }, @as([4]u8, @bitCast(address.addr))); + } +} diff --git a/tests/integration.py b/tests/integration.py index 94af0ca..21be0d1 100644 --- a/tests/integration.py +++ b/tests/integration.py @@ -167,8 +167,8 @@ def __enter__(self): require(0 < self.port <= 65535, "invalid bound port") return self - def connect(self, timeout=3.0): - sock = socket.create_connection(("127.0.0.1", self.port), timeout=timeout) + def connect(self, timeout=3.0, host="127.0.0.1"): + sock = socket.create_connection((host, self.port), timeout=timeout) sock.settimeout(timeout) sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) return sock @@ -251,7 +251,74 @@ def expect_closed(sock): pass +def run_binding_suite(binary, emit, sessions): + cases = [("default_loopback", None, "127.0.0.1", 1), + ("explicit_loopback", "127.0.0.1", "127.0.0.1", 1), + ("wildcard", "0.0.0.0", "127.0.0.1", 1)] + if sys.platform.startswith("linux") or os.name == "nt": + cases += [("sharded_loopback", "127.0.0.1", "127.0.0.1", 2), + ("sharded_wildcard", "0.0.0.0", "127.0.0.1", 2)] + if sys.platform.startswith("linux"): + # Linux routes the complete 127/8 prefix locally without an interface alias. + # These clients would fail if the listener silently retained 127.0.0.1. + cases += [("specific_alternate_loopback", "127.0.0.2", "127.0.0.2", 2), + ("wildcard_alternate_loopback", "0.0.0.0", "127.0.0.2", 2)] + close_request = b"GET /plaintext HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n" + for name, address, host, shards in cases: + start = time.monotonic() + options = dict(connections=2, shards=shards, send_chunk=65536) + if address is not None: + options["bind_address"] = address + if shards > 1: + options.update(execution="inline", workers=0) + with Server(binary, **options) as server: + ready = next(line for line in server.lines if line.startswith("READY ")) + require("bind_address=" + (address or "127.0.0.1") in ready, + "listener address missing from READY") + with contextlib.ExitStack() as stack: + held = [stack.enter_context(server.connect(host=host)) for _ in range(2)] + readers = [ResponseReader(sock) for sock in held] + for sock, reader in zip(held, readers): + sock.sendall(REQUEST) + require(reader.response()[2] == PLAINTEXT, "configured listener did not serve HTTP") + # Each response acknowledges an admitted, live keepalive connection. + with server.connect(host=host) as extra: + try: + extra.sendall(REQUEST) + expect_closed(extra) + except ConnectionResetError: + pass + for sock, reader in zip(held, readers): + sock.sendall(close_request) + require(reader.response()[2] == PLAINTEXT, "held connection lost its response") + expect_closed(sock) + with server.connect(host=host) as recovered: + recovered.sendall(close_request) + require(ResponseReader(recovered).response()[2] == PLAINTEXT, + "configured listener did not recover admission") + expect_closed(recovered) + require(server.stats["peak_connections"] == 2 and server.stats["rejected"] >= 1, + "configured listener did not preserve the shared connection ceiling") + require(server.stats["completed"] == 5, "configured listener lost or duplicated requests") + if os.name == "nt" and shards > 1: + require(server.stats["handoffs_received"] > 0, + "configured Windows listener did not exercise destination handoff") + sessions.append(dict(phase="bind_" + name, backend=server.backend, + options=options, client_address=host, stats=server.stats)) + emit("bind_" + name + "_admission_and_recovery", time.monotonic() - start) + + start = time.monotonic() + for invalid in ("", "localhost", "::1", "127.1", "127.0.0.1.2", "256.0.0.1", + "127..0.1", "-1.0.0.1", "1_0.0.0.1", "127.0.0.1:8080"): + result = subprocess.run([str(binary), "--bind-address", invalid], cwd=ROOT, + capture_output=True, timeout=8) + require(result.returncode != 0 and b"InvalidBindAddress" in result.stderr and + b"READY " not in result.stderr, "invalid bind address accepted: %r" % invalid) + emit("invalid_bind_address_rejected_before_startup", time.monotonic() - start) + + def run_suite(binary, emit, sessions): + run_binding_suite(binary, emit, sessions) with Server(binary) as server: def check(name, function): start = time.monotonic() From efd94fc243cbe084e081a1541a542046e935ce45 Mon Sep 17 00:00:00 2001 From: renerocksai Date: Sun, 13 Sep 2026 19:02:57 +0200 Subject: [PATCH 2/3] Update listener scope in embedding and transport guides --- docs/INTERFACES.md | 4 ++-- docs/USING.md | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/INTERFACES.md b/docs/INTERFACES.md index 3ad9a1e..c896f1e 100644 --- a/docs/INTERFACES.md +++ b/docs/INTERFACES.md @@ -59,8 +59,8 @@ Linux uses actual low-level io_uring accept/recv/send, runtime opcode probes, finite queues and explicit cancel drain. macOS uses nonblocking sockets/kqueue and the same completion interface. Windows uses overlapped `AcceptEx`, `WSARecv`, and `WSASend` through one completion port per owner. -IPv4 loopback binding initially; CLI can -expose other bind addresses later. No per-operation allocation. +The listener defaults to IPv4 loopback. `Config.bind_address` selects another local IPv4 address or all IPv4 interfaces. +The CLI exposes `--bind-address`. No operation allocates memory after startup. Gather vectors live in the caller's per-connection startup storage. Linux points its `msghdr` at those vectors. diff --git a/docs/USING.md b/docs/USING.md index 5747bc9..4ce07eb 100644 --- a/docs/USING.md +++ b/docs/USING.md @@ -5,7 +5,8 @@ Use exact Zig 0.16.0, as specified by [.zig-version](../.zig-version). The framework has Linux, macOS, and Windows transport adapters. The [Windows receipt](../reports/2026-09-06-windows-iocp.md) records native verification and its exclusions. -The current listener accepts plain HTTP/1.1 on IPv4 loopback only. +The listener accepts plain HTTP/1.1 and defaults to IPv4 loopback. +Use `Config.bind_address` to select a local IPv4 address or all IPv4 interfaces. The framework has no Transport Layer Security (TLS), general file server, protocol upgrade, or tunnel implementation. Treat the current API as experimental. From 3f0ef4644ddb51092a0580c207fc5e0f2c5de9a0 Mon Sep 17 00:00:00 2001 From: renerocksai Date: Sun, 13 Sep 2026 19:06:48 +0200 Subject: [PATCH 3/3] Recognize Windows aborts when checking admission refusal --- tests/integration.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/integration.py b/tests/integration.py index 21be0d1..353cade 100644 --- a/tests/integration.py +++ b/tests/integration.py @@ -286,7 +286,8 @@ def run_binding_suite(binary, emit, sessions): try: extra.sendall(REQUEST) expect_closed(extra) - except ConnectionResetError: + except (ConnectionResetError, ConnectionAbortedError): + # Windows can report WSAECONNABORTED for a refused accepted socket. pass for sock, reader in zip(held, readers): sock.sendall(close_request)