| 1 | package tap |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "maps" |
| 6 | "math" |
| 7 | "net" |
| 8 | "sync" |
| 9 | |
| 10 | "github.com/apparentlymart/go-cidr/cidr" |
| 11 | ) |
| 12 | |
| 13 | type IPPool struct { |
| 14 | base *net.IPNet |
| 15 | count uint64 |
| 16 | leases map[string]string |
| 17 | lock sync.Mutex |
| 18 | } |
| 19 | |
| 20 | func NewIPPool(base *net.IPNet) *IPPool { |
| 21 | return &IPPool{ |
| 22 | base: base, |
| 23 | count: cidr.AddressCount(base), |
| 24 | leases: make(map[string]string), |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | func (p *IPPool) Leases() map[string]string { |
| 29 | p.lock.Lock() |
| 30 | defer p.lock.Unlock() |
| 31 | leases := map[string]string{} |
| 32 | maps.Copy(leases, p.leases) |
| 33 | return leases |
| 34 | } |
| 35 | |
| 36 | func (p *IPPool) Mask() int { |
| 37 | ones, _ := p.base.Mask.Size() |
| 38 | return ones |
| 39 | } |
| 40 | |
| 41 | func (p *IPPool) GetOrAssign(mac string) (net.IP, error) { |
| 42 | p.lock.Lock() |
| 43 | defer p.lock.Unlock() |
| 44 | |
| 45 | for ip, candidate := range p.leases { |
| 46 | if candidate == mac { |
| 47 | return net.ParseIP(ip), nil |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | if p.count > math.MaxInt { |
| 52 | return nil, errors.New("IP pool exceeds maximum number of IP addresses") |
| 53 | } |
| 54 | for i := 1; i < int(p.count); i++ { |
| 55 | candidate, err := cidr.Host(p.base, i) |
| 56 | if err != nil { |
| 57 | continue |
| 58 | } |
| 59 | if _, ok := p.leases[candidate.String()]; !ok { |
| 60 | p.leases[candidate.String()] = mac |
| 61 | return candidate, nil |
| 62 | } |
| 63 | } |
| 64 | return nil, errors.New("cannot find available IP") |
| 65 | } |
| 66 | |
| 67 | func (p *IPPool) Reserve(ip net.IP, mac string) { |
| 68 | p.lock.Lock() |
| 69 | defer p.lock.Unlock() |
| 70 | |
| 71 | p.leases[ip.String()] = mac |
| 72 | } |
| 73 | |
| 74 | func (p *IPPool) Release(given string) { |
| 75 | p.lock.Lock() |
| 76 | defer p.lock.Unlock() |
| 77 | |
| 78 | var found string |
| 79 | for ip, mac := range p.leases { |
| 80 | if mac == given { |
| 81 | found = ip |
| 82 | break |
| 83 | } |
| 84 | } |
| 85 | if found != "" { |
| 86 | delete(p.leases, found) |
| 87 | } |
| 88 | } |