From c3b47ba81277a24c8fb6cc194bace0da51c25ada Mon Sep 17 00:00:00 2001 From: Alejandro Mery Date: Tue, 22 Aug 2023 15:41:40 +0000 Subject: [PATCH] zones: introduce ValidZoneID() and ValidNodeID() Signed-off-by: Alejandro Mery --- pkg/zones/rings.go | 63 +++++++++++++++++++++++++++++++++++----------- 1 file changed, 49 insertions(+), 14 deletions(-) diff --git a/pkg/zones/rings.go b/pkg/zones/rings.go index 187b45a..dd65028 100644 --- a/pkg/zones/rings.go +++ b/pkg/zones/rings.go @@ -2,7 +2,39 @@ package zones import "net/netip" +const ( + // MaxZoneID indicates the highest ID allowed for a Zone + MaxZoneID = 0xf + // MaxNodeID indicates the highest Machine ID allowed within a Zone + MaxNodeID = 0xff - 1 +) + +// ValidZoneID checks if the given zoneID is a valid 4 bit zone number. +// +// 0 is reserved, and only allowed when composing CIDRs. +func ValidZoneID(zoneID int) bool { + switch { + case zoneID < 0 || zoneID > MaxZoneID: + return false + default: + return true + } +} + +// ValidNodeID checks if the given nodeID is a valid 8 bit number. +// nodeID is unique within a Zone. +// 0 is reserved, and only allowed when composing CIDRs. +func ValidNodeID(nodeID int) bool { + switch { + case nodeID < 0 || nodeID > MaxNodeID: + return false + default: + return true + } +} + // ParseRingZeroAddress extracts zone and node ID from a wg0 [netip.Addr] +// wg0 addresses are of the form `10.0.{{zoneID}}.{{nodeID}}` func ParseRingZeroAddress(addr netip.Addr) (zoneID int, nodeID int, ok bool) { if addr.IsValid() { a4 := addr.As4() @@ -15,16 +47,18 @@ func ParseRingZeroAddress(addr netip.Addr) (zoneID int, nodeID int, ok bool) { } // RingZeroAddress returns a wg0 IP address -func RingZeroAddress(zoneID, nodeID int) netip.Addr { - c := zoneID - d := nodeID - - return netip.AddrFrom4([4]byte{ - 10, 0, uint8(c), uint8(d), - }) +func RingZeroAddress(zoneID, nodeID int) (netip.Addr, bool) { + switch { + case !ValidZoneID(zoneID) || !ValidNodeID(nodeID): + return netip.Addr{}, false + default: + a4 := [4]uint8{10, 0, uint8(zoneID), uint8(nodeID)} + return netip.AddrFrom4(a4), true + } } // ParseRingOneAddress extracts zone and node ID from a wg1 [netip.Addr] +// wg1 addresses are of the form `10.{{zoneID << 4}}.{{nodeID}}` func ParseRingOneAddress(addr netip.Addr) (zoneID int, nodeID int, ok bool) { if addr.IsValid() { a4 := addr.As4() @@ -39,11 +73,12 @@ func ParseRingOneAddress(addr netip.Addr) (zoneID int, nodeID int, ok bool) { } // RingOneAddress returns a wg1 IP address -func RingOneAddress(zoneID, nodeID int) netip.Addr { - b := zoneID << 4 - d := nodeID - - return netip.AddrFrom4([4]byte{ - 10, uint8(b), 0, uint8(d), - }) +func RingOneAddress(zoneID, nodeID int) (netip.Addr, bool) { + switch { + case !ValidZoneID(zoneID) || !ValidNodeID(nodeID): + return netip.Addr{}, false + default: + a4 := [4]uint8{10, 0, uint8(zoneID << 4), uint8(nodeID)} + return netip.AddrFrom4(a4), true + } }