1
0

remote_list.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  1. package nebula
  2. import (
  3. "context"
  4. "log/slog"
  5. "net"
  6. "net/netip"
  7. "slices"
  8. "sort"
  9. "strconv"
  10. "sync"
  11. "sync/atomic"
  12. "time"
  13. )
  14. // forEachFunc is used to benefit folks that want to do work inside the lock
  15. type forEachFunc func(addr netip.AddrPort, preferred bool)
  16. // The checkFuncs here are to simplify bulk importing LH query response logic into a single function (reset slice and iterate)
  17. type checkFuncV4 func(vpnIp netip.Addr, to *V4AddrPort) bool
  18. type checkFuncV6 func(vpnIp netip.Addr, to *V6AddrPort) bool
  19. // CacheMap is a struct that better represents the lighthouse cache for humans
  20. // The string key is the owners vpnIp
  21. type CacheMap map[string]*Cache
  22. // Cache is the other part of CacheMap to better represent the lighthouse cache for humans
  23. // We don't reason about ipv4 vs ipv6 here
  24. type Cache struct {
  25. Learned []netip.AddrPort `json:"learned,omitempty"`
  26. Reported []netip.AddrPort `json:"reported,omitempty"`
  27. Relay []netip.Addr `json:"relay"`
  28. }
  29. // cache is an internal struct that splits v4 and v6 addresses inside the cache map
  30. type cache struct {
  31. v4 *cacheV4
  32. v6 *cacheV6
  33. relay *cacheRelay
  34. }
  35. type cacheRelay struct {
  36. relay []netip.Addr
  37. }
  38. // cacheV4 stores learned and reported ipv4 records under cache
  39. type cacheV4 struct {
  40. learned *V4AddrPort
  41. reported []*V4AddrPort
  42. }
  43. // cacheV4 stores learned and reported ipv6 records under cache
  44. type cacheV6 struct {
  45. learned *V6AddrPort
  46. reported []*V6AddrPort
  47. }
  48. type hostnamePort struct {
  49. name string
  50. port uint16
  51. }
  52. type hostnamesResults struct {
  53. hostnames []hostnamePort
  54. network string
  55. lookupTimeout time.Duration
  56. cancelFn func()
  57. l *slog.Logger
  58. ips atomic.Pointer[map[netip.AddrPort]struct{}]
  59. }
  60. func NewHostnameResults(ctx context.Context, l *slog.Logger, d time.Duration, network string, timeout time.Duration, hostPorts []string, onUpdate func()) (*hostnamesResults, error) {
  61. r := &hostnamesResults{
  62. hostnames: make([]hostnamePort, len(hostPorts)),
  63. network: network,
  64. lookupTimeout: timeout,
  65. l: l,
  66. }
  67. // Fastrack IP addresses to ensure they're immediately available for use.
  68. // DNS lookups for hostnames that aren't hardcoded IP's will happen in a background goroutine.
  69. performBackgroundLookup := false
  70. ips := map[netip.AddrPort]struct{}{}
  71. for idx, hostPort := range hostPorts {
  72. rIp, sPort, err := net.SplitHostPort(hostPort)
  73. if err != nil {
  74. return nil, err
  75. }
  76. iPort, err := strconv.Atoi(sPort)
  77. if err != nil {
  78. return nil, err
  79. }
  80. r.hostnames[idx] = hostnamePort{name: rIp, port: uint16(iPort)}
  81. addr, err := netip.ParseAddr(rIp)
  82. if err != nil {
  83. // This address is a hostname, not an IP address
  84. performBackgroundLookup = true
  85. continue
  86. }
  87. // Save the IP address immediately
  88. ips[netip.AddrPortFrom(addr, uint16(iPort))] = struct{}{}
  89. }
  90. r.ips.Store(&ips)
  91. // Time for the DNS lookup goroutine
  92. if performBackgroundLookup {
  93. newCtx, cancel := context.WithCancel(ctx)
  94. r.cancelFn = cancel
  95. ticker := time.NewTicker(d)
  96. go func() {
  97. defer ticker.Stop()
  98. for {
  99. netipAddrs := map[netip.AddrPort]struct{}{}
  100. for _, hostPort := range r.hostnames {
  101. timeoutCtx, timeoutCancel := context.WithTimeout(ctx, r.lookupTimeout)
  102. addrs, err := net.DefaultResolver.LookupNetIP(timeoutCtx, r.network, hostPort.name)
  103. timeoutCancel()
  104. if err != nil {
  105. l.Error("DNS resolution failed for static_map host",
  106. "hostname", hostPort.name,
  107. "network", r.network,
  108. "error", err,
  109. )
  110. continue
  111. }
  112. for _, a := range addrs {
  113. netipAddrs[netip.AddrPortFrom(a.Unmap(), hostPort.port)] = struct{}{}
  114. }
  115. }
  116. origSet := r.ips.Load()
  117. different := false
  118. for a := range *origSet {
  119. if _, ok := netipAddrs[a]; !ok {
  120. different = true
  121. break
  122. }
  123. }
  124. if !different {
  125. for a := range netipAddrs {
  126. if _, ok := (*origSet)[a]; !ok {
  127. different = true
  128. break
  129. }
  130. }
  131. }
  132. if different {
  133. l.Info("DNS results changed for host list",
  134. "origSet", origSet,
  135. "newSet", netipAddrs,
  136. )
  137. r.ips.Store(&netipAddrs)
  138. onUpdate()
  139. }
  140. select {
  141. case <-newCtx.Done():
  142. return
  143. case <-ticker.C:
  144. continue
  145. }
  146. }
  147. }()
  148. }
  149. return r, nil
  150. }
  151. func (hr *hostnamesResults) Cancel() {
  152. if hr != nil && hr.cancelFn != nil {
  153. hr.cancelFn()
  154. }
  155. }
  156. func (hr *hostnamesResults) GetAddrs() []netip.AddrPort {
  157. var retSlice []netip.AddrPort
  158. if hr != nil {
  159. p := hr.ips.Load()
  160. if p != nil {
  161. for k := range *p {
  162. retSlice = append(retSlice, k)
  163. }
  164. }
  165. }
  166. return retSlice
  167. }
  168. // RemoteList is a unifying concept for lighthouse servers and clients as well as hostinfos.
  169. // It serves as a local cache of query replies, host update notifications, and locally learned addresses
  170. type RemoteList struct {
  171. // Every interaction with internals requires a lock!
  172. sync.RWMutex
  173. // The full list of vpn addresses assigned to this host
  174. vpnAddrs []netip.Addr
  175. // A deduplicated set of underlay addresses. Any accessor should lock beforehand.
  176. addrs []netip.AddrPort
  177. // A set of relay addresses. VpnIp addresses that the remote identified as relays.
  178. relays []netip.Addr
  179. // These are maps to store v4 and v6 addresses per lighthouse
  180. // Map key is the vpnIp of the person that told us about this the cached entries underneath.
  181. // For learned addresses, this is the vpnIp that sent the packet
  182. cache map[netip.Addr]*cache
  183. hr *hostnamesResults
  184. // shouldAdd is a nillable function that decides if x should be added to addrs.
  185. shouldAdd func(vpnAddrs []netip.Addr, x netip.Addr) bool
  186. // This is a list of remotes that we have tried to handshake with and have returned from the wrong vpn ip.
  187. // They should not be tried again during a handshake
  188. badRemotes []netip.AddrPort
  189. // A flag that the cache may have changed and addrs needs to be rebuilt
  190. shouldRebuild bool
  191. }
  192. // NewRemoteList creates a new empty RemoteList
  193. func NewRemoteList(vpnAddrs []netip.Addr, shouldAdd func([]netip.Addr, netip.Addr) bool) *RemoteList {
  194. r := &RemoteList{
  195. vpnAddrs: make([]netip.Addr, len(vpnAddrs)),
  196. addrs: make([]netip.AddrPort, 0),
  197. relays: make([]netip.Addr, 0),
  198. cache: make(map[netip.Addr]*cache),
  199. shouldAdd: shouldAdd,
  200. }
  201. copy(r.vpnAddrs, vpnAddrs)
  202. return r
  203. }
  204. func (r *RemoteList) unlockedSetHostnamesResults(hr *hostnamesResults) {
  205. // Cancel any existing hostnamesResults DNS goroutine to release resources
  206. r.hr.Cancel()
  207. r.hr = hr
  208. }
  209. // ResetForOwner zeros the reported address slices for the given owner and marks the addrs list dirty.
  210. // Any pending hostname resolution will be canceled.
  211. func (r *RemoteList) ResetForOwner(ownerVpnAddr netip.Addr) {
  212. r.Lock()
  213. defer r.Unlock()
  214. r.hr.Cancel()
  215. if c, ok := r.cache[ownerVpnAddr]; ok {
  216. if c.v4 != nil {
  217. c.v4.reported = c.v4.reported[:0]
  218. }
  219. if c.v6 != nil {
  220. c.v6.reported = c.v6.reported[:0]
  221. }
  222. }
  223. r.shouldRebuild = true
  224. }
  225. // ClearHostnameResults cancels the in-flight DNS resolver goroutine (if any) and drops the resolved IP cache.
  226. func (r *RemoteList) ClearHostnameResults() {
  227. r.Lock()
  228. defer r.Unlock()
  229. r.unlockedSetHostnamesResults(nil)
  230. r.shouldRebuild = true
  231. }
  232. // Len locks and reports the size of the deduplicated address list
  233. // The deduplication work may need to occur here, so you must pass preferredRanges
  234. func (r *RemoteList) Len(preferredRanges []netip.Prefix) int {
  235. r.Rebuild(preferredRanges)
  236. r.RLock()
  237. defer r.RUnlock()
  238. return len(r.addrs)
  239. }
  240. // ForEach locks and will call the forEachFunc for every deduplicated address in the list
  241. // The deduplication work may need to occur here, so you must pass preferredRanges
  242. func (r *RemoteList) ForEach(preferredRanges []netip.Prefix, forEach forEachFunc) {
  243. r.Rebuild(preferredRanges)
  244. r.RLock()
  245. for _, v := range r.addrs {
  246. forEach(v, isPreferred(v.Addr(), preferredRanges))
  247. }
  248. r.RUnlock()
  249. }
  250. // CopyAddrs locks and makes a deep copy of the deduplicated address list
  251. // The deduplication work may need to occur here, so you must pass preferredRanges
  252. func (r *RemoteList) CopyAddrs(preferredRanges []netip.Prefix) []netip.AddrPort {
  253. if r == nil {
  254. return nil
  255. }
  256. r.Rebuild(preferredRanges)
  257. r.RLock()
  258. defer r.RUnlock()
  259. c := make([]netip.AddrPort, len(r.addrs))
  260. for i, v := range r.addrs {
  261. c[i] = v
  262. }
  263. return c
  264. }
  265. // LearnRemote locks and sets the learned slot for the owner vpn ip to the provided addr
  266. // Currently this is only needed when HostInfo.SetRemote is called as that should cover both handshaking and roaming.
  267. // It will mark the deduplicated address list as dirty, so do not call it unless new information is available
  268. func (r *RemoteList) LearnRemote(ownerVpnIp netip.Addr, remote netip.AddrPort) {
  269. r.Lock()
  270. defer r.Unlock()
  271. if remote.Addr().Is4() {
  272. r.unlockedSetLearnedV4(ownerVpnIp, netAddrToProtoV4AddrPort(remote.Addr(), remote.Port()))
  273. } else {
  274. r.unlockedSetLearnedV6(ownerVpnIp, netAddrToProtoV6AddrPort(remote.Addr(), remote.Port()))
  275. }
  276. }
  277. // CopyCache locks and creates a more human friendly form of the internal address cache.
  278. // This may contain duplicates and blocked addresses
  279. func (r *RemoteList) CopyCache() *CacheMap {
  280. r.RLock()
  281. defer r.RUnlock()
  282. cm := make(CacheMap)
  283. getOrMake := func(vpnIp string) *Cache {
  284. c := cm[vpnIp]
  285. if c == nil {
  286. c = &Cache{
  287. Learned: make([]netip.AddrPort, 0),
  288. Reported: make([]netip.AddrPort, 0),
  289. Relay: make([]netip.Addr, 0),
  290. }
  291. cm[vpnIp] = c
  292. }
  293. return c
  294. }
  295. for owner, mc := range r.cache {
  296. c := getOrMake(owner.String())
  297. if mc.v4 != nil {
  298. if mc.v4.learned != nil {
  299. c.Learned = append(c.Learned, protoV4AddrPortToNetAddrPort(mc.v4.learned))
  300. }
  301. for _, a := range mc.v4.reported {
  302. c.Reported = append(c.Reported, protoV4AddrPortToNetAddrPort(a))
  303. }
  304. }
  305. if mc.v6 != nil {
  306. if mc.v6.learned != nil {
  307. c.Learned = append(c.Learned, protoV6AddrPortToNetAddrPort(mc.v6.learned))
  308. }
  309. for _, a := range mc.v6.reported {
  310. c.Reported = append(c.Reported, protoV6AddrPortToNetAddrPort(a))
  311. }
  312. }
  313. if mc.relay != nil {
  314. for _, a := range mc.relay.relay {
  315. c.Relay = append(c.Relay, a)
  316. }
  317. }
  318. }
  319. return &cm
  320. }
  321. // BlockRemote locks and records the address as bad, it will be excluded from the deduplicated address list
  322. func (r *RemoteList) BlockRemote(bad ViaSender) {
  323. if bad.IsRelayed {
  324. return
  325. }
  326. r.Lock()
  327. defer r.Unlock()
  328. // Check if we already blocked this addr
  329. if r.unlockedIsBad(bad.UdpAddr) {
  330. return
  331. }
  332. // We copy here because we are taking something else's memory and we can't trust everything
  333. r.badRemotes = append(r.badRemotes, bad.UdpAddr)
  334. // Mark the next interaction must recollect/dedupe
  335. r.shouldRebuild = true
  336. }
  337. // CopyBlockedRemotes locks and makes a deep copy of the blocked remotes list
  338. func (r *RemoteList) CopyBlockedRemotes() []netip.AddrPort {
  339. r.RLock()
  340. defer r.RUnlock()
  341. c := make([]netip.AddrPort, len(r.badRemotes))
  342. for i, v := range r.badRemotes {
  343. c[i] = v
  344. }
  345. return c
  346. }
  347. // RefreshFromHandshake locks and updates the RemoteList to account for data learned upon a completed handshake
  348. func (r *RemoteList) RefreshFromHandshake(vpnAddrs []netip.Addr) {
  349. r.Lock()
  350. r.badRemotes = nil
  351. r.vpnAddrs = make([]netip.Addr, len(vpnAddrs))
  352. copy(r.vpnAddrs, vpnAddrs)
  353. r.Unlock()
  354. }
  355. // ResetBlockedRemotes locks and clears the blocked remotes list
  356. func (r *RemoteList) ResetBlockedRemotes() {
  357. r.Lock()
  358. r.badRemotes = nil
  359. r.Unlock()
  360. }
  361. // Rebuild locks and generates the deduplicated address list only if there is work to be done
  362. // There is generally no reason to call this directly but it is safe to do so
  363. func (r *RemoteList) Rebuild(preferredRanges []netip.Prefix) {
  364. r.Lock()
  365. defer r.Unlock()
  366. // Only rebuild if the cache changed
  367. if r.shouldRebuild {
  368. r.unlockedCollect()
  369. r.shouldRebuild = false
  370. }
  371. // Always re-sort, preferredRanges can change via HUP
  372. r.unlockedSort(preferredRanges)
  373. }
  374. // unlockedIsBad assumes you have the write lock and checks if the remote matches any entry in the blocked address list
  375. func (r *RemoteList) unlockedIsBad(remote netip.AddrPort) bool {
  376. return slices.Contains(r.badRemotes, remote)
  377. }
  378. // unlockedSetLearnedV4 assumes you have the write lock and sets the current learned address for this owner and marks the
  379. // deduplicated address list as dirty
  380. func (r *RemoteList) unlockedSetLearnedV4(ownerVpnIp netip.Addr, to *V4AddrPort) {
  381. r.shouldRebuild = true
  382. r.unlockedGetOrMakeV4(ownerVpnIp).learned = to
  383. }
  384. // unlockedSetV4 assumes you have the write lock and resets the reported list of ips for this owner to the list provided
  385. // and marks the deduplicated address list as dirty
  386. func (r *RemoteList) unlockedSetV4(ownerVpnIp, vpnIp netip.Addr, to []*V4AddrPort, check checkFuncV4) {
  387. r.shouldRebuild = true
  388. c := r.unlockedGetOrMakeV4(ownerVpnIp)
  389. // Reset the slice
  390. c.reported = c.reported[:0]
  391. // We can't take their array but we can take their pointers
  392. for _, v := range to[:minInt(len(to), MaxRemotes)] {
  393. if check(vpnIp, v) {
  394. c.reported = append(c.reported, v)
  395. }
  396. }
  397. }
  398. func (r *RemoteList) unlockedSetRelay(ownerVpnIp netip.Addr, to []netip.Addr) {
  399. r.shouldRebuild = true
  400. c := r.unlockedGetOrMakeRelay(ownerVpnIp)
  401. // Reset the slice
  402. c.relay = c.relay[:0]
  403. // We can't take their array but we can take their pointers
  404. c.relay = append(c.relay, to[:minInt(len(to), MaxRemotes)]...)
  405. }
  406. // unlockedPrependV4 assumes you have the write lock and prepends the address in the reported list for this owner
  407. // This is only useful for establishing static hosts
  408. func (r *RemoteList) unlockedPrependV4(ownerVpnIp netip.Addr, to *V4AddrPort) {
  409. r.shouldRebuild = true
  410. c := r.unlockedGetOrMakeV4(ownerVpnIp)
  411. // We are doing the easy append because this is rarely called
  412. c.reported = append([]*V4AddrPort{to}, c.reported...)
  413. if len(c.reported) > MaxRemotes {
  414. c.reported = c.reported[:MaxRemotes]
  415. }
  416. }
  417. // unlockedSetLearnedV6 assumes you have the write lock and sets the current learned address for this owner and marks the
  418. // deduplicated address list as dirty
  419. func (r *RemoteList) unlockedSetLearnedV6(ownerVpnIp netip.Addr, to *V6AddrPort) {
  420. r.shouldRebuild = true
  421. r.unlockedGetOrMakeV6(ownerVpnIp).learned = to
  422. }
  423. // unlockedSetV6 assumes you have the write lock and resets the reported list of ips for this owner to the list provided
  424. // and marks the deduplicated address list as dirty
  425. func (r *RemoteList) unlockedSetV6(ownerVpnIp, vpnIp netip.Addr, to []*V6AddrPort, check checkFuncV6) {
  426. r.shouldRebuild = true
  427. c := r.unlockedGetOrMakeV6(ownerVpnIp)
  428. // Reset the slice
  429. c.reported = c.reported[:0]
  430. // We can't take their array but we can take their pointers
  431. for _, v := range to[:minInt(len(to), MaxRemotes)] {
  432. if check(vpnIp, v) {
  433. c.reported = append(c.reported, v)
  434. }
  435. }
  436. }
  437. // unlockedPrependV6 assumes you have the write lock and prepends the address in the reported list for this owner
  438. // This is only useful for establishing static hosts
  439. func (r *RemoteList) unlockedPrependV6(ownerVpnIp netip.Addr, to *V6AddrPort) {
  440. r.shouldRebuild = true
  441. c := r.unlockedGetOrMakeV6(ownerVpnIp)
  442. // We are doing the easy append because this is rarely called
  443. c.reported = append([]*V6AddrPort{to}, c.reported...)
  444. if len(c.reported) > MaxRemotes {
  445. c.reported = c.reported[:MaxRemotes]
  446. }
  447. }
  448. func (r *RemoteList) unlockedGetOrMakeRelay(ownerVpnIp netip.Addr) *cacheRelay {
  449. am := r.cache[ownerVpnIp]
  450. if am == nil {
  451. am = &cache{}
  452. r.cache[ownerVpnIp] = am
  453. }
  454. // Avoid occupying memory for relay if we never have any
  455. if am.relay == nil {
  456. am.relay = &cacheRelay{}
  457. }
  458. return am.relay
  459. }
  460. // unlockedGetOrMakeV4 assumes you have the write lock and builds the cache and owner entry. Only the v4 pointer is established.
  461. // The caller must dirty the learned address cache if required
  462. func (r *RemoteList) unlockedGetOrMakeV4(ownerVpnIp netip.Addr) *cacheV4 {
  463. am := r.cache[ownerVpnIp]
  464. if am == nil {
  465. am = &cache{}
  466. r.cache[ownerVpnIp] = am
  467. }
  468. // Avoid occupying memory for v6 addresses if we never have any
  469. if am.v4 == nil {
  470. am.v4 = &cacheV4{}
  471. }
  472. return am.v4
  473. }
  474. // unlockedGetOrMakeV6 assumes you have the write lock and builds the cache and owner entry. Only the v6 pointer is established.
  475. // The caller must dirty the learned address cache if required
  476. func (r *RemoteList) unlockedGetOrMakeV6(ownerVpnIp netip.Addr) *cacheV6 {
  477. am := r.cache[ownerVpnIp]
  478. if am == nil {
  479. am = &cache{}
  480. r.cache[ownerVpnIp] = am
  481. }
  482. // Avoid occupying memory for v4 addresses if we never have any
  483. if am.v6 == nil {
  484. am.v6 = &cacheV6{}
  485. }
  486. return am.v6
  487. }
  488. // unlockedCollect assumes you have the write lock and collects/transforms the cache into the deduped address list.
  489. // The result of this function can contain duplicates. unlockedSort handles cleaning it.
  490. func (r *RemoteList) unlockedCollect() {
  491. addrs := r.addrs[:0]
  492. relays := r.relays[:0]
  493. for _, c := range r.cache {
  494. if c.v4 != nil {
  495. if c.v4.learned != nil {
  496. u := protoV4AddrPortToNetAddrPort(c.v4.learned)
  497. if !r.unlockedIsBad(u) {
  498. addrs = append(addrs, u)
  499. }
  500. }
  501. for _, v := range c.v4.reported {
  502. u := protoV4AddrPortToNetAddrPort(v)
  503. if !r.unlockedIsBad(u) {
  504. addrs = append(addrs, u)
  505. }
  506. }
  507. }
  508. if c.v6 != nil {
  509. if c.v6.learned != nil {
  510. u := protoV6AddrPortToNetAddrPort(c.v6.learned)
  511. if !r.unlockedIsBad(u) {
  512. addrs = append(addrs, u)
  513. }
  514. }
  515. for _, v := range c.v6.reported {
  516. u := protoV6AddrPortToNetAddrPort(v)
  517. if !r.unlockedIsBad(u) {
  518. addrs = append(addrs, u)
  519. }
  520. }
  521. }
  522. if c.relay != nil {
  523. for _, v := range c.relay.relay {
  524. relays = append(relays, v)
  525. }
  526. }
  527. }
  528. dnsAddrs := r.hr.GetAddrs()
  529. for _, addr := range dnsAddrs {
  530. if r.shouldAdd == nil || r.shouldAdd(r.vpnAddrs, addr.Addr()) {
  531. if !r.unlockedIsBad(addr) {
  532. addrs = append(addrs, addr)
  533. }
  534. }
  535. }
  536. r.addrs = addrs
  537. r.relays = relays
  538. }
  539. // unlockedSort assumes you have the write lock and performs the deduping and sorting of the address list
  540. func (r *RemoteList) unlockedSort(preferredRanges []netip.Prefix) {
  541. // Use a map to deduplicate any relay addresses
  542. dedupedRelays := map[netip.Addr]struct{}{}
  543. for _, relay := range r.relays {
  544. dedupedRelays[relay] = struct{}{}
  545. }
  546. r.relays = r.relays[:0]
  547. for relay := range dedupedRelays {
  548. r.relays = append(r.relays, relay)
  549. }
  550. // Put them in a somewhat consistent order after de-duplication
  551. slices.SortFunc(r.relays, func(a, b netip.Addr) int {
  552. return a.Compare(b)
  553. })
  554. // Now the addrs
  555. n := len(r.addrs)
  556. if n < 2 {
  557. return
  558. }
  559. lessFunc := func(i, j int) bool {
  560. a := r.addrs[i]
  561. b := r.addrs[j]
  562. // Preferred addresses first
  563. aPref := isPreferred(a.Addr(), preferredRanges)
  564. bPref := isPreferred(b.Addr(), preferredRanges)
  565. switch {
  566. case aPref && !bPref:
  567. // If i is preferred and j is not, i is less than j
  568. return true
  569. case !aPref && bPref:
  570. // If j is preferred then i is not due to the else, i is not less than j
  571. return false
  572. default:
  573. // Both i an j are either preferred or not, sort within that
  574. }
  575. // ipv6 addresses 2nd
  576. a4 := a.Addr().Is4()
  577. b4 := b.Addr().Is4()
  578. switch {
  579. case a4 == false && b4 == true:
  580. // If i is v6 and j is v4, i is less than j
  581. return true
  582. case a4 == true && b4 == false:
  583. // If j is v6 and i is v4, i is not less than j
  584. return false
  585. case a4 == true && b4 == true:
  586. // i and j are both ipv4
  587. aPrivate := a.Addr().IsPrivate()
  588. bPrivate := b.Addr().IsPrivate()
  589. switch {
  590. case !aPrivate && bPrivate:
  591. // If i is a public ip (not private) and j is a private ip, i is less then j
  592. return true
  593. case aPrivate && !bPrivate:
  594. // If j is public (not private) then i is private due to the else, i is not less than j
  595. return false
  596. default:
  597. // Both i an j are either public or private, sort within that
  598. }
  599. default:
  600. // Both i an j are either ipv4 or ipv6, sort within that
  601. }
  602. // lexical order of ips 3rd
  603. c := a.Addr().Compare(b.Addr())
  604. if c == 0 {
  605. // Ips are the same, Lexical order of ports 4th
  606. return a.Port() < b.Port()
  607. }
  608. // Ip wasn't the same
  609. return c < 0
  610. }
  611. // Sort it
  612. sort.Slice(r.addrs, lessFunc)
  613. // Deduplicate
  614. a, b := 0, 1
  615. for b < n {
  616. if r.addrs[a] != r.addrs[b] {
  617. a++
  618. if a != b {
  619. r.addrs[a], r.addrs[b] = r.addrs[b], r.addrs[a]
  620. }
  621. }
  622. b++
  623. }
  624. r.addrs = r.addrs[:a+1]
  625. return
  626. }
  627. // minInt returns the minimum integer of a or b
  628. func minInt(a, b int) int {
  629. if a < b {
  630. return a
  631. }
  632. return b
  633. }
  634. // isPreferred returns true of the ip is contained in the preferredRanges list
  635. func isPreferred(ip netip.Addr, preferredRanges []netip.Prefix) bool {
  636. for _, p := range preferredRanges {
  637. if p.Contains(ip) {
  638. return true
  639. }
  640. }
  641. return false
  642. }