From 5b9d8a838f681baaf32564b9586e885e469659c7 Mon Sep 17 00:00:00 2001 From: Jakob Borg Date: Sun, 15 Sep 2024 17:00:32 +0200 Subject: [PATCH] chore(stdiscosrv): ensure incoming addresses are sorted and unique --- cmd/stdiscosrv/apisrv.go | 9 +++++---- cmd/stdiscosrv/database.go | 5 +++++ 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/cmd/stdiscosrv/apisrv.go b/cmd/stdiscosrv/apisrv.go index fced38e09..96bfce75c 100644 --- a/cmd/stdiscosrv/apisrv.go +++ b/cmd/stdiscosrv/apisrv.go @@ -307,16 +307,17 @@ func (s *apiSrv) handleAnnounce(deviceID protocol.DeviceID, addresses []string) now := time.Now() 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)) for i := range addresses { dbAddrs[i].Address = addresses[i] 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() if s.repl != nil { s.repl.send(&deviceID, dbAddrs, seen) diff --git a/cmd/stdiscosrv/database.go b/cmd/stdiscosrv/database.go index 4f2379c58..2a796848a 100644 --- a/cmd/stdiscosrv/database.go +++ b/cmd/stdiscosrv/database.go @@ -350,6 +350,7 @@ func (s *inMemoryStore) read() (int, error) { } slices.SortFunc(rec.Addresses, DatabaseAddress.Cmp) + rec.Addresses = slices.CompactFunc(rec.Addresses, DatabaseAddress.Equal) s.m.Store(key, DatabaseRecord{ Addresses: expire(rec.Addresses, s.clock.Now()), Seen: rec.Seen, @@ -420,3 +421,7 @@ func (d DatabaseAddress) Cmp(other DatabaseAddress) (n int) { } return cmp.Compare(d.Expires, other.Expires) } + +func (d DatabaseAddress) Equal(other DatabaseAddress) bool { + return d.Address == other.Address +}