diff --git a/Sources/NIOCore/SocketAddresses.swift b/Sources/NIOCore/SocketAddresses.swift index 30bf3853e..18f6740f3 100644 --- a/Sources/NIOCore/SocketAddresses.swift +++ b/Sources/NIOCore/SocketAddresses.swift @@ -345,6 +345,10 @@ public enum SocketAddress: CustomStringConvertible, Sendable { /// Create a new `SocketAddress` for an IP address in string form. /// + /// Supports both IPv4 and IPv6 addresses. IPv6 addresses may include a scope ID + /// suffix (e.g., `"fe80::1%eth0"`) for link-local addresses; the scope ID will be + /// preserved in the resulting `sockaddr_in6.sin6_scope_id`. + /// /// - Parameters: /// - ipAddress: The IP address, in string form. /// - port: The target port. @@ -366,6 +370,17 @@ public enum SocketAddress: CustomStringConvertible, Sendable { // IPv6 address. } + // IPv6 addresses with scope IDs (e.g. "fe80::1%eth0") are not supported by + // inet_pton. Use getaddrinfo with AI_NUMERICHOST which handles %scope and + // properly sets sin6_scope_id. + if ipAddress.utf8.contains(UInt8(ascii: "%")) { + #if !os(Windows) && !os(WASI) + return try Self._parseScopedIPv6(ipAddress, port: port) + #else + throw SocketAddressError.failedToParseIPString(ipAddress) + #endif + } + do { var ipv6Addr = in6_addr() try NIOBSDSocket.inet_pton(addressFamily: .inet6, addressDescription: $0, address: &ipv6Addr) @@ -386,6 +401,41 @@ public enum SocketAddress: CustomStringConvertible, Sendable { } } + #if !os(Windows) && !os(WASI) + /// Parse a scoped IPv6 address (containing `%scope`) using `getaddrinfo` with `AI_NUMERICHOST`. + private static func _parseScopedIPv6(_ ipAddress: String, port: Int) throws -> SocketAddress { + // Reject empty scope (e.g. "fe80::1%") before calling getaddrinfo, because + // some platforms (macOS) silently accept it with scope_id == 0. + guard let percentIndex = ipAddress.firstIndex(of: "%"), + ipAddress[ipAddress.index(after: percentIndex)...].isEmpty == false + else { + throw SocketAddressError.failedToParseIPString(ipAddress) + } + + var hints = addrinfo() + hints.ai_family = AF_INET6 + hints.ai_flags = AI_NUMERICHOST + var result: UnsafeMutablePointer? + let status = getaddrinfo(ipAddress, String(port), &hints, &result) + defer { if result != nil { freeaddrinfo(result) } } + guard status == 0, let addrInfo = result, let ai_addr = addrInfo.pointee.ai_addr, + ai_addr.pointee.sa_family == sa_family_t(AF_INET6) + else { + throw SocketAddressError.failedToParseIPString(ipAddress) + } + let sockaddr = ai_addr.withMemoryRebound(to: sockaddr_in6.self, capacity: 1) { $0.pointee } + + // On macOS, getaddrinfo can succeed even for nonexistent interface names, + // silently returning scope_id == 0. A valid scoped address must have a + // nonzero scope_id. + guard sockaddr.sin6_scope_id != 0 else { + throw SocketAddressError.failedToParseIPString(ipAddress) + } + + return .v6(.init(address: sockaddr, host: ipAddress)) + } + #endif + /// Create a new `SocketAddress` for an IP address in ByteBuffer form. /// /// - Parameters: diff --git a/Tests/NIOPosixTests/SocketAddressTest.swift b/Tests/NIOPosixTests/SocketAddressTest.swift index e08ebbe74..36336a1dd 100644 --- a/Tests/NIOPosixTests/SocketAddressTest.swift +++ b/Tests/NIOPosixTests/SocketAddressTest.swift @@ -157,6 +157,113 @@ class SocketAddressTest: XCTestCase { } } + func testCanCreateScopedIPv6AddressFromString() throws { + #if os(Windows) || os(WASI) + // Scoped IPv6 parsing uses getaddrinfo, not available on these platforms. + #else + let loopback: String + #if canImport(Darwin) + loopback = "lo0" + #else + loopback = "lo" + #endif + + let expectedIndex = if_nametoindex(loopback) + guard expectedIndex != 0 else { return } + + let sa = try SocketAddress(ipAddress: "fe80::1%\(loopback)", port: 443) + if case .v6(let address) = sa { + XCTAssertEqual(address.address.sin6_family, sa_family_t(NIOBSDSocket.AddressFamily.inet6.rawValue)) + XCTAssertEqual(address.address.sin6_port, in_port_t(443).bigEndian) + XCTAssertEqual(address.address.sin6_flowinfo, 0) + XCTAssertEqual(address.address.sin6_scope_id, expectedIndex) + XCTAssertEqual(address.host, "fe80::1%\(loopback)") + } else { + XCTFail("Invalid address: \(sa)") + } + #endif + } + + func testCanCreateScopedIPv6WithNumericIndex() throws { + #if os(Windows) || os(WASI) + // Scoped IPv6 parsing uses getaddrinfo, not available on these platforms. + #else + // Use the loopback interface index so the test isn't fragile on systems + // where index 1 might not exist. + let loopback: String + #if canImport(Darwin) + loopback = "lo0" + #else + loopback = "lo" + #endif + let expectedIndex = if_nametoindex(loopback) + guard expectedIndex != 0 else { return } + + // getaddrinfo accepts both interface names (%lo) and numeric indices (%1). + let sa = try SocketAddress(ipAddress: "fe80::1%\(expectedIndex)", port: 80) + if case .v6(let address) = sa { + XCTAssertEqual(address.address.sin6_flowinfo, 0) + XCTAssertEqual(address.address.sin6_scope_id, expectedIndex) + XCTAssertEqual(address.address.sin6_port, in_port_t(80).bigEndian) + } else { + XCTFail("Invalid address: \(sa)") + } + #endif + } + + func testScopedAndNonScopedIPv6AreNotEqual() throws { + #if os(Windows) || os(WASI) + #else + let loopback: String + #if canImport(Darwin) + loopback = "lo0" + #else + loopback = "lo" + #endif + guard if_nametoindex(loopback) != 0 else { return } + + let scoped = try SocketAddress(ipAddress: "fe80::1%\(loopback)", port: 80) + let nonScoped = try SocketAddress(ipAddress: "fe80::1", port: 80) + // sin6_scope_id differs, so these should not be equal. + XCTAssertNotEqual(scoped, nonScoped) + #endif + } + + func testRejectsInvalidScopedIPv6() { + #if os(Windows) || os(WASI) + #else + // Empty scope after % + XCTAssertThrowsError(try SocketAddress(ipAddress: "fe80::1%", port: 80)) { error in + switch error as? SocketAddressError { + case .some(.failedToParseIPString("fe80::1%")): + () // ok + default: + XCTFail("unexpected error: \(error)") + } + } + // Nonexistent interface name + XCTAssertThrowsError(try SocketAddress(ipAddress: "fe80::1%doesnotexist999", port: 80)) { error in + switch error as? SocketAddressError { + case .some(.failedToParseIPString("fe80::1%doesnotexist999")): + () // ok + default: + XCTFail("unexpected error: \(error)") + } + } + #endif + } + + func testCanCreateNonScopedIPv6AfterScopedIPv6Support() throws { + // Regression: ensure non-scoped IPv6 still works after adding scoped support. + let sa = try SocketAddress(ipAddress: "::1", port: 80) + if case .v6(let address) = sa { + XCTAssertEqual(address.address.sin6_scope_id, 0) + XCTAssertEqual(address.address.sin6_port, in_port_t(80).bigEndian) + } else { + XCTFail("Invalid address: \(sa)") + } + } + func testRejectsNonIPStrings() { XCTAssertThrowsError(try SocketAddress(ipAddress: "definitelynotanip", port: 800)) { error in switch error as? SocketAddressError {