Skip to content

Commit

Permalink
Get free profile id to generate ip
Browse files Browse the repository at this point in the history
  • Loading branch information
krim committed Nov 26, 2021
1 parent 9722f35 commit a2a7880
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 9 deletions.
8 changes: 1 addition & 7 deletions cmd/subspace/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -210,18 +210,12 @@ func (c *Config) UpdateProfile(id string, fn func(*Profile) error) error {
return c.save()
}

func (c *Config) AddProfile(userID, name, platform string, ipspeer string, allowedips string) (Profile, error) {
func (c *Config) AddProfile(number int, userID, name, platform, ipspeer, allowedips string) (Profile, error) {
c.Lock()
defer c.Unlock()

id := RandomString(16)

number := 2 // MUST start at 2
for _, p := range c.Profiles {
if p.Number >= number {
number = p.Number + 1
}
}
profile := Profile{
ID: id,
UserID: userID,
Expand Down
6 changes: 4 additions & 2 deletions cmd/subspace/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"net/http"
"os"
"regexp"
"sort"
"strings"

"github.com/crewjam/saml/samlsp"
Expand Down Expand Up @@ -412,7 +413,8 @@ func profileAddHandler(w *Web) {

//if len(config.ListProfiles()) >= maxProfiles {
// Check whether there is a room to assign new IP address or not.
if _, _, err := wgConfig.generateIPAddr(uint32(len(config.ListProfiles()))); err != nil {
firstFreeID := FindFirstFreeID(config.Profiles)
if _, _, err := wgConfig.generateIPAddr(firstFreeID); err != nil {
w.Redirect("/?error=addprofile")
return
}
Expand All @@ -422,7 +424,7 @@ func profileAddHandler(w *Web) {
return
}
}
profile, err := config.AddProfile(userID, name, platform, ipspeer, allowedips)
profile, err := config.AddProfile(int(firstFreeID), userID, name, platform, ipspeer, allowedips)
if err != nil {
logger.Warn(err)
w.Redirect("/?error=addprofile")
Expand Down
34 changes: 34 additions & 0 deletions cmd/subspace/helpers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package main

import "sort"

func FindFirstFreeID(profiles []*Profile) uint32 {
profileIDs := getProfileIDs(profiles)
sort.Slice(profileIDs, func(i, j int) bool {
return profileIDs[i] < profileIDs[j]
})

const minID = 2
if len(profileIDs) == 0 {
return minID
}
maxID := profileIDs[len(profileIDs)-1]
freeID := uint32(maxID + 1)
for i := minID; i < maxID; i++ {
if i != profileIDs[i-minID] {
freeID = uint32(i)
break
}
}

return freeID
}

func getProfileIDs(profiles []*Profile) []int {
var profileIDs = make([]int, len(profiles))
for i, profile := range profiles {
profileIDs[i] = profile.Number
}

return profileIDs
}

0 comments on commit a2a7880

Please sign in to comment.