Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unique peers aliases #54

Merged
merged 3 commits into from
Oct 25, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
peer`s alias is unique now
  • Loading branch information
GrigoryKrasnochub committed Oct 24, 2022
commit bbddc44700db82e477b6cc70792cc3bcdd54e8b3
12 changes: 12 additions & 0 deletions api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"net/http"
http_pprof "net/http/pprof"
"runtime/pprof"
"strings"

"github.com/anywherelan/awl/config"
"github.com/anywherelan/awl/p2p"
Expand Down Expand Up @@ -61,6 +62,11 @@ func (h *Handler) SetupAPI() error {
e.HideBanner = true
e.HidePort = true
val := validator.New()
err := val.RegisterValidation("trimmed_str_not_empty", validateTrimmedStringNotEmpty, false)
if err != nil {
return err
}

e.Validator = &customValidator{validator: val}

// Middleware
Expand Down Expand Up @@ -163,3 +169,9 @@ func (e Error) Error() string {
func ErrorMessage(message string) Error {
return Error{Message: message}
}

func validateTrimmedStringNotEmpty(fl validator.FieldLevel) bool {
str := fl.Field().String()
str = strings.TrimSpace(str)
return len(str) > 0
}
19 changes: 18 additions & 1 deletion api/peers.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package api
import (
"net/http"
"sort"
"strings"

"github.com/anywherelan/awl/awldns"
"github.com/anywherelan/awl/config"
Expand Down Expand Up @@ -112,7 +113,13 @@ func (h *Handler) UpdatePeerSettings(c echo.Context) (err error) {
}
peerID := knownPeer.PeerId()

knownPeer.Alias = req.Alias
req.Alias = strings.TrimSpace(req.Alias)
if h.conf.CheckIsUniqPeerAliasAndCache(req.Alias) {
knownPeer.Alias = req.Alias
} else {
return c.JSON(http.StatusBadRequest, ErrorMessage("peer name is not unique"))
}
pymq marked this conversation as resolved.
Show resolved Hide resolved

knownPeer.DomainName = req.DomainName
h.conf.UpsertPeer(knownPeer)

Expand Down Expand Up @@ -158,6 +165,11 @@ func (h *Handler) SendFriendRequest(c echo.Context) (err error) {
return c.JSON(http.StatusBadRequest, ErrorMessage("Peer has already been added"))
}

req.Alias = strings.TrimSpace(req.Alias)
if !h.conf.CheckIsUniqPeerAliasAndCache(req.Alias) {
return c.JSON(http.StatusBadRequest, ErrorMessage("peer name is not unique"))
}

h.authStatus.AddPeer(h.ctx, peerId, "", req.Alias, false)

return c.NoContent(http.StatusOK)
Expand Down Expand Up @@ -208,6 +220,11 @@ func (h *Handler) AcceptFriend(c echo.Context) (err error) {
return c.NoContent(http.StatusOK)
}

req.Alias = strings.TrimSpace(req.Alias)
if !h.conf.CheckIsUniqPeerAliasAndCache(req.Alias) {
return c.JSON(http.StatusBadRequest, ErrorMessage("peer name is not unique"))
}

h.authStatus.AddPeer(h.ctx, peerId, auth.Name, req.Alias, true)

return c.NoContent(http.StatusOK)
Expand Down
12 changes: 6 additions & 6 deletions application_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ func TestRemovePeer(t *testing.T) {
a.Len(peer2.app.AuthStatus.GetIngoingAuthRequests(), 0)

// Add peer2 from peer1 - should succeed
err = peer1.api.SendFriendRequest(peer2.PeerID(), "")
err = peer1.api.SendFriendRequest(peer2.PeerID(), "peer_2")
a.NoError(err)
time.Sleep(500 * time.Millisecond)

Expand Down Expand Up @@ -113,7 +113,7 @@ func TestDeclinePeerFriendRequest(t *testing.T) {
defer peer2.Close()
ensurePeersAvailableInDHT(a, peer1, peer2)

err := peer1.api.SendFriendRequest(peer2.PeerID(), "")
err := peer1.api.SendFriendRequest(peer2.PeerID(), "peer_2")
a.NoError(err)

var authRequests []entity.AuthRequest
Expand All @@ -122,7 +122,7 @@ func TestDeclinePeerFriendRequest(t *testing.T) {
a.NoError(err)
return len(authRequests) == 1
}, 15*time.Second, 50*time.Millisecond)
err = peer2.api.ReplyFriendRequest(authRequests[0].PeerID, "", true)
err = peer2.api.ReplyFriendRequest(authRequests[0].PeerID, "peer_1", true)
a.NoError(err)

time.Sleep(500 * time.Millisecond)
Expand Down Expand Up @@ -151,7 +151,7 @@ func TestAutoAcceptFriendRequest(t *testing.T) {
peer2.app.Conf.P2pNode.AutoAcceptAuthRequests = true
peer2.app.Conf.Unlock()

err := peer1.api.SendFriendRequest(peer2.PeerID(), "")
err := peer1.api.SendFriendRequest(peer2.PeerID(), "peer_2")
a.NoError(err)

a.Eventually(func() bool {
Expand Down Expand Up @@ -330,7 +330,7 @@ func ensurePeersAvailableInDHT(a *require.Assertions, peer1, peer2 testPeer) {

func makeFriends(a *require.Assertions, peer1, peer2 testPeer) {
ensurePeersAvailableInDHT(a, peer1, peer2)
err := peer1.api.SendFriendRequest(peer2.PeerID(), "")
err := peer1.api.SendFriendRequest(peer2.PeerID(), "peer_2")
a.NoError(err)

var authRequests []entity.AuthRequest
Expand All @@ -339,7 +339,7 @@ func makeFriends(a *require.Assertions, peer1, peer2 testPeer) {
a.NoError(err)
return len(authRequests) == 1
}, 15*time.Second, 50*time.Millisecond)
err = peer2.api.ReplyFriendRequest(authRequests[0].PeerID, "", false)
err = peer2.api.ReplyFriendRequest(authRequests[0].PeerID, "peer_1", false)
a.NoError(err)

time.Sleep(500 * time.Millisecond)
Expand Down
2 changes: 1 addition & 1 deletion cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ func (a *Application) init() {
&cli.StringFlag{
Name: "name",
Usage: "peer name",
Required: false,
Required: true,
},
},
Before: a.initApiConnection,
Expand Down
48 changes: 45 additions & 3 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package config

import (
"encoding/json"
"fmt"
"io/ioutil"
"net"
"path/filepath"
Expand All @@ -25,13 +26,16 @@ const (
// TODO 8989 maybe?
DefaultHTTPPort = 8639
HttpServerDomainName = "admin"

DefaultPeerAlias = "peer"
)

type (
Config struct {
sync.RWMutex `swaggerignore:"true"`
dataDir string
emitter awlevent.Emitter
sync.RWMutex `swaggerignore:"true"`
dataDir string
emitter awlevent.Emitter
peersUniqAliases map[string]struct{}

Version string `json:"version"`
LoggerLevel string `json:"loggerLevel"`
Expand Down Expand Up @@ -97,6 +101,23 @@ func (c *Config) Save() {
c.RUnlock()
}

func (c *Config) CheckIsUniqPeerAliasAndCache(alias string) bool {
c.Lock()
pymq marked this conversation as resolved.
Show resolved Hide resolved
_, ok := c.peersUniqAliases[alias]
if !ok {
c.peersUniqAliases[alias] = struct{}{}
}
c.Unlock()
return !ok
}

func (c *Config) GenUniqPeerAlias(name, alias string) string {
c.Lock()
pymq marked this conversation as resolved.
Show resolved Hide resolved
alias = c.genUniqPeerAlias(name, alias)
c.Unlock()
return alias
}

func (c *Config) KnownPeersIds() []peer.ID {
c.RLock()
ids := make([]peer.ID, 0, len(c.KnownPeers))
Expand All @@ -119,6 +140,7 @@ func (c *Config) RemovePeer(peerID string) (KnownPeer, bool) {
knownPeer, exists := c.KnownPeers[peerID]
if exists {
delete(c.KnownPeers, peerID)
delete(c.peersUniqAliases, knownPeer.Alias)
c.save()
}
c.Unlock()
Expand Down Expand Up @@ -332,6 +354,26 @@ func (c *Config) path() string {
return path
}

func (c *Config) genUniqPeerAlias(name, alias string) string {
if alias == "" {
if name == "" {
alias = DefaultPeerAlias
} else {
alias = name
}
}
if _, ok := c.peersUniqAliases[alias]; ok {
newAlias := ""
for i := 0; ok; i++ {
newAlias = fmt.Sprintf("%s_%d", alias, i)
_, ok = c.peersUniqAliases[newAlias]
}
alias = newAlias
}
c.peersUniqAliases[alias] = struct{}{}
return alias
}

func (kp KnownPeer) PeerId() peer.ID {
peerID, err := peer.Decode(kp.PeerID)
if err != nil {
Expand Down
6 changes: 6 additions & 0 deletions config/other.go
Original file line number Diff line number Diff line change
Expand Up @@ -169,11 +169,17 @@ func setDefaults(conf *Config, bus awlevent.Bus) {
conf.VPNConfig.InterfaceName = defaultInterfaceName
}

conf.peersUniqAliases = make(map[string]struct{})
if conf.KnownPeers == nil {
conf.KnownPeers = make(map[string]KnownPeer)
}
for peerID := range conf.KnownPeers {
peer := conf.KnownPeers[peerID]
newAlias := conf.genUniqPeerAlias(peer.Name, peer.Alias)
if newAlias != peer.Alias {
logger.Warnf("incorrect config: peer alias %s is not unique, updated automaticaly to %s", peer.Alias, newAlias)
pymq marked this conversation as resolved.
Show resolved Hide resolved
peer.Alias = newAlias
}
if peer.IPAddr == "" {
peer.IPAddr = conf.GenerateNextIpAddr()
}
Expand Down
Loading