chore(stdiscosrv): ensure incoming addresses are sorted and unique

This commit is contained in:
Jakob Borg 2024-09-15 17:00:32 +02:00
parent 8b19cb1e11
commit 5b9d8a838f
No known key found for this signature in database
2 changed files with 10 additions and 4 deletions

View File

@ -307,16 +307,17 @@ func (s *apiSrv) handleAnnounce(deviceID protocol.DeviceID, addresses []string)
now := time.Now() now := time.Now()
expire := now.Add(addressExpiryTime).UnixNano() expire := now.Add(addressExpiryTime).UnixNano()
// The address slice must always be sorted for database merges to work
// properly.
slices.Sort(addresses)
addresses = slices.Compact(addresses)
dbAddrs := make([]DatabaseAddress, len(addresses)) dbAddrs := make([]DatabaseAddress, len(addresses))
for i := range addresses { for i := range addresses {
dbAddrs[i].Address = addresses[i] dbAddrs[i].Address = addresses[i]
dbAddrs[i].Expires = expire dbAddrs[i].Expires = expire
} }
// The address slice must always be sorted for database merges to work
// properly.
slices.SortFunc(dbAddrs, DatabaseAddress.Cmp)
seen := now.UnixNano() seen := now.UnixNano()
if s.repl != nil { if s.repl != nil {
s.repl.send(&deviceID, dbAddrs, seen) s.repl.send(&deviceID, dbAddrs, seen)

View File

@ -350,6 +350,7 @@ func (s *inMemoryStore) read() (int, error) {
} }
slices.SortFunc(rec.Addresses, DatabaseAddress.Cmp) slices.SortFunc(rec.Addresses, DatabaseAddress.Cmp)
rec.Addresses = slices.CompactFunc(rec.Addresses, DatabaseAddress.Equal)
s.m.Store(key, DatabaseRecord{ s.m.Store(key, DatabaseRecord{
Addresses: expire(rec.Addresses, s.clock.Now()), Addresses: expire(rec.Addresses, s.clock.Now()),
Seen: rec.Seen, Seen: rec.Seen,
@ -420,3 +421,7 @@ func (d DatabaseAddress) Cmp(other DatabaseAddress) (n int) {
} }
return cmp.Compare(d.Expires, other.Expires) return cmp.Compare(d.Expires, other.Expires)
} }
func (d DatabaseAddress) Equal(other DatabaseAddress) bool {
return d.Address == other.Address
}