remote_list.go 19 KB

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