//! Network address handling and validation //! //! This module provides comprehensive network address abstraction supporting //! IPv4, IPv6, Unix sockets, and custom address formats with validation, //! parsing, and comparison utilities. const std = @import("std"); const testing = std.testing; const net = std.net; const os = std.os; const posix = std.posix; const mem = std.mem; const fmt = std.fmt; const builtin = @import("builtin"); const Mutex = @import("sync").Mutex; const AtomicValue = @import("sync").AtomicValue; const Error = @import("error.zig").Error; const platform_time = @import("platform").time; /// Address family types pub const AddressFamily = enum(u8) { ipv4 = 1, ipv6 = 2, unix = 3, custom = 4, }; /// Address data types pub const AddressData = union(AddressFamily) { ipv4: Ipv4Address, ipv6: Ipv6Address, unix: UnixAddress, custom: CustomAddress, }; /// IPv4 address representation pub const Ipv4Address = struct { bytes: [4]u8, pub fn init(bytes: [4]u8) Ipv4Address { return .{ .bytes = bytes }; } pub fn fromString(str: []const u8) Error!Ipv4Address { var addr = Ipv4Address{ .bytes = undefined }; var parts: [4]u8 = undefined; var part_idx: usize = 0; var current_num: u16 = 0; for (str) |c| { if (c == '.') { if (current_num > 255 or part_idx >= 3) return Error.AddressParseError; parts[part_idx] = @intCast(current_num); part_idx += 1; current_num = 0; } else if (c >= '0' and c <= '9') { current_num = current_num * 10 + (c - '0'); if (current_num > 255) return Error.AddressParseError; } else { return Error.AddressParseError; } } if (part_idx != 3 or current_num > 255) return Error.AddressParseError; parts[3] = @intCast(current_num); addr.bytes = parts; return addr; } /// Convert to string representation. /// Returns the formatted string and its length. pub fn toStringWithLen(self: Ipv4Address) struct { buf: [15]u8, len: usize } { var buffer: [15]u8 = [_]u8{0} ** 15; const slice = fmt.bufPrint(&buffer, "{d}.{d}.{d}.{d}", .{ self.bytes[0], self.bytes[1], self.bytes[2], self.bytes[3], }) catch { // Format should never fail for IPv4 (max 15 chars: "255.255.255.255") // but if it does, return a safe fallback const fallback = "0.0.0.0"; @memcpy(buffer[0..fallback.len], fallback); return .{ .buf = buffer, .len = fallback.len }; }; return .{ .buf = buffer, .len = slice.len }; } /// Convert to string slice (caller must use the returned slice, not the buffer) pub fn toSlice(self: Ipv4Address, buffer: *[15]u8) []const u8 { return fmt.bufPrint(buffer, "{d}.{d}.{d}.{d}", .{ self.bytes[0], self.bytes[1], self.bytes[2], self.bytes[3], }) catch { // Format should never fail for IPv4 (max 15 chars: "255.255.255.255") // but if it does, return a safe fallback const fallback = "0.0.0.0"; @memcpy(buffer[0..fallback.len], fallback); return buffer[0..fallback.len]; }; } pub fn toNetIp(self: Ipv4Address) net.Ip4Addr { return net.Ip4Addr{ .raw = self.bytes }; } pub fn fromNetIp(ip: net.Ip4Addr) Ipv4Address { return Ipv4Address{ .bytes = ip.raw }; } pub fn isLocalhost(self: Ipv4Address) bool { return self.bytes[0] == 127 and self.bytes[1] == 0 and self.bytes[2] == 0 and self.bytes[3] == 1; } pub fn isPrivate(self: Ipv4Address) bool { // Check for private network ranges: // 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 return (self.bytes[0] == 10) or (self.bytes[0] == 172 and self.bytes[1] >= 16 and self.bytes[1] <= 31) or (self.bytes[0] == 192 and self.bytes[1] == 168); } pub fn isLoopback(self: Ipv4Address) bool { return self.bytes[0] == 127; } pub fn isMulticast(self: Ipv4Address) bool { return self.bytes[0] >= 224 and self.bytes[0] <= 239; } /// Convert to a 32-bit integer for use as a hash key /// Network byte order (big-endian) pub fn toU32(self: Ipv4Address) u32 { return std.mem.readInt(u32, &self.bytes, .big); } /// Create from a 32-bit integer (network byte order) pub fn fromU32(value: u32) Ipv4Address { var bytes: [4]u8 = undefined; std.mem.writeInt(u32, &bytes, value, .big); return Ipv4Address{ .bytes = bytes }; } }; /// IPv6 address representation pub const Ipv6Address = struct { bytes: [16]u8, pub fn init(bytes: [16]u8) Ipv6Address { return .{ .bytes = bytes }; } pub fn fromString(str: []const u8) Error!Ipv6Address { // Two-pass parsing for :: compression // Pass 1: parse groups into front/back arrays around :: var front: [8]u16 = [_]u16{0} ** 8; var back: [8]u16 = [_]u16{0} ** 8; var front_count: usize = 0; var back_count: usize = 0; var found_double_colon = false; var current_val: u16 = 0; var digit_count: usize = 0; var i: usize = 0; // Handle leading :: if (str.len >= 2 and str[0] == ':' and str[1] == ':') { found_double_colon = true; i = 2; } while (i < str.len) : (i += 1) { const c = str[i]; if (c == ':') { // Write current group const target = if (found_double_colon) &back else &front; const count = if (found_double_colon) &back_count else &front_count; if (count.* >= 8) return Error.AddressParseError; target[count.*] = current_val; count.* += 1; current_val = 0; digit_count = 0; if (i + 1 < str.len and str[i + 1] == ':') { if (found_double_colon) return Error.AddressParseError; // only one :: allowed found_double_colon = true; i += 1; // skip second colon } } else { const digit: u16 = switch (c) { '0'...'9' => c - '0', 'a'...'f' => c - 'a' + 10, 'A'...'F' => c - 'A' + 10, else => return Error.AddressParseError, }; current_val = (current_val << 4) | digit; digit_count += 1; if (digit_count > 4) return Error.AddressParseError; } } // Write final group if (digit_count > 0) { const target = if (found_double_colon) &back else &front; const count = if (found_double_colon) &back_count else &front_count; if (count.* >= 8) return Error.AddressParseError; target[count.*] = current_val; count.* += 1; } // Assemble: front groups + zero padding + back groups const total = front_count + back_count; if (found_double_colon) { if (total > 8) return Error.AddressParseError; } else { if (total != 8) return Error.AddressParseError; } var addr = Ipv6Address{ .bytes = [_]u8{0} ** 16 }; for (front[0..front_count], 0..) |val, g| { addr.bytes[g * 2] = @intCast(val >> 8); addr.bytes[g * 2 + 1] = @intCast(val & 0xFF); } const back_start = 8 - back_count; for (back[0..back_count], 0..) |val, g| { const idx = back_start + g; addr.bytes[idx * 2] = @intCast(val >> 8); addr.bytes[idx * 2 + 1] = @intCast(val & 0xFF); } return addr; } /// Convert to proper IPv6 colon notation string with length pub fn toStringWithLen(self: Ipv6Address) struct { buf: [39]u8, len: usize } { var buffer: [39]u8 = [_]u8{0} ** 39; // Format as proper IPv6 colon notation: xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx const slice = fmt.bufPrint(&buffer, "{x:0>4}:{x:0>4}:{x:0>4}:{x:0>4}:{x:0>4}:{x:0>4}:{x:0>4}:{x:0>4}", .{ (@as(u16, self.bytes[0]) << 8) | self.bytes[1], (@as(u16, self.bytes[2]) << 8) | self.bytes[3], (@as(u16, self.bytes[4]) << 8) | self.bytes[5], (@as(u16, self.bytes[6]) << 8) | self.bytes[7], (@as(u16, self.bytes[8]) << 8) | self.bytes[9], (@as(u16, self.bytes[10]) << 8) | self.bytes[11], (@as(u16, self.bytes[12]) << 8) | self.bytes[13], (@as(u16, self.bytes[14]) << 8) | self.bytes[15], }) catch { // Format should never fail for IPv6 (max 39 chars) // but if it does, return a safe fallback const fallback = "0000:0000:0000:0000:0000:0000:0000:0000"; @memcpy(buffer[0..fallback.len], fallback); return .{ .buf = buffer, .len = fallback.len }; }; return .{ .buf = buffer, .len = slice.len }; } /// Convert to string slice pub fn toSlice(self: Ipv6Address, buffer: *[39]u8) []const u8 { return fmt.bufPrint(buffer, "{x:0>4}:{x:0>4}:{x:0>4}:{x:0>4}:{x:0>4}:{x:0>4}:{x:0>4}:{x:0>4}", .{ (@as(u16, self.bytes[0]) << 8) | self.bytes[1], (@as(u16, self.bytes[2]) << 8) | self.bytes[3], (@as(u16, self.bytes[4]) << 8) | self.bytes[5], (@as(u16, self.bytes[6]) << 8) | self.bytes[7], (@as(u16, self.bytes[8]) << 8) | self.bytes[9], (@as(u16, self.bytes[10]) << 8) | self.bytes[11], (@as(u16, self.bytes[12]) << 8) | self.bytes[13], (@as(u16, self.bytes[14]) << 8) | self.bytes[15], }) catch { // Format should never fail for IPv6 (max 39 chars) // but if it does, return a safe fallback const fallback = "0000:0000:0000:0000:0000:0000:0000:0000"; @memcpy(buffer[0..fallback.len], fallback); return buffer[0..fallback.len]; }; } pub fn toNetIp(self: Ipv6Address) net.Ip6Addr { return net.Ip6Addr{ .raw = self.bytes }; } pub fn fromNetIp(ip: net.Ip6Addr) Ipv6Address { return Ipv6Address{ .bytes = ip.raw }; } pub fn isLoopback(self: Ipv6Address) bool { // ::1/128 const zeros: [15]u8 = .{0} ** 15; return mem.eql(u8, self.bytes[0..15], &zeros) and self.bytes[15] == 1; } pub fn isMulticast(self: Ipv6Address) bool { return self.bytes[0] == 0xff; } pub fn isLinkLocal(self: Ipv6Address) bool { return self.bytes[0] == 0xfe and (self.bytes[1] & 0xc0) == 0x80; } pub fn isUniqueLocal(self: Ipv6Address) bool { return (self.bytes[0] & 0xfe) == 0xfc; } }; /// Unix socket address representation pub const UnixAddress = struct { path: [108]u8, path_len: usize, pub fn init(path_str: []const u8) UnixAddress { var result = UnixAddress{ .path = [_]u8{0} ** 108, .path_len = 0 }; const len = @min(path_str.len, 107); @memcpy(result.path[0..len], path_str[0..len]); result.path_len = len; return result; } pub fn fromString(str: []const u8) Error!UnixAddress { // Unix socket paths - just store the path bytes if (str.len > 107) return Error.InvalidAddressFormat; var path: [108]u8 = [_]u8{0} ** 108; @memcpy(path[0..str.len], str); return UnixAddress{ .path = path, .path_len = str.len }; } pub fn toString(self: *const UnixAddress) []const u8 { return self.path[0..self.path_len]; } pub fn isAbsolute(self: UnixAddress) bool { return self.path_len > 0 and self.path[0] == '/'; } }; /// Custom address format for extensibility pub const CustomAddress = struct { id: u32, data: []const u8, pub fn init(id: u32, data: []const u8) CustomAddress { return .{ .id = id, .data = data }; } pub fn format(self: CustomAddress, allocator: mem.Allocator) ![]const u8 { return fmt.allocPrint(allocator, "CustomAddress(id={d}, data=0x{x})", .{ self.id, self.data, }); } }; /// Main address structure pub const Address = struct { family: AddressFamily, data: AddressData, port: u16, // Port is 0 for Unix sockets and custom addresses pub fn init() Address { return .{ .family = .ipv4, .data = .{ .ipv4 = Ipv4Address{ .bytes = .{0, 0, 0, 0} } }, .port = 0, }; } pub fn ipv4(bytes: [4]u8, port: u16) Address { return .{ .family = .ipv4, .data = .{ .ipv4 = Ipv4Address.init(bytes) }, .port = port, }; } pub fn ipv6(bytes: [16]u8, port: u16) Address { return .{ .family = .ipv6, .data = .{ .ipv6 = Ipv6Address.init(bytes) }, .port = port, }; } pub fn unix(path: [:0]const u8) Address { return .{ .family = .unix, .data = .{ .unix = UnixAddress.init(path) }, .port = 0, }; } pub fn custom(id: u32, data: []const u8) Address { return .{ .family = .custom, .data = .{ .custom = CustomAddress.init(id, data) }, .port = 0, }; } /// Parse address from string (supports IPv4:port, IPv6:port, and unix paths) pub fn parse(str: []const u8) Error!Address { // Check if it's a Unix socket path if (str.len > 0 and str[0] == '/') { const unix_addr = try UnixAddress.fromString(str); return .{ .family = .unix, .data = .{ .unix = unix_addr }, .port = 0, }; } // Try to parse IPv6 with port (format: [ipv6]:port) if (str.len > 0 and str[0] == '[') { const end_bracket = mem.indexOf(u8, str, "]"); if (end_bracket) |bracket| { const ip_part = str[1..bracket]; const port_part = str[bracket + 1 ..]; if (port_part.len > 0 and port_part[0] == ':') { const port_str = port_part[1..]; const port = fmt.parseInt(u16, port_str, 10) catch return Error.InvalidPort; const ipv6_addr = try Ipv6Address.fromString(ip_part); return .{ .family = .ipv6, .data = .{ .ipv6 = ipv6_addr }, .port = port, }; } } } // Count colons to distinguish IPv4:port (1 colon) from IPv6 (multiple colons) var colon_count: usize = 0; for (str) |c| { if (c == ':') colon_count += 1; } // IPv6 without port has multiple colons (at least 2) if (colon_count >= 2) { const ipv6_addr = try Ipv6Address.fromString(str); return .{ .family = .ipv6, .data = .{ .ipv6 = ipv6_addr }, .port = 0, }; } // IPv4 with port has exactly 1 colon if (colon_count == 1) { const colon_idx = mem.indexOf(u8, str, ":").?; const ip_part = str[0..colon_idx]; const port_str = str[colon_idx + 1 ..]; const port = fmt.parseInt(u16, port_str, 10) catch return Error.InvalidPort; const ipv4_addr = try Ipv4Address.fromString(ip_part); return .{ .family = .ipv4, .data = .{ .ipv4 = ipv4_addr }, .port = port, }; } // No colons - try to parse IPv4 without port const ipv4_addr = try Ipv4Address.fromString(str); return .{ .family = .ipv4, .data = .{ .ipv4 = ipv4_addr }, .port = 0, }; } /// Convert address to string representation pub fn toString(self: Address, allocator: mem.Allocator) Error![]const u8 { switch (self.family) { .ipv4 => { const ipv4_addr = self.data.ipv4; const ip_result = ipv4_addr.toStringWithLen(); return fmt.allocPrint(allocator, "{s}:{d}", .{ ip_result.buf[0..ip_result.len], self.port }) catch return Error.OutOfMemory; }, .ipv6 => { const ipv6_addr = self.data.ipv6; const ip_result = ipv6_addr.toStringWithLen(); return fmt.allocPrint(allocator, "[{s}]:{d}", .{ ip_result.buf[0..ip_result.len], self.port }) catch return Error.OutOfMemory; }, .unix => { const unix_addr = self.data.unix; return fmt.allocPrint(allocator, "{s}", .{unix_addr.toString()}) catch return Error.OutOfMemory; }, .custom => { const custom_addr = self.data.custom; return custom_addr.format(allocator); }, } } /// Convert address to string using a fixed buffer (no allocation) pub fn toStringBuf(self: Address, buf: *[128]u8) []const u8 { switch (self.family) { .ipv4 => { const ipv4_addr = self.data.ipv4; const ip_result = ipv4_addr.toStringWithLen(); return fmt.bufPrint(buf, "{s}:{d}", .{ ip_result.buf[0..ip_result.len], self.port }) catch "invalid"; }, .ipv6 => { const ipv6_addr = self.data.ipv6; const ip_result = ipv6_addr.toStringWithLen(); return fmt.bufPrint(buf, "[{s}]:{d}", .{ ip_result.buf[0..ip_result.len], self.port }) catch "invalid"; }, .unix => { const unix_addr = self.data.unix; return fmt.bufPrint(buf, "{s}", .{unix_addr.toString()}) catch "invalid"; }, .custom => { return fmt.bufPrint(buf, "custom:{d}", .{self.data.custom.id}) catch "invalid"; }, } } /// Check if address is valid for network operations pub fn isValid(self: Address) bool { switch (self.family) { .ipv4 => { const ipv4_addr = self.data.ipv4; // IPv4 addresses with certain invalid patterns return !ipv4_addr.isMulticast() or self.port != 0; }, .ipv6 => { const ipv6_addr = self.data.ipv6; // IPv6 addresses with certain invalid patterns return !ipv6_addr.isMulticast() or self.port != 0; }, .unix => { const unix_addr = self.data.unix; // Unix socket paths are typically limited to 104-108 bytes return unix_addr.path_len > 0 and unix_addr.path_len < 108; }, .custom => { const custom_addr = self.data.custom; return custom_addr.data.len > 0; }, } } /// Check if addresses are equal pub fn equals(self: Address, other: Address) bool { if (self.family != other.family) return false; if (self.port != other.port) return false; switch (self.family) { .ipv4 => { return mem.eql(u8, &self.data.ipv4.bytes, &other.data.ipv4.bytes); }, .ipv6 => { return mem.eql(u8, &self.data.ipv6.bytes, &other.data.ipv6.bytes); }, .unix => { return mem.eql(u8, &self.data.unix.path, &other.data.unix.path); }, .custom => { return self.data.custom.id == other.data.custom.id and mem.eql(u8, self.data.custom.data, other.data.custom.data); }, } } /// MED-3 FIX: Convert IP address to u128 for use as hashmap key /// IPv4 addresses are zero-extended to 128 bits /// Unix and custom addresses return 0 (not suitable for IP-based rate limiting) pub fn toU128(self: Address) u128 { switch (self.family) { .ipv4 => { // Pack IPv4 into lower 32 bits const b = self.data.ipv4.bytes; return @as(u128, b[0]) << 24 | @as(u128, b[1]) << 16 | @as(u128, b[2]) << 8 | @as(u128, b[3]); }, .ipv6 => { // Pack all 16 bytes into u128 const b = self.data.ipv6.bytes; var result: u128 = 0; inline for (0..16) |i| { result = (result << 8) | @as(u128, b[i]); } return result; }, .unix, .custom => { // Non-IP addresses not suitable for IP rate limiting return 0; }, } } /// Compare addresses (useful for sorting) pub fn compare(self: Address, other: Address) i32 { if (self.family != other.family) { return @as(i32, @intFromEnum(self.family)) - @as(i32, @intFromEnum(other.family)); } switch (self.family) { .ipv4 => { for (0..4) |i| { if (self.data.ipv4.bytes[i] != other.data.ipv4.bytes[i]) { return @as(i32, self.data.ipv4.bytes[i]) - @as(i32, other.data.ipv4.bytes[i]); } } }, .ipv6 => { for (0..16) |i| { if (self.data.ipv6.bytes[i] != other.data.ipv6.bytes[i]) { return @as(i32, self.data.ipv6.bytes[i]) - @as(i32, other.data.ipv6.bytes[i]); } } }, .unix => { const cmp = mem.order(u8, &self.data.unix.path, &other.data.unix.path); if (cmp != .eq) return if (cmp == .lt) @as(i32, -1) else @as(i32, 1); }, .custom => { if (self.data.custom.id != other.data.custom.id) { return if (self.data.custom.id < other.data.custom.id) @as(i32, -1) else @as(i32, 1); } const cmp = mem.order(u8, self.data.custom.data, other.data.custom.data); if (cmp != .eq) return if (cmp == .lt) @as(i32, -1) else @as(i32, 1); }, } if (self.port != other.port) { return @as(i32, self.port) - @as(i32, other.port); } return 0; } /// Check if address is loopback pub fn isLoopback(self: Address) bool { switch (self.family) { .ipv4 => return self.data.ipv4.isLoopback(), .ipv6 => return self.data.ipv6.isLoopback(), .unix => return false, // Unix sockets don't have loopback concept .custom => return false, } } /// Check if address is private/local pub fn isPrivate(self: Address) bool { switch (self.family) { .ipv4 => return self.data.ipv4.isPrivate(), .ipv6 => return self.data.ipv6.isUniqueLocal(), .unix => return !self.data.unix.isAbsolute(), .custom => return false, } } /// Get raw address bytes for socket operations pub fn getRawBytes(self: Address) Error![]const u8 { return switch (self.family) { .ipv4 => &self.data.ipv4.bytes, .ipv6 => &self.data.ipv6.bytes, .unix => self.data.unix.path[0..self.data.unix.path_len], .custom => self.data.custom.data, }; } /// Get address family constant for socket operations pub fn getSocketFamily(self: Address) u16 { return switch (self.family) { .ipv4 => posix.AF.INET, .ipv6 => posix.AF.INET6, .unix => posix.AF.UNIX, .custom => 0, }; } /// Convert to posix socket address storage /// Returns a storage struct large enough to hold any address type pub fn toSockAddr(self: Address) Error!posix.sockaddr.storage { var result: posix.sockaddr.storage = undefined; @memset(mem.asBytes(&result), 0); switch (self.family) { .ipv4 => { const addr_in: *posix.sockaddr.in = @ptrCast(@alignCast(&result)); addr_in.* = .{ .family = posix.AF.INET, .port = mem.nativeToBig(u16, self.port), .addr = mem.bytesToValue(u32, &self.data.ipv4.bytes), }; }, .ipv6 => { const addr_in6: *posix.sockaddr.in6 = @ptrCast(@alignCast(&result)); addr_in6.* = .{ .family = posix.AF.INET6, .port = mem.nativeToBig(u16, self.port), .flowinfo = 0, .addr = self.data.ipv6.bytes, .scope_id = 0, }; }, .unix => { const addr_un: *posix.sockaddr.un = @ptrCast(@alignCast(&result)); addr_un.* = .{ .family = posix.AF.UNIX, .path = undefined }; const path = self.data.unix.path[0..self.data.unix.path_len]; @memcpy(addr_un.path[0..path.len], path); if (path.len < addr_un.path.len) { addr_un.path[path.len] = 0; } }, .custom => return Error.OperationNotSupported, } return result; } /// Create Address from posix socket address storage pub fn fromSockAddr(sock_addr: posix.sockaddr.storage) Error!Address { switch (sock_addr.family) { posix.AF.INET => { const addr_in: *const posix.sockaddr.in = @ptrCast(@alignCast(&sock_addr)); var ipv4_bytes: [4]u8 = undefined; @memcpy(&ipv4_bytes, mem.asBytes(&addr_in.addr)); return Address{ .family = .ipv4, .data = .{ .ipv4 = .{ .bytes = ipv4_bytes } }, .port = mem.bigToNative(u16, addr_in.port), }; }, posix.AF.INET6 => { const addr_in6: *const posix.sockaddr.in6 = @ptrCast(@alignCast(&sock_addr)); return Address{ .family = .ipv6, .data = .{ .ipv6 = .{ .bytes = addr_in6.addr } }, .port = mem.bigToNative(u16, addr_in6.port), }; }, posix.AF.UNIX => { const addr_un: *const posix.sockaddr.un = @ptrCast(@alignCast(&sock_addr)); var unix_addr = UnixAddress{ .path = undefined, .path_len = 0 }; for (addr_un.path, 0..) |c, i| { if (c == 0) { unix_addr.path_len = i; break; } unix_addr.path[i] = c; } return Address{ .family = .unix, .data = .{ .unix = unix_addr }, .port = 0, }; }, else => return Error.InvalidAddressFormat, } } }; /// Address list for managing multiple addresses pub const AddressList = struct { addresses: std.ArrayList(Address), allocator: mem.Allocator, pub fn init(allocator: mem.Allocator) AddressList { return .{ .addresses = .{}, .allocator = allocator, }; } pub fn deinit(self: *AddressList) void { self.addresses.deinit(self.allocator); } pub fn add(self: *AddressList, addr: Address) Error!void { self.addresses.append(self.allocator, addr) catch return Error.AddressError; } pub fn addMany(self: *AddressList, addrs: []const Address) Error!void { self.addresses.appendSlice(self.allocator, addrs) catch return Error.AddressError; } pub fn remove(self: *AddressList, addr: Address) void { for (self.addresses.items, 0..) |item, i| { if (item.equals(addr)) { _ = self.addresses.orderedRemove(i); break; } } } pub fn get(self: *const AddressList, index: usize) ?Address { if (index < self.addresses.items.len) { return self.addresses.items[index]; } return null; } pub fn len(self: *const AddressList) usize { return self.addresses.items.len; } pub fn clear(self: *AddressList) void { self.addresses.clearRetainingCapacity(); } pub fn find(self: *const AddressList, addr: Address) ?usize { for (self.addresses.items, 0..) |item, i| { if (item.equals(addr)) { return i; } } return null; } pub fn contains(self: *const AddressList, addr: Address) bool { return self.find(addr) != null; } pub fn sort(self: *AddressList) void { mem.sort(Address, self.addresses.items, {}, struct { fn lessThan(_: void, a: Address, b: Address) bool { return a.compare(b) < 0; } }.lessThan); } }; /// SECURITY: Maximum DNS results to prevent DNS amplification attacks /// This prevents unbounded memory growth from malicious DNS responses pub const MAX_DNS_RESULTS: usize = 100; /// SECURITY: Maximum total memory for DNS cache (10 MB) pub const MAX_DNS_CACHE_MEMORY: usize = 10 * 1024 * 1024; /// DNS rate limiting per host pub const DnsRateLimit = struct { last_lookup: std.AutoHashMap(u64, i64), mutex: Mutex, allocator: mem.Allocator, min_interval_ms: i64, pub fn init(allocator: mem.Allocator, min_interval_ms: i64) DnsRateLimit { return .{ .last_lookup = std.AutoHashMap(u64, i64).init(allocator), .mutex = .{}, .allocator = allocator, .min_interval_ms = min_interval_ms, }; } pub fn deinit(self: *DnsRateLimit) void { self.last_lookup.deinit(); } /// Check if lookup is allowed for this hostname (returns true if allowed) pub fn checkRateLimit(self: *DnsRateLimit, hostname: []const u8) bool { // Hash the hostname to use as a key var hasher = std.hash.Wyhash.init(0); hasher.update(hostname); const hash = hasher.final(); self.mutex.lock(); defer self.mutex.unlock(); const now = platform_time.milliTimestamp(); if (self.last_lookup.get(hash)) |last_time| { // Check if enough time has passed since last lookup if (now - last_time < self.min_interval_ms) { return false; // Rate limit exceeded } } // Update last lookup time self.last_lookup.put(hash, now) catch { // If we can't update, allow the lookup but log warning std.log.warn("Failed to update DNS rate limit for host hash {}", .{hash}); }; return true; } }; /// Address resolution utilities pub const AddressResolver = struct { allocator: mem.Allocator, /// SECURITY: Rate limiter to prevent DNS amplification attacks rate_limiter: DnsRateLimit, /// SECURITY: Track total cache memory usage cache_memory_used: AtomicValue(usize), pub fn init(allocator: mem.Allocator) AddressResolver { return .{ .allocator = allocator, .rate_limiter = DnsRateLimit.init(allocator, 1000), // 1 second minimum between lookups .cache_memory_used = AtomicValue(usize).init(0), }; } pub fn deinit(self: *AddressResolver) void { self.rate_limiter.deinit(); } /// SECURITY FIX Issue 2: Resolve hostname to addresses with rate limiting and bounds checking pub fn resolve(self: *AddressResolver, hostname: []const u8) Error!AddressList { // SECURITY: Rate limit DNS lookups per hostname if (!self.rate_limiter.checkRateLimit(hostname)) { std.log.warn("DNS rate limit exceeded for hostname: {s}", .{hostname}); return Error.ResourceExhausted; } var list = AddressList.init(self.allocator); errdefer list.deinit(); // Fast path: try to parse as an IP address first if (Ipv4Address.fromString(hostname)) |ipv4_addr| { const addr = Address{ .family = .ipv4, .data = .{ .ipv4 = ipv4_addr }, .port = 0, }; try list.add(addr); return list; } else |_| {} // Try IPv6 literal if (Ipv6Address.fromString(hostname)) |ipv6_addr| { const addr = Address{ .family = .ipv6, .data = .{ .ipv6 = ipv6_addr }, .port = 0, }; try list.add(addr); return list; } else |_| {} // DNS resolution using std.net.getAddressList const net_addrs = net.getAddressList(self.allocator, hostname, 0) catch |err| { std.log.warn("DNS resolution failed for {s}: {}", .{ hostname, err }); return Error.AddressParseError; }; defer net_addrs.deinit(); // Iterate through results with SECURITY limits var count: usize = 0; for (net_addrs.addrs) |net_addr| { // SECURITY: Limit results to prevent amplification if (count >= MAX_DNS_RESULTS) { std.log.warn("DNS resolution truncated at {} results for {s}", .{ MAX_DNS_RESULTS, hostname }); break; } const addr: Address = switch (net_addr.any.family) { posix.AF.INET => blk: { // net.Ip4Address has sa field which is posix.sockaddr.in const ip_bytes = @as(*const [4]u8, @ptrCast(&net_addr.in.sa.addr)); break :blk Address{ .family = .ipv4, .data = .{ .ipv4 = Ipv4Address.init(ip_bytes.*) }, .port = 0, }; }, posix.AF.INET6 => blk: { // net.Ip6Address has sa field which is posix.sockaddr.in6 break :blk Address{ .family = .ipv6, .data = .{ .ipv6 = Ipv6Address.init(net_addr.in6.sa.addr) }, .port = 0, }; }, else => continue, // Skip unsupported address families }; list.add(addr) catch |err| { std.log.warn("Failed to add DNS result: {}", .{err}); continue; }; count += 1; } if (count == 0) { std.log.warn("DNS resolution returned no usable addresses for {s}", .{hostname}); return Error.AddressNotFound; } // SECURITY: Track memory usage for cache limits const memory_per_result = @sizeOf(Address); _ = self.cache_memory_used.fetchAdd(count * memory_per_result, .monotonic); return list; } /// Resolve service (port) for address pub fn resolveService(_: *AddressResolver, service: []const u8) Error!u16 { return fmt.parseInt(u16, service, 10) catch return Error.InvalidPort; } }; // Testing utilities test "ipv4 address parsing and operations" { const addr_str = "192.168.1.100"; const addr = try Ipv4Address.fromString(addr_str); try testing.expect(addr.bytes[0] == 192); try testing.expect(addr.bytes[1] == 168); try testing.expect(addr.bytes[2] == 1); try testing.expect(addr.bytes[3] == 100); const str_result = addr.toStringWithLen(); try testing.expectEqualSlices(u8, "192.168.1.100", str_result.buf[0..str_result.len]); try testing.expect(!addr.isLocalhost()); try testing.expect(addr.isPrivate()); try testing.expect(!addr.isLoopback()); try testing.expect(!addr.isMulticast()); } test "ipv6 address operations" { var bytes: [16]u8 = undefined; bytes[0..15].* = [1]u8{0} ** 15; bytes[15] = 1; // ::1 (loopback) const addr = Ipv6Address.init(bytes); try testing.expect(addr.isLoopback()); // Reset for multicast test bytes[0] = 0xff; bytes[1] = 0x02; const mcast_addr = Ipv6Address.init(bytes); try testing.expect(mcast_addr.isMulticast()); // Reset for link-local test bytes[0] = 0xfe; bytes[1] = 0x80; const link_local = Ipv6Address.init(bytes); try testing.expect(link_local.isLinkLocal()); } test "unix socket address" { const path = "/tmp/test.sock"; const addr = try UnixAddress.fromString(path); try testing.expectEqualSlices(u8, path, addr.toString()); try testing.expect(addr.isAbsolute()); } test "address parsing" { // Test IPv4 with port const ipv4_str = "192.168.1.100:8080"; const addr = try Address.parse(ipv4_str); try testing.expect(addr.family == .ipv4); try testing.expectEqual(@as(u16, 8080), addr.port); try testing.expect(mem.eql(u8, &addr.data.ipv4.bytes, &.{192, 168, 1, 100})); // Test IPv6 with port const ipv6_str = "[2001:db8::1]:8080"; const ipv6_addr = try Address.parse(ipv6_str); try testing.expect(ipv6_addr.family == .ipv6); try testing.expectEqual(@as(u16, 8080), ipv6_addr.port); // Test Unix socket const unix_str = "/tmp/test.sock"; const unix_addr = try Address.parse(unix_str); try testing.expect(unix_addr.family == .unix); try testing.expectEqual(@as(u16, 0), unix_addr.port); } test "address validation and comparison" { const addr1 = try Address.parse("192.168.1.100:8080"); const addr2 = try Address.parse("192.168.1.100:8080"); const addr3 = try Address.parse("192.168.1.100:9090"); try testing.expect(addr1.isValid()); try testing.expect(addr1.equals(addr2)); try testing.expect(!addr1.equals(addr3)); const cmp = addr1.compare(addr2); try testing.expectEqual(@as(i32, 0), cmp); const cmp2 = addr1.compare(addr3); try testing.expect(cmp2 < 0); // port 8080 < 9090 } test "address list operations" { var list = AddressList.init(testing.allocator); defer list.deinit(); const addr1 = try Address.parse("192.168.1.100:8080"); const addr2 = try Address.parse("192.168.1.101:8080"); try list.add(addr1); try list.add(addr2); try testing.expectEqual(@as(usize, 2), list.len()); try testing.expect(list.contains(addr1)); try testing.expect(list.contains(addr2)); list.remove(addr1); try testing.expectEqual(@as(usize, 1), list.len()); try testing.expect(!list.contains(addr1)); } test "address resolver" { var resolver = AddressResolver.init(testing.allocator); defer resolver.deinit(); // Test service resolution const port = try resolver.resolveService("8080"); try testing.expectEqual(@as(u16, 8080), port); // Note: hostname resolution might not work in test environment // so we skip that test for now } test "address system conversion" { const addr = try Address.parse("192.168.1.100:8080"); const sock_addr = try addr.toSockAddr(); try testing.expectEqual(posix.AF.INET, sock_addr.family); const back_to_addr = try Address.fromSockAddr(sock_addr); try testing.expect(back_to_addr.equals(addr)); } test "AddressList.add error handling" { var list = AddressList.init(testing.allocator); defer list.deinit(); const addr = try Address.parse("192.168.1.100:8080"); // Should succeed with proper allocator try list.add(addr); try testing.expectEqual(@as(usize, 1), list.len()); try testing.expect(list.contains(addr)); } test "AddressList.addMany error handling" { var list = AddressList.init(testing.allocator); defer list.deinit(); const addrs = [_]Address{ try Address.parse("192.168.1.100:8080"), try Address.parse("192.168.1.101:8080"), try Address.parse("192.168.1.102:8080"), }; // Should succeed with proper allocator try list.addMany(&addrs); try testing.expectEqual(@as(usize, 3), list.len()); for (addrs) |addr| { try testing.expect(list.contains(addr)); } } test "Ipv4Address.isMulticast" { const multicast = Ipv4Address.init([_]u8{ 224, 0, 0, 1 }); try testing.expect(multicast.isMulticast()); const not_multicast = Ipv4Address.init([_]u8{ 192, 168, 1, 1 }); try testing.expect(!not_multicast.isMulticast()); } test "Ipv4Address.toU32 and fromU32" { const addr = Ipv4Address.init([_]u8{ 192, 168, 1, 1 }); const as_u32 = addr.toU32(); const restored = Ipv4Address.fromU32(as_u32); try testing.expect(std.mem.eql(u8, &addr.bytes, &restored.bytes)); } test "Ipv6Address.isMulticast" { const multicast = Ipv6Address.init([_]u8{ 0xff, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }); try testing.expect(multicast.isMulticast()); const not_multicast = Ipv6Address.init([_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }); try testing.expect(!not_multicast.isMulticast()); } test "Ipv6Address.isLinkLocal" { const link_local = Ipv6Address.init([_]u8{ 0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }); try testing.expect(link_local.isLinkLocal()); const not_link_local = Ipv6Address.init([_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }); try testing.expect(!not_link_local.isLinkLocal()); } test "Ipv6Address.isUniqueLocal" { const unique_local = Ipv6Address.init([_]u8{ 0xfc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }); try testing.expect(unique_local.isUniqueLocal()); const not_unique_local = Ipv6Address.init([_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }); try testing.expect(!not_unique_local.isUniqueLocal()); } test "UnixAddress.isAbsolute" { const absolute = UnixAddress.init("/var/run/test.sock"); try testing.expect(absolute.isAbsolute()); const relative = UnixAddress.init("relative.sock"); try testing.expect(!relative.isAbsolute()); } test "Address.isLoopback" { const loopback4 = Address.ipv4([_]u8{ 127, 0, 0, 1 }, 8080); try testing.expect(loopback4.isLoopback()); const not_loopback = Address.ipv4([_]u8{ 192, 168, 1, 1 }, 8080); try testing.expect(!not_loopback.isLoopback()); } test "Address.isPrivate" { const private1 = Address.ipv4([_]u8{ 10, 0, 0, 1 }, 8080); try testing.expect(private1.isPrivate()); const private2 = Address.ipv4([_]u8{ 172, 16, 0, 1 }, 8080); try testing.expect(private2.isPrivate()); const private3 = Address.ipv4([_]u8{ 192, 168, 1, 1 }, 8080); try testing.expect(private3.isPrivate()); const public_addr = Address.ipv4([_]u8{ 8, 8, 8, 8 }, 8080); try testing.expect(!public_addr.isPrivate()); } test "Address.compare" { const addr1 = Address.ipv4([_]u8{ 192, 168, 1, 1 }, 8080); const addr2 = Address.ipv4([_]u8{ 192, 168, 1, 2 }, 8080); const addr3 = Address.ipv4([_]u8{ 192, 168, 1, 1 }, 8080); try testing.expect(addr1.compare(addr2) < 0); try testing.expect(addr2.compare(addr1) > 0); try testing.expectEqual(@as(i32, 0), addr1.compare(addr3)); } test "Address.getSocketFamily" { const ipv4_addr = Address.ipv4([_]u8{ 192, 168, 1, 1 }, 8080); try testing.expectEqual(@as(u16, posix.AF.INET), ipv4_addr.getSocketFamily()); const ipv6_addr = Address.ipv6([_]u8{0} ** 16, 8080); // IPv6 family differs between platforms, just verify it's different from IPv4 try testing.expect(ipv6_addr.getSocketFamily() != ipv4_addr.getSocketFamily()); } test "AddressList.find and get" { var list = AddressList.init(testing.allocator); defer list.deinit(); const addr1 = try Address.parse("192.168.1.1:8080"); const addr2 = try Address.parse("192.168.1.2:8080"); try list.add(addr1); try list.add(addr2); try testing.expectEqual(@as(?usize, 0), list.find(addr1)); try testing.expectEqual(@as(?usize, 1), list.find(addr2)); const got = list.get(0); try testing.expect(got != null); try testing.expect(got.?.equals(addr1)); try testing.expect(list.get(100) == null); } test "AddressList.remove" { var list = AddressList.init(testing.allocator); defer list.deinit(); const addr1 = try Address.parse("192.168.1.1:8080"); const addr2 = try Address.parse("192.168.1.2:8080"); try list.add(addr1); try list.add(addr2); try testing.expectEqual(@as(usize, 2), list.len()); list.remove(addr1); try testing.expectEqual(@as(usize, 1), list.len()); try testing.expect(!list.contains(addr1)); try testing.expect(list.contains(addr2)); } test "AddressList.sort" { var list = AddressList.init(testing.allocator); defer list.deinit(); const addr3 = try Address.parse("192.168.1.3:8080"); const addr1 = try Address.parse("192.168.1.1:8080"); const addr2 = try Address.parse("192.168.1.2:8080"); try list.add(addr3); try list.add(addr1); try list.add(addr2); list.sort(); const first = list.get(0); try testing.expect(first != null); try testing.expect(first.?.equals(addr1)); } test "AddressList.clear" { var list = AddressList.init(testing.allocator); defer list.deinit(); try list.add(try Address.parse("192.168.1.1:8080")); try list.add(try Address.parse("192.168.1.2:8080")); try testing.expectEqual(@as(usize, 2), list.len()); list.clear(); try testing.expectEqual(@as(usize, 0), list.len()); } test "Ipv6Address.toStringWithLen" { const ipv6 = Ipv6Address.init([_]u8{ 0x20, 0x01, 0x0d, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 }); const result = ipv6.toStringWithLen(); try testing.expect(result.len > 0); try testing.expect(result.len <= 39); } test "Ipv6Address.fromString uppercase hex" { // Test uppercase hex parsing (A-F in address) const result = try Ipv6Address.fromString("2001:0DB8:0000:0000:0000:0000:0000:0001"); try testing.expectEqual(@as(u8, 0x20), result.bytes[0]); try testing.expectEqual(@as(u8, 0x01), result.bytes[1]); } test "Address.toString ipv4" { const addr = try Address.parse("192.168.1.1:8080"); const formatted = try addr.toString(testing.allocator); defer testing.allocator.free(formatted); try testing.expect(formatted.len > 0); } test "Address.toStringBuf ipv4" { const addr = try Address.parse("192.168.1.1:8080"); var buf: [128]u8 = undefined; const result = addr.toStringBuf(&buf); try testing.expect(result.len > 0); } test "Address.isValid ipv4" { const valid_addr = try Address.parse("192.168.1.1:8080"); try testing.expect(valid_addr.isValid()); // init() returns 0.0.0.0:0 which is valid (not multicast or 0) const zero_addr = Address.init(); try testing.expect(zero_addr.isValid()); } test "Ipv4Address.toStringWithLen max values" { // Test with max byte values const ip = Ipv4Address.init([_]u8{ 255, 255, 255, 255 }); const result = ip.toStringWithLen(); try testing.expect(result.len == 15); // "255.255.255.255" } test "Address.port access" { const addr = try Address.parse("192.168.1.1:9999"); try testing.expectEqual(@as(u16, 9999), addr.port); } test "Ipv6Address all zeros" { const addr = Ipv6Address.init([_]u8{0} ** 16); try testing.expectEqual(@as(u8, 0), addr.bytes[0]); // All zeros is not multicast, not link-local, not unique-local try testing.expect(!addr.isMulticast()); try testing.expect(!addr.isLinkLocal()); try testing.expect(!addr.isUniqueLocal()); } test "Address family detection" { const ipv4_addr = try Address.parse("127.0.0.1:80"); try testing.expectEqual(@as(u16, posix.AF.INET), ipv4_addr.getSocketFamily()); // init() returns ipv4 family, so family is INET not UNSPEC const zero_addr = Address.init(); try testing.expectEqual(@as(u16, posix.AF.INET), zero_addr.getSocketFamily()); } test "Address.toU128 ipv4" { const addr = try Address.parse("192.168.1.1:8080"); const u128_val = addr.toU128(); try testing.expect(u128_val != 0); } test "Ipv6Address.toSlice" { const ipv6 = Ipv6Address.init([_]u8{ 0x20, 0x01, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x01 }); var buf: [39]u8 = undefined; const slice = ipv6.toSlice(&buf); try testing.expect(slice.len > 0); } test "Ipv4Address.toSlice" { const ip = Ipv4Address.init([_]u8{ 192, 168, 1, 1 }); var buf: [15]u8 = undefined; const slice = ip.toSlice(&buf); try testing.expect(slice.len > 0); }