Skip to content

Commit

Permalink
peer`s alias is unique now
Browse files Browse the repository at this point in the history
  • Loading branch information
GrigoryKrasnochub committed Oct 24, 2022
1 parent a27fb42 commit 1efac94
Show file tree
Hide file tree
Showing 9 changed files with 180 additions and 50 deletions.
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"))
}

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
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()
_, ok := c.peersUniqAliases[alias]
if !ok {
c.peersUniqAliases[alias] = struct{}{}
}
c.Unlock()
return !ok
}

func (c *Config) GenUniqPeerAlias(name, alias string) string {
c.Lock()
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)
peer.Alias = newAlias
}
if peer.IPAddr == "" {
peer.IPAddr = conf.GenerateNextIpAddr()
}
Expand Down
108 changes: 73 additions & 35 deletions docs/swagger.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,49 +18,63 @@ definitions:
type: object
config.Config:
properties:
bucketSize:
type: integer
concurrency:
connManager: {}
connectionGater: {}
disablePing:
type: boolean
enableAutoRelay:
type: boolean
enableService:
type: boolean
forceReachability:
type: integer
datastore: {}
disableFixLowPeers:
description: test specific Config options
insecure:
type: boolean
enableProviders:
listenAddrs:
items: {}
type: array
multiaddrResolver:
$ref: '#/definitions/madns.Resolver'
muxers:
items:
$ref: '#/definitions/config.MsMuxC'
type: array
peerKey: {}
peerstore: {}
psk:
items:
type: integer
type: array
relay:
type: boolean
enableValues:
relayCustom:
type: boolean
maxRecordAge:
relayOpts:
items:
type: integer
type: array
reporter: {}
securityTransports:
items:
$ref: '#/definitions/config.MsSecC'
type: array
staticRelays:
items:
$ref: '#/definitions/peer.AddrInfo'
type: array
throttleGlobalLimit:
type: integer
mode:
throttleInterval:
type: integer
protocolPrefix:
type: string
resiliency:
throttlePeerLimit:
type: integer
routingTable:
properties:
autoRefresh:
type: boolean
checkInterval:
type: integer
diversityFilter: {}
latencyTolerance:
type: integer
refreshInterval:
type: integer
refreshQueryTimeout:
type: integer
type: object
testAddressUpdateProcessing:
type: boolean
v1ProtocolOverride:
userAgent:
description: |-
UserAgent is the identifier this node will send to other peers when
identifying itself, e.g. via the identify protocol.
Set it via the UserAgent option function.
type: string
validator: {}
validatorChanged:
description: if true implies that the validator has been changed and that
Defaults should not be used
type: boolean
type: object
config.KnownPeer:
properties:
Expand Down Expand Up @@ -92,6 +106,16 @@ definitions:
description: Hex-encoded multihash representing a peer ID
type: string
type: object
config.MsMuxC:
properties:
id:
type: string
type: object
config.MsSecC:
properties:
id:
type: string
type: object
entity.AuthRequest:
properties:
name:
Expand Down Expand Up @@ -170,6 +194,7 @@ definitions:
peerID:
type: string
required:
- alias
- peerID
type: object
entity.FriendRequestReply:
Expand All @@ -181,6 +206,7 @@ definitions:
peerID:
type: string
required:
- alias
- peerID
type: object
entity.GeneralDebugInfo:
Expand All @@ -205,6 +231,7 @@ definitions:
declined:
type: boolean
displayName:
description: 'Deprecated: useless, equal to Alias all the time'
type: string
domainName:
type: string
Expand Down Expand Up @@ -296,6 +323,7 @@ definitions:
peerID:
type: string
required:
- alias
- peerID
type: object
kbucket.PeerInfo:
Expand All @@ -316,6 +344,8 @@ definitions:
Please see the DHT docs for the definition of usefulness.
type: string
type: object
madns.Resolver:
type: object
metrics.Stats:
properties:
rateIn:
Expand Down Expand Up @@ -355,6 +385,14 @@ definitions:
transient:
type: boolean
type: object
peer.AddrInfo:
properties:
addrs:
items: {}
type: array
id:
type: string
type: object
host: localhost:8639
info:
contact: {}
Expand Down
8 changes: 4 additions & 4 deletions entity/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,19 @@ type (
}
FriendRequest struct {
PeerID string `validate:"required"`
Alias string
Alias string `validate:"required,trimmed_str_not_empty"`
}
FriendRequestReply struct {
PeerID string `validate:"required"`
Alias string
Alias string `validate:"required,trimmed_str_not_empty"`
Decline bool
}
PeerIDRequest struct {
PeerID string `validate:"required"`
}
UpdatePeerSettingsRequest struct {
PeerID string `validate:"required"`
Alias string
Alias string `validate:"required,trimmed_str_not_empty"`
DomainName string
}
UpdateMySettingsRequest struct {
Expand All @@ -42,7 +42,7 @@ type (
KnownPeersResponse struct {
PeerID string
Name string // Deprecated: use DisplayName instead
DisplayName string
DisplayName string // Deprecated: useless, equal to Alias all the time
Alias string
Version string
IpAddr string
Expand Down
Loading

0 comments on commit 1efac94

Please sign in to comment.