// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! An IPv4 network in CIDR notation (RFC 4632), as in `192.168.1.0/24`. //! //! The stored address is always the network address: every bit outside the //! prefix is zero. `parse` rejects text whose host bits are set, and //! `parseTruncate` clears them instead. const std = @import("std"); const json = @import("json.zig"); const Writer = std.Io.Writer; const decimal = @import("decimal.zig"); const Ipv4Address = @import("Ipv4Address.zig"); const Ipv4Network = @This(); /// The network address: the low `32 - prefix_len` bits are zero. address: Ipv4Address, /// Length of the routing prefix in bits, at most 32. prefix_len: u8, /// The default route, `0.0.0.0/0`, which contains every IPv4 address. pub const default_route: Ipv4Network = .{ .address = .unspecified, .prefix_len = 0 }; pub const InitError = error{ /// The prefix length was greater than 32. InvalidPrefixLength, /// Bits outside the prefix were set, as in `192.168.1.1/24`. HasHostBits, }; /// Builds a network, requiring the host bits of `address` to be clear. pub fn init(address: Ipv4Address, prefix_len: u8) InitError!Ipv4Network { if (prefix_len > Ipv4Address.bit_count) return error.InvalidPrefixLength; if (address.toInt() & ~netmaskInt(prefix_len) != 0) return error.HasHostBits; return .{ .address = address, .prefix_len = prefix_len }; } /// Builds a network from any address in it, clearing the host bits. pub fn initTruncate(address: Ipv4Address, prefix_len: u8) error{InvalidPrefixLength}!Ipv4Network { if (prefix_len > Ipv4Address.bit_count) return error.InvalidPrefixLength; return .{ .address = .fromInt(address.toInt() & netmaskInt(prefix_len)), .prefix_len = prefix_len, }; } /// The `/32` network holding exactly `address`. pub fn fromHost(address: Ipv4Address) Ipv4Network { return .{ .address = address, .prefix_len = Ipv4Address.bit_count }; } /// What can go wrong reading the text after `/`. `parsePrefixLen` returns /// these, and both parsers here include them. pub const PrefixError = error{ /// The text after `/` was not a decimal prefix length in the range 0 to 32 /// and was not a dotted-decimal netmask. InvalidPrefix, /// The prefix length after `/` was greater than 32. InvalidPrefixLength, /// The netmask after `/` did not consist of a run of one bits followed by /// a run of zero bits, as in `10.0.0.0/255.0.255.0`. NonContiguousNetmask, }; pub const ParseError = Ipv4Address.ParseError || InitError || PrefixError; /// Options accepted by `parseWithOptions` and `parsePrefixLenWithOptions`. pub const ParseOptions = struct { /// Accept a dotted-decimal netmask in place of a prefix length, as in /// `192.168.1.0/255.255.255.0`. CIDR notation proper has only the decimal /// length; the netmask is the older spelling, still common in /// configuration files, and rejecting it is `error.InvalidPrefix`. allow_netmask: bool = true, /// Clear the bits outside the prefix rather than rejecting them with /// `error.HasHostBits`, so that `192.168.1.130/24` yields /// `192.168.1.0/24`. This is what `parseTruncate` sets. truncate_host_bits: bool = false, /// What an SPF record may write after `ip4:`, as RFC 7208 §5.6 defines it. /// /// SPF spells the prefix length as a decimal number and nothing else -- /// `ip4-cidr-length = "/" ("0" / %x31-39 0*1DIGIT)`, a value of 0 to 32 -- /// so the netmask form is not part of the language and is refused. The /// mechanism then compares only the high-order bits of the address, which /// makes `ip4:192.0.2.130/24` a legal way to write `192.0.2.0/24` rather /// than the error the default would make of it. /// /// The rest of what §5.6 requires is what this parser already does: /// `ip4-network` is four `qnum`s, which is exactly the dotted-quad /// `Ipv4Address.parse` accepts and no leading zeros, and an omitted /// length means `/32`. /// /// Only the network is parsed, so strip the `ip4:` first. A record that /// should be rejected outright for setting host bits, rather than read the /// way a checker reads it, wants `.{ .allow_netmask = false }` instead. pub const spf: ParseOptions = .{ .allow_netmask = false, .truncate_host_bits = true }; }; /// Parses CIDR notation, as in `192.168.1.0/24`. /// /// A dotted-decimal netmask is also accepted in place of a prefix length, as /// in `192.168.1.0/255.255.255.0`. Text with no `/` at all is read as a single /// host, equivalent to a `/32`. /// /// Host bits must be clear; `192.168.1.1/24` is rejected with /// `error.HasHostBits`. Use `parseTruncate` to accept and clear them, or /// `parseWithOptions` to say what a particular text form allows. pub fn parse(text: []const u8) ParseError!Ipv4Network { return parseWithOptions(text, .{}); } /// Like `parse`, but clears any host bits instead of rejecting them, so that /// `192.168.1.130/24` yields `192.168.1.0/24`. pub fn parseTruncate(text: []const u8) ParseError!Ipv4Network { return parseWithOptions(text, .{ .truncate_host_bits = true }); } /// Like `parse`, but reading the text form that `options` describes. Use this /// for the stricter notation another standard defines, such as the `ip4:` of /// an SPF record: /// /// ``` /// const network = try Ipv4Network.parseWithOptions(term["ip4:".len..], .spf); /// ``` pub fn parseWithOptions(text: []const u8, options: ParseOptions) ParseError!Ipv4Network { const parsed = try parseParts(text, options); if (options.truncate_host_bits) return initTruncate(parsed.address, parsed.prefix_len); return init(parsed.address, parsed.prefix_len); } fn parseParts( text: []const u8, options: ParseOptions, ) ParseError!struct { address: Ipv4Address, prefix_len: u8 } { // A plain loop, because on text this short the vectorized // `std.mem.findScalar` costs more in setup than it saves. const slash: ?usize = for (text, 0..) |c, i| { if (c == '/') break i; } else null; return .{ .address = try Ipv4Address.parse(text[0 .. slash orelse text.len]), .prefix_len = if (slash) |index| try parsePrefixLenWithOptions(text[index + 1 ..], options) else Ipv4Address.bit_count, }; } /// Parses the text that follows a `/`: a decimal prefix length, or a /// dotted-decimal netmask in its place, so that both `24` and `255.255.255.0` /// yield 24. Leading zeros are rejected, as they are everywhere else. /// /// `Ipv4Interface` reads its prefix through this, so the two types are strict /// about the same things. pub fn parsePrefixLen(text: []const u8) PrefixError!u8 { return parsePrefixLenWithOptions(text, .{}); } /// Like `parsePrefixLen`, but reading only what `options` allows. Only /// `allow_netmask` has any say in what follows a `/`; the host bits are the /// address's business rather than the length's. pub fn parsePrefixLenWithOptions(text: []const u8, options: ParseOptions) PrefixError!u8 { for (text) |c| { if (c == '.') { if (!options.allow_netmask) return error.InvalidPrefix; const mask = Ipv4Address.parse(text) catch return error.InvalidPrefix; return prefixLenFromNetmask(mask); } } if (text.len == 0 or text.len > 2) return error.InvalidPrefix; if (text.len > 1 and text[0] == '0') return error.InvalidPrefix; var value: u8 = 0; for (text) |c| { const digit = c -% '0'; if (digit > 9) return error.InvalidPrefix; value = value * 10 + digit; } if (value > Ipv4Address.bit_count) return error.InvalidPrefixLength; return value; } /// The prefix length a netmask stands for, as in `255.255.255.0` for 24. pub fn prefixLenFromNetmask(mask: Ipv4Address) error{NonContiguousNetmask}!u8 { const value = mask.toInt(); const prefix_len: u8 = @popCount(value); if (value != netmaskInt(prefix_len)) return error.NonContiguousNetmask; return prefix_len; } /// Whether `text` is valid CIDR notation with its host bits clear, discarding /// the reason when it is not. pub fn isValid(text: []const u8) bool { _ = parse(text) catch return false; return true; } fn netmaskInt(prefix_len: u8) u32 { if (prefix_len == 0) return 0; return ~@as(u32, 0) << @intCast(Ipv4Address.bit_count - prefix_len); } /// The netmask, as in `255.255.255.0` for a `/24`. pub fn netmask(n: Ipv4Network) Ipv4Address { return .fromInt(netmaskInt(n.prefix_len)); } /// The complement of the netmask, as in `0.0.0.255` for a `/24`. pub fn hostmask(n: Ipv4Network) Ipv4Address { return .fromInt(~netmaskInt(n.prefix_len)); } /// The first address in the network, which is its network address. pub fn networkAddress(n: Ipv4Network) Ipv4Address { return n.address; } /// The last address in the network, which is its directed broadcast address. pub fn broadcastAddress(n: Ipv4Network) Ipv4Address { return .fromInt(n.address.toInt() | ~netmaskInt(n.prefix_len)); } /// Whether the network holds exactly one address, which is to say that its /// prefix length is the full width of the family: a `/32` for IPv4 or a /// `/128` for IPv6. /// /// This is worth asking as a question of its own because such a network is /// where a great deal of code has a special case — a route that is a host /// route, a firewall rule that names one machine, an access list entry /// written with no `/` at all — and reading `n.prefixLen() == Ipv4Address.bit_count` /// at each of those places says less about the intent than this does. pub fn isSingleAddress(n: Ipv4Network) bool { return n.prefix_len == Ipv4Address.bit_count; } /// The number of addresses in the network, from 1 for a `/32` up to 2^32 for /// a `/0`. pub fn addressCount(n: Ipv4Network) u64 { return @as(u64, 1) << @intCast(Ipv4Address.bit_count - n.prefix_len); } /// The number of usable host addresses. A `/31` is a point-to-point link whose /// two addresses are both usable (RFC 3021) and a `/32` is a single host; /// every shorter prefix reserves its network and broadcast addresses. pub fn hostCount(n: Ipv4Network) u64 { return switch (n.prefix_len) { 32 => 1, 31 => 2, else => n.addressCount() - 2, }; } /// The first usable host address. pub fn firstHost(n: Ipv4Network) Ipv4Address { if (n.prefix_len >= 31) return n.address; return .fromInt(n.address.toInt() + 1); } /// The last usable host address. pub fn lastHost(n: Ipv4Network) Ipv4Address { if (n.prefix_len >= 31) return n.broadcastAddress(); return .fromInt(n.broadcastAddress().toInt() - 1); } /// Whether `address` falls inside the network. pub fn contains(n: Ipv4Network, address: Ipv4Address) bool { return address.toInt() & netmaskInt(n.prefix_len) == n.address.toInt(); } /// Whether every address of `other` also falls inside `n`. pub fn containsNetwork(n: Ipv4Network, other: Ipv4Network) bool { return other.prefix_len >= n.prefix_len and n.contains(other.address); } /// Whether the two networks share any address. Two networks either nest or are /// disjoint, so this is true exactly when one contains the other. pub fn overlaps(n: Ipv4Network, other: Ipv4Network) bool { return n.contains(other.address) or other.contains(n.address); } /// The network one bit shorter than this one, or the network with the given /// prefix length when `new_prefix_len` is supplied. pub fn supernet(n: Ipv4Network, new_prefix_len: ?u8) error{InvalidPrefixLength}!Ipv4Network { const prefix_len = new_prefix_len orelse (if (n.prefix_len == 0) return error.InvalidPrefixLength else n.prefix_len - 1); if (prefix_len > n.prefix_len) return error.InvalidPrefixLength; return initTruncate(n.address, prefix_len); } /// The part of this network that is left once `other` is taken out of it, /// as a sequence of whole networks. /// /// Removing one prefix from another cannot leave one prefix behind — take a /// `/26` out of a `/24` and what is left is a `/25` and a `/26` — so the /// answer is an iterator. It yields at most `other.prefixLen() - /// prefixLen()` networks, which is 32 at the very worst for IPv4 and 128 for /// IPv6, and it allocates nothing: each block is computed from the path down /// to `other` as it goes. The blocks are disjoint, none of them overlaps /// `other`, and together they cover exactly the remainder. /// /// The three cases it has to handle, none of which is an error: /// /// * `other` lies outside this network, so nothing is removed and the one /// network yielded is this one. /// * `other` covers this network, so everything is removed and nothing is /// yielded. /// * `other` lies strictly inside, which is the interesting case above. /// /// The blocks come out largest first, which is the order they are found in /// walking down to `other`. That is not address order and cannot be: which /// side of `other` each block falls on depends on where in the network /// `other` sits. /// /// This is the operation a firewall or a routing table is built out of — /// "this range, except that part of it" — and the one thing CIDR notation /// cannot write down directly. pub fn exclude(n: Ipv4Network, other: Ipv4Network) ExcludeIterator { if (!n.overlaps(other)) return .initWhole(n); if (other.containsNetwork(n)) return .initEmpty(); return .{ .whole = null, .target = other.address, .next_len = n.prefix_len + 1, .last_len = other.prefix_len, }; } pub const ExcludeIterator = struct { /// Set only in the case where nothing was removed, and handed back by the /// first `next` call. whole: ?Ipv4Network, /// The network being removed. Only its leading bits are read: the block /// to yield at each level is the sibling of `target`'s prefix at that /// level, which is the half of it that `target` is not in. target: Ipv4Address, next_len: u8, last_len: u8, /// An iterator over `network` alone, which is what `exclude` returns when /// there was nothing in it to remove. pub fn initWhole(network: Ipv4Network) ExcludeIterator { return .{ .whole = network, .target = undefined, .next_len = 1, .last_len = 0 }; } /// An iterator over nothing, which is what `exclude` returns when the /// whole network was removed. pub fn initEmpty() ExcludeIterator { return .{ .whole = null, .target = undefined, .next_len = 1, .last_len = 0 }; } pub fn next(it: *ExcludeIterator) ?Ipv4Network { if (it.whole) |network| { it.whole = null; return network; } if (it.next_len > it.last_len) return null; const len = it.next_len; it.next_len += 1; // The bit that tells the two halves at this level apart. Flipping it // in `target`'s prefix names the half `target` is not in, which is // therefore entirely outside `other` and entirely inside `n`. const bit = @as(u32, 1) << @intCast(Ipv4Address.bit_count - len); const prefix = it.target.toInt() & netmaskInt(len); return .{ .address = .fromInt(prefix ^ bit), .prefix_len = len }; } test next { // Three levels down, so three blocks. var it = (try parse("192.0.2.0/24")).exclude(try .parse("192.0.2.0/27")); var count: usize = 0; while (it.next()) |_| count += 1; try std.testing.expectEqual(@as(usize, 3), count); } }; /// Splits the network into equal subnets of length `new_prefix_len`, which /// must be at least as long as this network's prefix. pub fn subnets(n: Ipv4Network, new_prefix_len: u8) error{InvalidPrefixLength}!SubnetIterator { if (new_prefix_len < n.prefix_len or new_prefix_len > Ipv4Address.bit_count) { return error.InvalidPrefixLength; } const start: u64 = n.address.toInt(); return .{ .next_value = start, .end_value = start + n.addressCount(), .step = @as(u64, 1) << @intCast(Ipv4Address.bit_count - new_prefix_len), .prefix_len = new_prefix_len, }; } pub const SubnetIterator = struct { next_value: u64, end_value: u64, step: u64, prefix_len: u8, pub fn next(it: *SubnetIterator) ?Ipv4Network { if (it.next_value >= it.end_value) return null; const value: u32 = @intCast(it.next_value); it.next_value += it.step; return .{ .address = .fromInt(value), .prefix_len = it.prefix_len }; } test next { var it = try (try parse("192.0.2.0/24")).subnets(26); try std.testing.expect(it.next().?.eql(try parse("192.0.2.0/26"))); try std.testing.expect(it.next().?.eql(try parse("192.0.2.64/26"))); try std.testing.expect(it.next().?.eql(try parse("192.0.2.128/26"))); try std.testing.expect(it.next().?.eql(try parse("192.0.2.192/26"))); // Null once the network is used up, so a `while` loop ends on its own. try std.testing.expectEqual(null, it.next()); } }; /// Iterates over every address in the network, network and broadcast /// addresses included. pub fn addresses(n: Ipv4Network) AddressIterator { const start: u64 = n.address.toInt(); return .{ .next_value = start, .end_value = start + n.addressCount() }; } /// Iterates over the usable host addresses, skipping the network and broadcast /// addresses of a `/30` or shorter prefix. pub fn hosts(n: Ipv4Network) AddressIterator { const first: u64 = n.firstHost().toInt(); return .{ .next_value = first, .end_value = first + n.hostCount() }; } pub const AddressIterator = struct { next_value: u64, end_value: u64, pub fn next(it: *AddressIterator) ?Ipv4Address { if (it.next_value >= it.end_value) return null; const value: u32 = @intCast(it.next_value); it.next_value += 1; return .fromInt(value); } test next { var it = (try parse("192.0.2.0/30")).addresses(); try std.testing.expect(it.next().?.eql(try .parse("192.0.2.0"))); try std.testing.expect(it.next().?.eql(try .parse("192.0.2.1"))); try std.testing.expect(it.next().?.eql(try .parse("192.0.2.2"))); try std.testing.expect(it.next().?.eql(try .parse("192.0.2.3"))); // Null once the network is used up, so a `while` loop ends on its own. try std.testing.expectEqual(null, it.next()); } }; /// Sorts `networks` in place and folds it down to the smallest set of /// networks covering exactly the same addresses, returning the prefix of the /// slice that survives. /// /// Two things are folded away: a network already inside another disappears, /// and two networks that are the two halves of one larger network become that /// larger network. The second is applied repeatedly, so four adjacent `/26`s /// come out as one `/24`, and it is why the result can be shorter than /// anything a single pass over the input would produce. /// /// This is the operation that keeps a generated access list or route set from /// growing without bound -- the one thing on this type that is naturally a /// whole-collection operation rather than a question about one network. /// /// It takes a mutable slice rather than an allocator because sorting is the /// only thing it needs and sorting can be done in place. The caller owns the /// storage, decides where it came from, and keeps whatever is past the /// returned slice: those entries are still the caller's networks, merely no /// longer needed, rather than freed memory. /// /// ``` /// var list = [_]Ipv4Network{ a, b, c }; /// for (Ipv4Network.merge(&list)) |network| ... /// ``` pub fn merge(networks: []Ipv4Network) []Ipv4Network { // Unstable, because under this comparator two networks that compare // equal are the same network and there is no order between them to // preserve. std.mem.sortUnstable(Ipv4Network, networks, {}, lessThan); // The front of the slice doubles as a stack of the networks kept so far, // which is what makes this allocation-free: nothing survives that was not // already in the input, and it can only move towards the front. var kept: usize = 0; for (networks) |candidate| { var network = candidate; // Sorted order puts a containing network before everything inside it, // and the networks kept so far are disjoint, so only the top of the // stack can possibly contain or join this one. Combining can expose // another pair, so this repeats: `.0/26`, `.64/26`, `.128/25` folds // twice. while (kept > 0) { const top = networks[kept - 1]; if (top.containsNetwork(network)) break; network = join(top, network) orelse break; kept -= 1; } if (kept > 0 and networks[kept - 1].containsNetwork(network)) continue; networks[kept] = network; kept += 1; } return networks[0..kept]; } fn lessThan(_: void, a: Ipv4Network, b: Ipv4Network) bool { return a.order(b) == .lt; } /// The one network that covers both exactly, when they are the two halves of /// it, and null otherwise. Order does not matter. /// /// Being adjacent is not enough and neither is being the same size. A `/25` /// and the `/26` after it touch without being halves of anything, and so do /// the upper `/26` of one `/25` and the lower `/26` of the next: halves are /// two networks of the same size that differ in exactly the bit their length /// makes significant, which means the lower of them has that bit clear. /// /// This is the step `merge` is built out of, and it is worth having on its /// own wherever the question is whether two entries in a list can be written /// as one. pub fn join(a: Ipv4Network, b: Ipv4Network) ?Ipv4Network { if (a.prefix_len != b.prefix_len or a.prefix_len == 0) return null; const lower = if (a.address.toInt() <= b.address.toInt()) a else b; const upper = if (a.address.toInt() <= b.address.toInt()) b else a; const bit = @as(u32, 1) << @intCast(Ipv4Address.bit_count - a.prefix_len); const low = lower.address.toInt(); if (low & bit != 0) return null; if (low | bit != upper.address.toInt()) return null; return .{ .address = lower.address, .prefix_len = lower.prefix_len - 1 }; } pub fn eql(n: Ipv4Network, other: Ipv4Network) bool { return n.prefix_len == other.prefix_len and n.address.eql(other.address); } /// Orders by network address first, then by prefix length, so that a /// containing network sorts before the networks inside it. pub fn order(n: Ipv4Network, other: Ipv4Network) std.math.Order { return switch (n.address.order(other.address)) { .eq => std.math.order(n.prefix_len, other.prefix_len), else => |result| result, }; } /// The longest text an IPv4 network can format to, as in /// `255.255.255.255/32`. pub const max_text_len = Ipv4Address.max_text_len + "/32".len; /// Writes the network in CIDR notation. Use the `{f}` specifier. pub fn format(n: Ipv4Network, w: *Writer) Writer.Error!void { var buffer: [render_len]u8 = undefined; try w.writeAll(n.render(&buffer)); } /// Formats into `buffer`, returning the written slice. The buffer must be at /// least `max_text_len` bytes. pub fn bufPrint(n: Ipv4Network, buffer: []u8) error{NoSpaceLeft}![]u8 { var rendered: [render_len]u8 = undefined; const text = n.render(&rendered); if (buffer.len < text.len) return error.NoSpaceLeft; @memcpy(buffer[0..text.len], text); return buffer[0..text.len]; } /// Room for the longest text plus the byte of slack the address's `bufPrint` /// wants to render in place and the spill of `decimal.renderSmall`. const render_len = Ipv4Address.max_text_len + 1 + "/".len + 4; /// Renders the CIDR notation into `buffer`, returning the written slice. This /// is the one place the text is produced; `format` and `bufPrint` both go /// through it rather than through `Writer.print`, whose per-integer formatting /// costs more than the whole network. fn render(n: Ipv4Network, buffer: *[render_len]u8) []u8 { const address = n.address.bufPrint(buffer[0 .. Ipv4Address.max_text_len + 1]) catch unreachable; var len = address.len; buffer[len] = '/'; len += 1; len += decimal.renderSmall(n.prefix_len, buffer[len..][0..4]); return buffer[0..len]; } /// Writes the value as a JSON string. See `json.stringify`. pub fn jsonStringify(value: Ipv4Network, jws: anytype) !void { return json.stringify(value, jws); } /// Reads a JSON string with `parse`. See `json.parse` for what happens to the /// reason when the text is rejected. pub fn jsonParse( allocator: std.mem.Allocator, source: anytype, options: std.json.ParseOptions, ) !Ipv4Network { _ = options; return json.parse(Ipv4Network, allocator, source); } const testing = std.testing; test parse { const n = try parse("192.168.1.0/24"); try testing.expectEqual(Ipv4Address.init(192, 168, 1, 0), n.address); try testing.expectEqual(@as(u8, 24), n.prefix_len); try testing.expect((try parse("0.0.0.0/0")).eql(default_route)); try testing.expect((try parse("10.0.0.0/255.0.0.0")).eql(try parse("10.0.0.0/8"))); // Text without a prefix is a single host. try testing.expect((try parse("192.0.2.1")).eql(fromHost(.init(192, 0, 2, 1)))); try testing.expect((try parse("192.0.2.1/32")).eql(fromHost(.init(192, 0, 2, 1)))); } test "parse rejects malformed text" { try testing.expectError(error.HasHostBits, parse("192.168.1.1/24")); try testing.expectError(error.HasHostBits, parse("10.0.0.1/255.0.0.0")); try testing.expectError(error.InvalidPrefixLength, parse("192.168.1.0/33")); try testing.expectError(error.InvalidPrefix, parse("192.168.1.0/")); try testing.expectError(error.InvalidPrefix, parse("192.168.1.0/24 ")); try testing.expectError(error.InvalidPrefix, parse("192.168.1.0/024")); try testing.expectError(error.InvalidPrefix, parse("192.168.1.0/x")); try testing.expectError(error.InvalidPrefix, parse("192.168.1.0/-1")); try testing.expectError(error.NonContiguousNetmask, parse("10.0.0.0/255.0.255.0")); try testing.expectError(error.TooFewOctets, parse("192.168.1/24")); try testing.expectError(error.OctetOutOfRange, parse("192.168.1.256/24")); } test parseTruncate { try testing.expect((try parseTruncate("192.168.1.130/24")).eql(try parse("192.168.1.0/24"))); try testing.expect((try parseTruncate("1.2.3.4/0")).eql(default_route)); try testing.expect((try parseTruncate("192.168.1.130/32")).eql(fromHost(.init(192, 168, 1, 130)))); } test "the SPF form of ip4-network" { // RFC 7208 section 5.6's own example, and the shape nearly every record // uses. try testing.expect((try parseWithOptions("192.0.2.0/24", .spf)) .eql(try parse("192.0.2.0/24"))); // An omitted length is a /32, as section 5.6 says in as many words. try testing.expect((try parseWithOptions("192.0.2.1", .spf)) .eql(fromHost(.init(192, 0, 2, 1)))); try testing.expect((try parseWithOptions("0.0.0.0/0", .spf)).eql(default_route)); // The mechanism compares high-order bits, so host bits are something to // ignore rather than to refuse. try testing.expect((try parseWithOptions("192.0.2.130/24", .spf)) .eql(try parse("192.0.2.0/24"))); // The netmask spelling is not in the grammar at all. try testing.expectError(error.InvalidPrefix, parseWithOptions("10.0.0.0/255.0.0.0", .spf)); try testing.expect((try parse("10.0.0.0/255.0.0.0")).eql(try parse("10.0.0.0/8"))); // `ip4-cidr-length` is one or two digits with no leading zero, and // `ip4-network` is four `qnum`s -- all of which the default parser is // already strict about, so the option has nothing to add. try testing.expectError(error.InvalidPrefix, parseWithOptions("192.0.2.0/024", .spf)); try testing.expectError(error.InvalidPrefixLength, parseWithOptions("192.0.2.0/33", .spf)); try testing.expectError(error.LeadingZero, parseWithOptions("192.000.2.0/24", .spf)); try testing.expectError(error.TooFewOctets, parseWithOptions("192.0.2/24", .spf)); // Refusing the netmask and refusing host bits are separate switches, for // a validator that wants to say a record is sloppy rather than read it // the way a checker would. const strict: ParseOptions = .{ .allow_netmask = false }; try testing.expectError(error.HasHostBits, parseWithOptions("192.0.2.130/24", strict)); try testing.expectError(error.InvalidPrefix, parseWithOptions("10.0.0.0/255.0.0.0", strict)); } test parsePrefixLenWithOptions { try testing.expectEqual(@as(u8, 8), try parsePrefixLen("255.0.0.0")); try testing.expectEqual(@as(u8, 8), try parsePrefixLenWithOptions("8", .spf)); try testing.expectError(error.InvalidPrefix, parsePrefixLenWithOptions("255.0.0.0", .spf)); } test jsonStringify { var buffer: [128]u8 = undefined; var w: Writer = .fixed(&buffer); try std.json.Stringify.value(try Ipv4Network.parse("192.0.2.0/24"), .{}, &w); // A JSON string holding exactly what `format` would have written. try testing.expectEqualStrings("\"192.0.2.0/24\"", w.buffered()); } test jsonParse { // The hook is driven directly rather than through `parseFromSlice`, so // that this tests the function it is named after and nothing else; // `root.zig` has the end-to-end one. var scanner = std.json.Scanner.initCompleteInput(testing.allocator, "\"192.0.2.0/24\""); defer scanner.deinit(); const value = try Ipv4Network.jsonParse(testing.allocator, &scanner, .{}); try testing.expect(value.eql(try Ipv4Network.parse("192.0.2.0/24"))); // As strict inside a JSON document as anywhere else, though the reason is // flattened to `InvalidCharacter` on the way out. var bad = std.json.Scanner.initCompleteInput(testing.allocator, "\"192.0.2.1/24\""); defer bad.deinit(); try testing.expectError( error.InvalidCharacter, Ipv4Network.jsonParse(testing.allocator, &bad, .{}), ); // Anything that is not a string is the wrong shape rather than a bad // address. var number = std.json.Scanner.initCompleteInput(testing.allocator, "42"); defer number.deinit(); try testing.expectError( error.UnexpectedToken, Ipv4Network.jsonParse(testing.allocator, &number, .{}), ); } test format { try testing.expectFmt("192.168.1.0/24", "{f}", .{try parse("192.168.1.0/24")}); try testing.expectFmt("0.0.0.0/0", "{f}", .{default_route}); try testing.expectFmt("192.0.2.1/32", "{f}", .{fromHost(.init(192, 0, 2, 1))}); var buffer: [max_text_len]u8 = undefined; try testing.expectEqualStrings("255.255.255.255/32", try (fromHost(.broadcast)).bufPrint(&buffer)); } test "masks and bounds" { const n = try parse("192.168.1.0/24"); try testing.expectFmt("255.255.255.0", "{f}", .{n.netmask()}); try testing.expectFmt("0.0.0.255", "{f}", .{n.hostmask()}); try testing.expectFmt("192.168.1.0", "{f}", .{n.networkAddress()}); try testing.expectFmt("192.168.1.255", "{f}", .{n.broadcastAddress()}); try testing.expectFmt("192.168.1.1", "{f}", .{n.firstHost()}); try testing.expectFmt("192.168.1.254", "{f}", .{n.lastHost()}); try testing.expectEqual(@as(u64, 256), n.addressCount()); try testing.expectEqual(@as(u64, 254), n.hostCount()); // A /0 covers the whole address space without overflowing. try testing.expectEqual(@as(u64, 1) << 32, default_route.addressCount()); try testing.expectFmt("0.0.0.0", "{f}", .{default_route.netmask()}); try testing.expectFmt("255.255.255.255", "{f}", .{default_route.broadcastAddress()}); // RFC 3021 point-to-point links and single hosts have no reserved // addresses. const p2p = try parse("192.0.2.0/31"); try testing.expectEqual(@as(u64, 2), p2p.hostCount()); try testing.expectFmt("192.0.2.0", "{f}", .{p2p.firstHost()}); try testing.expectFmt("192.0.2.1", "{f}", .{p2p.lastHost()}); const host = try parse("192.0.2.1/32"); try testing.expectEqual(@as(u64, 1), host.addressCount()); try testing.expectEqual(@as(u64, 1), host.hostCount()); try testing.expectFmt("192.0.2.1", "{f}", .{host.firstHost()}); try testing.expectFmt("192.0.2.1", "{f}", .{host.lastHost()}); } test contains { const n = try parse("192.168.1.0/24"); try testing.expect(n.contains(.init(192, 168, 1, 0))); try testing.expect(n.contains(.init(192, 168, 1, 255))); try testing.expect(!n.contains(.init(192, 168, 2, 0))); try testing.expect(!n.contains(.init(192, 168, 0, 255))); try testing.expect(default_route.contains(.broadcast)); try testing.expect(default_route.contains(.unspecified)); const private = try parse("10.0.0.0/8"); try testing.expect(private.containsNetwork(try parse("10.1.0.0/16"))); try testing.expect(private.containsNetwork(private)); try testing.expect(!private.containsNetwork(try parse("11.0.0.0/16"))); try testing.expect(!(try parse("10.1.0.0/16")).containsNetwork(private)); try testing.expect(private.overlaps(try parse("10.1.0.0/16"))); try testing.expect((try parse("10.1.0.0/16")).overlaps(private)); try testing.expect(!private.overlaps(try parse("11.0.0.0/8"))); } test exclude { // A `/26` out of a `/24` leaves a `/25` and a `/26`, largest first. var it = (try parse("192.0.2.0/24")).exclude(try .parse("192.0.2.0/26")); try std.testing.expect(it.next().?.eql(try .parse("192.0.2.128/25"))); try std.testing.expect(it.next().?.eql(try .parse("192.0.2.64/26"))); try std.testing.expectEqual(null, it.next()); // Nothing to remove: the network comes back whole. var apart = (try parse("192.0.2.0/24")).exclude(try .parse("198.51.100.0/24")); try std.testing.expect(apart.next().?.eql(try parse("192.0.2.0/24"))); try std.testing.expectEqual(null, apart.next()); // Everything removed, including the case where the two are equal. var all = (try parse("192.0.2.0/24")).exclude(try .parse("192.0.0.0/16")); try std.testing.expectEqual(null, all.next()); var same = (try parse("192.0.2.0/24")).exclude(try .parse("192.0.2.0/24")); try std.testing.expectEqual(null, same.next()); // Whatever is excluded, the blocks left behind cover the rest exactly: // none contains the removed address, and their sizes add up. var total: u129 = 0; var parts = (try parse("192.0.2.0/24")).exclude(try .parse("192.0.2.0/26")); while (parts.next()) |part| { try std.testing.expect(!part.overlaps(try .parse("192.0.2.0/26"))); total += part.addressCount(); } try std.testing.expectEqual( (try parse("192.0.2.0/24")).addressCount() - (try parse("192.0.2.0/26")).addressCount(), total, ); } test subnets { var it = try (try parse("192.168.1.0/24")).subnets(26); try testing.expectFmt("192.168.1.0/26", "{f}", .{it.next().?}); try testing.expectFmt("192.168.1.64/26", "{f}", .{it.next().?}); try testing.expectFmt("192.168.1.128/26", "{f}", .{it.next().?}); try testing.expectFmt("192.168.1.192/26", "{f}", .{it.next().?}); try testing.expectEqual(null, it.next()); // Splitting to the same prefix length yields the network itself. var same = try (try parse("10.0.0.0/8")).subnets(8); try testing.expect(same.next().?.eql(try parse("10.0.0.0/8"))); try testing.expectEqual(null, same.next()); // The whole space splits into two halves without overflowing. var halves = try default_route.subnets(1); try testing.expectFmt("0.0.0.0/1", "{f}", .{halves.next().?}); try testing.expectFmt("128.0.0.0/1", "{f}", .{halves.next().?}); try testing.expectEqual(null, halves.next()); try testing.expectError(error.InvalidPrefixLength, (try parse("10.0.0.0/8")).subnets(4)); try testing.expectError(error.InvalidPrefixLength, (try parse("10.0.0.0/8")).subnets(33)); } test supernet { try testing.expect((try (try parse("192.168.1.0/24")).supernet(null)).eql(try parse("192.168.0.0/23"))); try testing.expect((try (try parse("192.168.1.0/24")).supernet(16)).eql(try parse("192.168.0.0/16"))); try testing.expectError(error.InvalidPrefixLength, default_route.supernet(null)); try testing.expectError(error.InvalidPrefixLength, (try parse("10.0.0.0/8")).supernet(9)); } test "iterating addresses and hosts" { var it = (try parse("192.0.2.0/30")).addresses(); try testing.expectFmt("192.0.2.0", "{f}", .{it.next().?}); try testing.expectFmt("192.0.2.1", "{f}", .{it.next().?}); try testing.expectFmt("192.0.2.2", "{f}", .{it.next().?}); try testing.expectFmt("192.0.2.3", "{f}", .{it.next().?}); try testing.expectEqual(null, it.next()); var host_it = (try parse("192.0.2.0/30")).hosts(); try testing.expectFmt("192.0.2.1", "{f}", .{host_it.next().?}); try testing.expectFmt("192.0.2.2", "{f}", .{host_it.next().?}); try testing.expectEqual(null, host_it.next()); // The last network in the address space stops rather than wrapping. var last = (try parse("255.255.255.252/30")).addresses(); var count: usize = 0; while (last.next()) |_| count += 1; try testing.expectEqual(@as(usize, 4), count); var single = (try parse("192.0.2.1/32")).hosts(); try testing.expectFmt("192.0.2.1", "{f}", .{single.next().?}); try testing.expectEqual(null, single.next()); } test "ordering" { try testing.expectEqual(.lt, (try parse("10.0.0.0/8")).order(try parse("10.0.0.0/16"))); try testing.expectEqual(.lt, (try parse("10.0.0.0/8")).order(try parse("11.0.0.0/8"))); try testing.expectEqual(.eq, (try parse("10.0.0.0/8")).order(try parse("10.0.0.0/8"))); } test prefixLenFromNetmask { try testing.expectEqual(@as(u8, 24), try prefixLenFromNetmask(.init(255, 255, 255, 0))); try testing.expectEqual(@as(u8, 0), try prefixLenFromNetmask(.unspecified)); try testing.expectEqual(@as(u8, 32), try prefixLenFromNetmask(.broadcast)); try testing.expectError(error.NonContiguousNetmask, prefixLenFromNetmask(.init(255, 0, 255, 0))); } test init { const network = try Ipv4Network.init(try .parse("192.168.1.0"), 24); try testing.expect(network.eql(try parse("192.168.1.0/24"))); // The host bits have to be clear; `initTruncate` is the one that clears // them. try testing.expectError(error.HasHostBits, Ipv4Network.init(try .parse("192.168.1.42"), 24)); try testing.expectError(error.InvalidPrefixLength, Ipv4Network.init(.unspecified, 33)); } test initTruncate { const network = try Ipv4Network.initTruncate(try .parse("192.168.1.42"), 24); try testing.expect(network.eql(try parse("192.168.1.0/24"))); } test fromHost { const network = Ipv4Network.fromHost(try .parse("192.0.2.1")); try testing.expectEqual(@as(u8, 32), network.prefix_len); try testing.expectEqual(@as(u64, 1), network.addressCount()); } test parseWithOptions { // The `ip4:` of an SPF record compares only the prefix, so host bits are // a legal way to write the network rather than an error. try testing.expect((try parseWithOptions("192.0.2.130/24", .spf)).eql(try parse("192.0.2.0/24"))); // That notation has no netmask form, though the default accepts one. try testing.expectError(error.InvalidPrefix, parseWithOptions("192.0.2.0/255.255.255.0", .spf)); try testing.expect((try parseWithOptions("192.0.2.0/255.255.255.0", .{})).eql(try parse("192.0.2.0/24"))); } test parsePrefixLen { try testing.expectEqual(@as(u8, 24), try parsePrefixLen("24")); // A netmask stands in for the length it means. try testing.expectEqual(@as(u8, 24), try parsePrefixLen("255.255.255.0")); try testing.expectError(error.InvalidPrefix, parsePrefixLen("024")); try testing.expectError(error.InvalidPrefixLength, parsePrefixLen("33")); } test isValid { try testing.expect(isValid("192.168.1.0/24")); // A bare address is a `/32` and so is valid notation. try testing.expect(isValid("192.0.2.1")); // Host bits are not, which is what separates a network from an interface. try testing.expect(!isValid("192.168.1.42/24")); } test netmask { try testing.expect((try parse("192.168.1.0/24")).netmask().eql(try .parse("255.255.255.0"))); try testing.expect((try parse("0.0.0.0/0")).netmask().eql(.unspecified)); } test hostmask { try testing.expect((try parse("192.168.1.0/24")).hostmask().eql(try .parse("0.0.0.255"))); try testing.expect((try parse("192.0.2.1/32")).hostmask().eql(.unspecified)); } test networkAddress { try testing.expect((try parse("192.168.1.0/24")).networkAddress().eql(try .parse("192.168.1.0"))); } test broadcastAddress { try testing.expect((try parse("192.168.1.0/24")) .broadcastAddress().eql(try .parse("192.168.1.255"))); } test isSingleAddress { try testing.expect((try parse("192.0.2.1/32")).isSingleAddress()); try testing.expect(!(try parse("192.0.2.0/24")).isSingleAddress()); // Text with no `/` parses as a single host, so it is one too. try testing.expect((try parse("192.0.2.1")).isSingleAddress()); } test addressCount { try testing.expectEqual(@as(u64, 256), (try parse("192.168.1.0/24")).addressCount()); try testing.expectEqual(@as(u64, 1), (try parse("192.0.2.1/32")).addressCount()); // A `/0` is the whole address space, which is why the count is 64 bits // wide. try testing.expectEqual(@as(u64, 1) << 32, (try parse("0.0.0.0/0")).addressCount()); } test hostCount { // Two addresses of an ordinary network are the network and broadcast // addresses rather than hosts. try testing.expectEqual(@as(u64, 254), (try parse("192.168.1.0/24")).hostCount()); // A `/31` is a point-to-point link where both addresses are usable, and a // `/32` is one host. try testing.expectEqual(@as(u64, 2), (try parse("192.0.2.0/31")).hostCount()); try testing.expectEqual(@as(u64, 1), (try parse("192.0.2.1/32")).hostCount()); } test firstHost { try testing.expect((try parse("192.168.1.0/24")).firstHost().eql(try .parse("192.168.1.1"))); // Nothing is reserved on a `/31`, so the network address is a host. try testing.expect((try parse("192.0.2.0/31")).firstHost().eql(try .parse("192.0.2.0"))); } test lastHost { try testing.expect((try parse("192.168.1.0/24")).lastHost().eql(try .parse("192.168.1.254"))); try testing.expect((try parse("192.0.2.0/31")).lastHost().eql(try .parse("192.0.2.1"))); } test containsNetwork { const outer = try parse("192.168.0.0/16"); try testing.expect(outer.containsNetwork(try parse("192.168.1.0/24"))); try testing.expect(outer.containsNetwork(outer)); // A shorter prefix is a larger network and cannot sit inside this one. try testing.expect(!outer.containsNetwork(try parse("192.0.0.0/8"))); } test overlaps { const network = try parse("192.168.1.0/24"); // Two networks either nest or are disjoint, so overlapping is containment // one way or the other. try testing.expect(network.overlaps(try parse("192.168.0.0/16"))); try testing.expect(network.overlaps(try parse("192.168.1.128/25"))); try testing.expect(!network.overlaps(try parse("192.168.2.0/24"))); } test addresses { var found: usize = 0; var it = (try parse("192.0.2.0/29")).addresses(); while (it.next()) |_| found += 1; // Every address, the network and broadcast addresses included. try testing.expectEqual(@as(usize, 8), found); } test hosts { var found: usize = 0; var it = (try parse("192.0.2.0/29")).hosts(); while (it.next()) |_| found += 1; // The same network without its network and broadcast addresses. try testing.expectEqual(@as(usize, 6), found); } test merge { // The two halves of a network become the network, twice over: the two // `/26`s make a `/25`, and that `/25` and the next one make the `/24`. var halves = [_]Ipv4Network{ try .parse("192.0.2.0/26"), try .parse("192.0.2.64/26"), try .parse("192.0.2.128/25"), }; const folded = Ipv4Network.merge(&halves); try testing.expectEqual(@as(usize, 1), folded.len); try testing.expect(folded[0].eql(try .parse("192.0.2.0/24"))); // A network inside another disappears, whichever order it arrived in. var nested = [_]Ipv4Network{ try .parse("192.0.2.16/28"), try .parse("192.0.2.0/24") }; const outer = Ipv4Network.merge(&nested); try testing.expectEqual(@as(usize, 1), outer.len); try testing.expect(outer[0].eql(try .parse("192.0.2.0/24"))); // Networks that are neither nested nor halves of anything are all kept, // and come back sorted. var apart = [_]Ipv4Network{ try .parse("198.51.100.0/24"), try .parse("192.0.2.0/24") }; const both = Ipv4Network.merge(&apart); try testing.expectEqual(@as(usize, 2), both.len); try testing.expect(both[0].eql(try .parse("192.0.2.0/24"))); try testing.expect(both[1].eql(try .parse("198.51.100.0/24"))); // Adjacent is not the same as joinable: these two touch and are not the // two halves of anything, because they are not the same size. var uneven = [_]Ipv4Network{ try .parse("192.0.2.0/25"), try .parse("192.0.2.128/26") }; try testing.expectEqual(@as(usize, 2), Ipv4Network.merge(&uneven).len); // Duplicates collapse, since a network contains itself. var same = [_]Ipv4Network{ try .parse("192.0.2.0/24"), try .parse("192.0.2.0/24") }; try testing.expectEqual(@as(usize, 1), Ipv4Network.merge(&same).len); // Nothing at all is a valid input. var empty: [0]Ipv4Network = .{}; try testing.expectEqual(@as(usize, 0), Ipv4Network.merge(&empty).len); } test lessThan { // The order `merge` needs: a containing network ahead of what is inside // it, so that the sweep only ever has to look at the top of its stack. try testing.expect(lessThan({}, try .parse("192.0.2.0/24"), try .parse("192.0.2.64/26"))); try testing.expect(!lessThan({}, try .parse("192.0.2.64/26"), try .parse("192.0.2.0/24"))); } test join { // The two halves of a network, in either order. try testing.expect(Ipv4Network.join(try .parse("192.0.2.0/26"), try .parse("192.0.2.64/26")).? .eql(try .parse("192.0.2.0/25"))); try testing.expect(Ipv4Network.join(try .parse("192.0.2.64/26"), try .parse("192.0.2.0/26")).? .eql(try .parse("192.0.2.0/25"))); // The upper half of one network and the lower half of the next are // adjacent and are not halves of anything: the bit that tells halves // apart is already set in the first of them. try testing.expectEqual(null, Ipv4Network.join(try .parse("192.0.2.64/26"), try .parse("192.0.2.128/26"))); // Different sizes never join. try testing.expectEqual(null, Ipv4Network.join(try .parse("192.0.2.0/25"), try .parse("192.0.2.128/26"))); // Nor does anything join into something wider than the address space. try testing.expectEqual(null, Ipv4Network.join(try .parse("0.0.0.0/0"), try .parse("0.0.0.0/0"))); } test eql { try testing.expect((try parse("192.168.1.0/24")).eql(try parse("192.168.1.0/24"))); // The prefix length is part of the network, not just the address. try testing.expect(!(try parse("192.168.1.0/24")).eql(try parse("192.168.1.0/25"))); } test order { // A containing network sorts before the networks inside it. try testing.expectEqual(.lt, (try parse("192.168.0.0/16")).order(try parse("192.168.0.0/24"))); try testing.expectEqual(.lt, (try parse("10.0.0.0/8")).order(try parse("192.168.0.0/16"))); try testing.expectEqual(.eq, (try parse("10.0.0.0/8")).order(try parse("10.0.0.0/8"))); } test bufPrint { var buffer: [max_text_len]u8 = undefined; try testing.expectEqualStrings( "192.168.1.0/24", try (try parse("192.168.1.0/24")).bufPrint(&buffer), ); var small: [4]u8 = undefined; try testing.expectError(error.NoSpaceLeft, (try parse("192.168.1.0/24")).bufPrint(&small)); } test parseParts { // The two halves as the text gives them, before `init` or `initTruncate` // has had a say about the host bits. const parts = try parseParts("192.168.1.42/24", .{}); try testing.expect(parts.address.eql(try .parse("192.168.1.42"))); try testing.expectEqual(@as(u8, 24), parts.prefix_len); // Text with no `/` at all is a single host. try testing.expectEqual(@as(u8, 32), (try parseParts("192.0.2.1", .{})).prefix_len); // A netmask stands in for the length it means, where the options allow it. try testing.expectEqual(@as(u8, 24), (try parseParts("192.168.1.0/255.255.255.0", .{})).prefix_len); } test netmaskInt { try testing.expectEqual(@as(u32, 0xffff_ff00), netmaskInt(24)); try testing.expectEqual(@as(u32, 0xffff_ffff), netmaskInt(32)); // A `/0` is the case the shift alone could not express: shifting a 32-bit // value by 32 is undefined, so zero is returned outright. try testing.expectEqual(@as(u32, 0), netmaskInt(0)); } test render { var buffer: [render_len]u8 = undefined; try testing.expectEqualStrings("192.168.1.0/24", (try parse("192.168.1.0/24")).render(&buffer)); try testing.expectEqualStrings("0.0.0.0/0", (try parse("0.0.0.0/0")).render(&buffer)); try testing.expectEqualStrings("255.255.255.255/32", (try parse("255.255.255.255/32")).render(&buffer)); }