blob: 6758f3ef06d825b2ab7bf6618689f8174c8a8efd [file] [log] [blame]
giolekvad12813b2021-05-01 19:58:44 +04001package vpn
2
3import (
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.
13type IPManager interface {
14 New(pubKey types.PublicKey) (netaddr.IP, error)
15 Get(pubKey types.PublicKey) (netaddr.IP, error)
16}
17
18type SequentialIPManager struct {
19 cur netaddr.IP
20 keyToIP map[types.PublicKey]netaddr.IP
21}
22
23func NewSequentialIPManager(start netaddr.IP) IPManager {
24 return &SequentialIPManager{
25 cur: start,
26 keyToIP: make(map[types.PublicKey]netaddr.IP),
27 }
28}
29
30func (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
40func (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}