From 929a03c4d1fbadb8b31bb7c6aaf0781aaa4c3499 Mon Sep 17 00:00:00 2001 From: Bhavesh Varma <151822885+radheradhe01@users.noreply.github.com> Date: Sun, 28 Jun 2026 16:49:09 +0530 Subject: [PATCH] Fix UInt32 underflow when sizing the address allocator for small subnets MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ### Problem `DefaultNetworkService.init` computes the allocatable address count as: ```swift let size = Int(subnet.upper.value - subnet.lower.value - 3) ``` `upper.value` and `lower.value` are `UInt32`, so the subtraction happens in `UInt32` **before** the widening to `Int`. For a subnet where `upper - lower < 3` (e.g. a `/31`), this underflows and traps at runtime instead of producing a negative/zero count. ### Fix Widen to `Int` before subtracting, and guard that the resulting size is positive — throwing `invalidState` for a subnet too small to allocate from, rather than trapping. ### Notes No change for normally-sized subnets; this only affects degenerate small subnets that previously crashed. --- .../Network/Server/DefaultNetworkService.swift | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/Sources/Services/Network/Server/DefaultNetworkService.swift b/Sources/Services/Network/Server/DefaultNetworkService.swift index 70d17d396..adb8534ec 100644 --- a/Sources/Services/Network/Server/DefaultNetworkService.swift +++ b/Sources/Services/Network/Server/DefaultNetworkService.swift @@ -37,7 +37,16 @@ public actor DefaultNetworkService: NetworkService { } let subnet = status.ipv4Subnet - let size = Int(subnet.upper.value - subnet.lower.value - 3) + // Widen to Int before subtracting: doing the arithmetic in UInt32 traps + // on underflow when the subnet is too small (e.g. a /31 where + // upper - lower < 3). + let size = Int(subnet.upper.value) - Int(subnet.lower.value) - 3 + guard size > 0 else { + throw ContainerizationError( + .invalidState, + message: "network \(network.id) subnet is too small to allocate addresses" + ) + } self.network = network self.log = log self.allocator = try AttachmentAllocator(lower: subnet.lower.value + 2, size: size)