Debian Codegraph @

remote_list.go

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