| giolekva | d12813b | 2021-05-01 19:58:44 +0400 | [diff] [blame] | 1 | package vpn |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | |
| 6 | "github.com/giolekva/pcloud/core/vpn/types" |
| 7 | |
| 8 | "inet.af/netaddr" |
| 9 | ) |
| 10 | |
| 11 | // TODO(giolekva): Add Disable method which marks given IP as non-usable for future. |
| 12 | // It will be used when devices get removed from the network, in which case IP should not be reused for safety reasons. |
| 13 | type IPManager interface { |
| 14 | New(pubKey types.PublicKey) (netaddr.IP, error) |
| 15 | Get(pubKey types.PublicKey) (netaddr.IP, error) |
| 16 | } |
| 17 | |
| 18 | type SequentialIPManager struct { |
| 19 | cur netaddr.IP |
| 20 | keyToIP map[types.PublicKey]netaddr.IP |
| 21 | } |
| 22 | |
| 23 | func NewSequentialIPManager(start netaddr.IP) IPManager { |
| 24 | return &SequentialIPManager{ |
| 25 | cur: start, |
| 26 | keyToIP: make(map[types.PublicKey]netaddr.IP), |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | func (m *SequentialIPManager) New(pubKey types.PublicKey) (netaddr.IP, error) { |
| 31 | ip := m.cur |
| 32 | if _, ok := m.keyToIP[pubKey]; ok { |
| 33 | return netaddr.IP{}, fmt.Errorf("Device with public key %s has already been assigned IP", pubKey) |
| 34 | } |
| 35 | m.keyToIP[pubKey] = ip |
| 36 | m.cur = m.cur.Next() |
| 37 | return ip, nil |
| 38 | } |
| 39 | |
| 40 | func (m *SequentialIPManager) Get(pubKey types.PublicKey) (netaddr.IP, error) { |
| 41 | if ip, ok := m.keyToIP[pubKey]; ok { |
| 42 | return ip, nil |
| 43 | } |
| 44 | return netaddr.IP{}, fmt.Errorf("Device with public key %s pubKey does not have VPN IP assigned.", pubKey) |
| 45 | } |