From 7e8b66e03d8c7c9ebf3fbb85469a11728079d99a Mon Sep 17 00:00:00 2001 From: Gabriel de Souza Seibel Date: Thu, 27 Jul 2023 03:04:15 -0300 Subject: [PATCH] [NET-353] Solve race condition with "unique" ips (#2461) * Use a lock for getting unique ips * Make getting & setting unique ips atomic * Remove some blank lines * Set addressLock to &sync.Mutex on declaration --- logic/extpeers.go | 3 +++ logic/networks.go | 5 ++++- logic/nodes.go | 4 ++++ 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/logic/extpeers.go b/logic/extpeers.go index b2d99039..6b6e1a71 100644 --- a/logic/extpeers.go +++ b/logic/extpeers.go @@ -154,6 +154,9 @@ func GetExtClientByPubKey(publicKey string, network string) (*models.ExtClient, // CreateExtClient - creates an extclient func CreateExtClient(extclient *models.ExtClient) error { + // lock because we need unique IPs and having it concurrent makes parallel calls result in same "unique" IPs + addressLock.Lock() + defer addressLock.Unlock() if len(extclient.PublicKey) == 0 { privateKey, err := wgtypes.GeneratePrivateKey() diff --git a/logic/networks.go b/logic/networks.go index 102c39d3..61ea17d3 100644 --- a/logic/networks.go +++ b/logic/networks.go @@ -7,6 +7,7 @@ import ( "net" "sort" "strings" + "sync" "github.com/c-robinson/iplib" validator "github.com/go-playground/validator/v10" @@ -147,7 +148,7 @@ func GetNetworkSettings(networkname string) (models.Network, error) { return network, nil } -// UniqueAddress - see if address is unique +// UniqueAddress - get a unique ipv4 address func UniqueAddress(networkName string, reverse bool) (net.IP, error) { add := net.IP{} var network models.Network @@ -424,3 +425,5 @@ func SortNetworks(unsortedNetworks []models.Network) { } // == Private == + +var addressLock = &sync.Mutex{} diff --git a/logic/nodes.go b/logic/nodes.go index c0d79f35..93ed106d 100644 --- a/logic/nodes.go +++ b/logic/nodes.go @@ -460,6 +460,10 @@ func updateProNodeACLS(node *models.Node) error { // createNode - creates a node in database func createNode(node *models.Node) error { + // lock because we need unique IPs and having it concurrent makes parallel calls result in same "unique" IPs + addressLock.Lock() + defer addressLock.Unlock() + host, err := GetHost(node.HostID.String()) if err != nil { return err