package db import ( "net/netip" "sort" ) // SubnetOutside is the group name of an address that matches no configured // subnet (or is not an IP address at all). const SubnetOutside = "вне списка подсетей" // SubnetMatcher maps an address to the most specific configured subnet. type SubnetMatcher struct { list []subnetEntry } type subnetEntry struct { p netip.Prefix label string } // NewSubnetMatcher builds a matcher from the administrator's subnet list. // Entries that are not valid CIDR are skipped. func NewSubnetMatcher(subnets []Subnet) *SubnetMatcher { m := &SubnetMatcher{} for _, s := range subnets { if p, err := netip.ParsePrefix(s.CIDR); err == nil { m.list = append(m.list, subnetEntry{p.Masked(), s.Label}) } } sort.SliceStable(m.list, func(i, j int) bool { return m.list[i].p.Bits() > m.list[j].p.Bits() }) return m } // Lookup returns the CIDR and the label of the most specific subnet that // contains ip. With an empty list the address is grouped by /24 (/64 for // IPv6) without a label. An address outside the list gets SubnetOutside. func (m *SubnetMatcher) Lookup(ip string) (cidr, label string) { a, err := netip.ParseAddr(ip) if err != nil { return SubnetOutside, "" } if len(m.list) == 0 { bits := 24 if a.Is6() { bits = 64 } p, _ := a.Prefix(bits) return p.String(), "" } for _, e := range m.list { if e.p.Contains(a) { return e.p.String(), e.label } } return SubnetOutside, "" }