remote_list.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  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 *V4AddrPort) bool
  17. type checkFuncV6 func(vpnIp netip.Addr, to *V6AddrPort) 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 *V4AddrPort
  42. reported []*V4AddrPort
  43. }
  44. // cacheV4 stores learned and reported ipv6 records under cache
  45. type cacheV6 struct {
  46. learned *V6AddrPort
  47. reported []*V6AddrPort
  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) GetAddrs() []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. // The full list of vpn addresses assigned to this host
  168. vpnAddrs []netip.Addr
  169. // A deduplicated set of addresses. Any accessor should lock beforehand.
  170. addrs []netip.AddrPort
  171. // A set of relay addresses. VpnIp addresses that the remote identified as relays.
  172. relays []netip.Addr
  173. // These are maps to store v4 and v6 addresses per lighthouse
  174. // Map key is the vpnIp of the person that told us about this the cached entries underneath.
  175. // For learned addresses, this is the vpnIp that sent the packet
  176. cache map[netip.Addr]*cache
  177. hr *hostnamesResults
  178. shouldAdd func(netip.Addr) bool
  179. // This is a list of remotes that we have tried to handshake with and have returned from the wrong vpn ip.
  180. // They should not be tried again during a handshake
  181. badRemotes []netip.AddrPort
  182. // A flag that the cache may have changed and addrs needs to be rebuilt
  183. shouldRebuild bool
  184. }
  185. // NewRemoteList creates a new empty RemoteList
  186. func NewRemoteList(vpnAddrs []netip.Addr, shouldAdd func(netip.Addr) bool) *RemoteList {
  187. r := &RemoteList{
  188. vpnAddrs: make([]netip.Addr, len(vpnAddrs)),
  189. addrs: make([]netip.AddrPort, 0),
  190. relays: make([]netip.Addr, 0),
  191. cache: make(map[netip.Addr]*cache),
  192. shouldAdd: shouldAdd,
  193. }
  194. copy(r.vpnAddrs, vpnAddrs)
  195. return r
  196. }
  197. func (r *RemoteList) unlockedSetHostnamesResults(hr *hostnamesResults) {
  198. // Cancel any existing hostnamesResults DNS goroutine to release resources
  199. r.hr.Cancel()
  200. r.hr = hr
  201. }
  202. // Len locks and reports the size of the deduplicated address list
  203. // The deduplication work may need to occur here, so you must pass preferredRanges
  204. func (r *RemoteList) Len(preferredRanges []netip.Prefix) int {
  205. r.Rebuild(preferredRanges)
  206. r.RLock()
  207. defer r.RUnlock()
  208. return len(r.addrs)
  209. }
  210. // ForEach locks and will call the forEachFunc for every deduplicated address in the list
  211. // The deduplication work may need to occur here, so you must pass preferredRanges
  212. func (r *RemoteList) ForEach(preferredRanges []netip.Prefix, forEach forEachFunc) {
  213. r.Rebuild(preferredRanges)
  214. r.RLock()
  215. for _, v := range r.addrs {
  216. forEach(v, isPreferred(v.Addr(), preferredRanges))
  217. }
  218. r.RUnlock()
  219. }
  220. // CopyAddrs locks and makes a deep copy of the deduplicated address list
  221. // The deduplication work may need to occur here, so you must pass preferredRanges
  222. func (r *RemoteList) CopyAddrs(preferredRanges []netip.Prefix) []netip.AddrPort {
  223. if r == nil {
  224. return nil
  225. }
  226. r.Rebuild(preferredRanges)
  227. r.RLock()
  228. defer r.RUnlock()
  229. c := make([]netip.AddrPort, len(r.addrs))
  230. for i, v := range r.addrs {
  231. c[i] = v
  232. }
  233. return c
  234. }
  235. // LearnRemote locks and sets the learned slot for the owner vpn ip to the provided addr
  236. // Currently this is only needed when HostInfo.SetRemote is called as that should cover both handshaking and roaming.
  237. // It will mark the deduplicated address list as dirty, so do not call it unless new information is available
  238. // TODO: this needs to support the allow list list
  239. func (r *RemoteList) LearnRemote(ownerVpnIp netip.Addr, remote netip.AddrPort) {
  240. r.Lock()
  241. defer r.Unlock()
  242. if remote.Addr().Is4() {
  243. r.unlockedSetLearnedV4(ownerVpnIp, netAddrToProtoV4AddrPort(remote.Addr(), remote.Port()))
  244. } else {
  245. r.unlockedSetLearnedV6(ownerVpnIp, netAddrToProtoV6AddrPort(remote.Addr(), remote.Port()))
  246. }
  247. }
  248. // CopyCache locks and creates a more human friendly form of the internal address cache.
  249. // This may contain duplicates and blocked addresses
  250. func (r *RemoteList) CopyCache() *CacheMap {
  251. r.RLock()
  252. defer r.RUnlock()
  253. cm := make(CacheMap)
  254. getOrMake := func(vpnIp string) *Cache {
  255. c := cm[vpnIp]
  256. if c == nil {
  257. c = &Cache{
  258. Learned: make([]netip.AddrPort, 0),
  259. Reported: make([]netip.AddrPort, 0),
  260. Relay: make([]netip.Addr, 0),
  261. }
  262. cm[vpnIp] = c
  263. }
  264. return c
  265. }
  266. for owner, mc := range r.cache {
  267. c := getOrMake(owner.String())
  268. if mc.v4 != nil {
  269. if mc.v4.learned != nil {
  270. c.Learned = append(c.Learned, protoV4AddrPortToNetAddrPort(mc.v4.learned))
  271. }
  272. for _, a := range mc.v4.reported {
  273. c.Reported = append(c.Reported, protoV4AddrPortToNetAddrPort(a))
  274. }
  275. }
  276. if mc.v6 != nil {
  277. if mc.v6.learned != nil {
  278. c.Learned = append(c.Learned, protoV6AddrPortToNetAddrPort(mc.v6.learned))
  279. }
  280. for _, a := range mc.v6.reported {
  281. c.Reported = append(c.Reported, protoV6AddrPortToNetAddrPort(a))
  282. }
  283. }
  284. if mc.relay != nil {
  285. for _, a := range mc.relay.relay {
  286. c.Relay = append(c.Relay, a)
  287. }
  288. }
  289. }
  290. return &cm
  291. }
  292. // BlockRemote locks and records the address as bad, it will be excluded from the deduplicated address list
  293. func (r *RemoteList) BlockRemote(bad netip.AddrPort) {
  294. if !bad.IsValid() {
  295. // relays can have nil udp Addrs
  296. return
  297. }
  298. r.Lock()
  299. defer r.Unlock()
  300. // Check if we already blocked this addr
  301. if r.unlockedIsBad(bad) {
  302. return
  303. }
  304. // We copy here because we are taking something else's memory and we can't trust everything
  305. r.badRemotes = append(r.badRemotes, bad)
  306. // Mark the next interaction must recollect/dedupe
  307. r.shouldRebuild = true
  308. }
  309. // CopyBlockedRemotes locks and makes a deep copy of the blocked remotes list
  310. func (r *RemoteList) CopyBlockedRemotes() []netip.AddrPort {
  311. r.RLock()
  312. defer r.RUnlock()
  313. c := make([]netip.AddrPort, len(r.badRemotes))
  314. for i, v := range r.badRemotes {
  315. c[i] = v
  316. }
  317. return c
  318. }
  319. // ResetBlockedRemotes locks and clears the blocked remotes list
  320. func (r *RemoteList) ResetBlockedRemotes() {
  321. r.Lock()
  322. r.badRemotes = nil
  323. r.Unlock()
  324. }
  325. // Rebuild locks and generates the deduplicated address list only if there is work to be done
  326. // There is generally no reason to call this directly but it is safe to do so
  327. func (r *RemoteList) Rebuild(preferredRanges []netip.Prefix) {
  328. r.Lock()
  329. defer r.Unlock()
  330. // Only rebuild if the cache changed
  331. //TODO: shouldRebuild is probably pointless as we don't check for actual change when lighthouse updates come in
  332. if r.shouldRebuild {
  333. r.unlockedCollect()
  334. r.shouldRebuild = false
  335. }
  336. // Always re-sort, preferredRanges can change via HUP
  337. r.unlockedSort(preferredRanges)
  338. }
  339. // unlockedIsBad assumes you have the write lock and checks if the remote matches any entry in the blocked address list
  340. func (r *RemoteList) unlockedIsBad(remote netip.AddrPort) bool {
  341. for _, v := range r.badRemotes {
  342. if v == remote {
  343. return true
  344. }
  345. }
  346. return false
  347. }
  348. // unlockedSetLearnedV4 assumes you have the write lock and sets the current learned address for this owner and marks the
  349. // deduplicated address list as dirty
  350. func (r *RemoteList) unlockedSetLearnedV4(ownerVpnIp netip.Addr, to *V4AddrPort) {
  351. r.shouldRebuild = true
  352. r.unlockedGetOrMakeV4(ownerVpnIp).learned = to
  353. }
  354. // unlockedSetV4 assumes you have the write lock and resets the reported list of ips for this owner to the list provided
  355. // and marks the deduplicated address list as dirty
  356. func (r *RemoteList) unlockedSetV4(ownerVpnIp, vpnIp netip.Addr, to []*V4AddrPort, check checkFuncV4) {
  357. r.shouldRebuild = true
  358. c := r.unlockedGetOrMakeV4(ownerVpnIp)
  359. // Reset the slice
  360. c.reported = c.reported[:0]
  361. // We can't take their array but we can take their pointers
  362. for _, v := range to[:minInt(len(to), MaxRemotes)] {
  363. if check(vpnIp, v) {
  364. c.reported = append(c.reported, v)
  365. }
  366. }
  367. }
  368. func (r *RemoteList) unlockedSetRelay(ownerVpnIp, vpnIp netip.Addr, to []netip.Addr) {
  369. r.shouldRebuild = true
  370. c := r.unlockedGetOrMakeRelay(ownerVpnIp)
  371. // Reset the slice
  372. c.relay = c.relay[:0]
  373. // We can't take their array but we can take their pointers
  374. c.relay = append(c.relay, to[:minInt(len(to), MaxRemotes)]...)
  375. }
  376. // unlockedPrependV4 assumes you have the write lock and prepends the address in the reported list for this owner
  377. // This is only useful for establishing static hosts
  378. func (r *RemoteList) unlockedPrependV4(ownerVpnIp netip.Addr, to *V4AddrPort) {
  379. r.shouldRebuild = true
  380. c := r.unlockedGetOrMakeV4(ownerVpnIp)
  381. // We are doing the easy append because this is rarely called
  382. c.reported = append([]*V4AddrPort{to}, c.reported...)
  383. if len(c.reported) > MaxRemotes {
  384. c.reported = c.reported[:MaxRemotes]
  385. }
  386. }
  387. // unlockedSetLearnedV6 assumes you have the write lock and sets the current learned address for this owner and marks the
  388. // deduplicated address list as dirty
  389. func (r *RemoteList) unlockedSetLearnedV6(ownerVpnIp netip.Addr, to *V6AddrPort) {
  390. r.shouldRebuild = true
  391. r.unlockedGetOrMakeV6(ownerVpnIp).learned = to
  392. }
  393. // unlockedSetV6 assumes you have the write lock and resets the reported list of ips for this owner to the list provided
  394. // and marks the deduplicated address list as dirty
  395. func (r *RemoteList) unlockedSetV6(ownerVpnIp, vpnIp netip.Addr, to []*V6AddrPort, check checkFuncV6) {
  396. r.shouldRebuild = true
  397. c := r.unlockedGetOrMakeV6(ownerVpnIp)
  398. // Reset the slice
  399. c.reported = c.reported[:0]
  400. // We can't take their array but we can take their pointers
  401. for _, v := range to[:minInt(len(to), MaxRemotes)] {
  402. if check(vpnIp, v) {
  403. c.reported = append(c.reported, v)
  404. }
  405. }
  406. }
  407. // unlockedPrependV6 assumes you have the write lock and prepends the address in the reported list for this owner
  408. // This is only useful for establishing static hosts
  409. func (r *RemoteList) unlockedPrependV6(ownerVpnIp netip.Addr, to *V6AddrPort) {
  410. r.shouldRebuild = true
  411. c := r.unlockedGetOrMakeV6(ownerVpnIp)
  412. // We are doing the easy append because this is rarely called
  413. c.reported = append([]*V6AddrPort{to}, c.reported...)
  414. if len(c.reported) > MaxRemotes {
  415. c.reported = c.reported[:MaxRemotes]
  416. }
  417. }
  418. func (r *RemoteList) unlockedGetOrMakeRelay(ownerVpnIp netip.Addr) *cacheRelay {
  419. am := r.cache[ownerVpnIp]
  420. if am == nil {
  421. am = &cache{}
  422. r.cache[ownerVpnIp] = am
  423. }
  424. // Avoid occupying memory for relay if we never have any
  425. if am.relay == nil {
  426. am.relay = &cacheRelay{}
  427. }
  428. return am.relay
  429. }
  430. // unlockedGetOrMakeV4 assumes you have the write lock and builds the cache and owner entry. Only the v4 pointer is established.
  431. // The caller must dirty the learned address cache if required
  432. func (r *RemoteList) unlockedGetOrMakeV4(ownerVpnIp netip.Addr) *cacheV4 {
  433. am := r.cache[ownerVpnIp]
  434. if am == nil {
  435. am = &cache{}
  436. r.cache[ownerVpnIp] = am
  437. }
  438. // Avoid occupying memory for v6 addresses if we never have any
  439. if am.v4 == nil {
  440. am.v4 = &cacheV4{}
  441. }
  442. return am.v4
  443. }
  444. // unlockedGetOrMakeV6 assumes you have the write lock and builds the cache and owner entry. Only the v6 pointer is established.
  445. // The caller must dirty the learned address cache if required
  446. func (r *RemoteList) unlockedGetOrMakeV6(ownerVpnIp netip.Addr) *cacheV6 {
  447. am := r.cache[ownerVpnIp]
  448. if am == nil {
  449. am = &cache{}
  450. r.cache[ownerVpnIp] = am
  451. }
  452. // Avoid occupying memory for v4 addresses if we never have any
  453. if am.v6 == nil {
  454. am.v6 = &cacheV6{}
  455. }
  456. return am.v6
  457. }
  458. // unlockedCollect assumes you have the write lock and collects/transforms the cache into the deduped address list.
  459. // The result of this function can contain duplicates. unlockedSort handles cleaning it.
  460. func (r *RemoteList) unlockedCollect() {
  461. addrs := r.addrs[:0]
  462. relays := r.relays[:0]
  463. for _, c := range r.cache {
  464. if c.v4 != nil {
  465. if c.v4.learned != nil {
  466. u := protoV4AddrPortToNetAddrPort(c.v4.learned)
  467. if !r.unlockedIsBad(u) {
  468. addrs = append(addrs, u)
  469. }
  470. }
  471. for _, v := range c.v4.reported {
  472. u := protoV4AddrPortToNetAddrPort(v)
  473. if !r.unlockedIsBad(u) {
  474. addrs = append(addrs, u)
  475. }
  476. }
  477. }
  478. if c.v6 != nil {
  479. if c.v6.learned != nil {
  480. u := protoV6AddrPortToNetAddrPort(c.v6.learned)
  481. if !r.unlockedIsBad(u) {
  482. addrs = append(addrs, u)
  483. }
  484. }
  485. for _, v := range c.v6.reported {
  486. u := protoV6AddrPortToNetAddrPort(v)
  487. if !r.unlockedIsBad(u) {
  488. addrs = append(addrs, u)
  489. }
  490. }
  491. }
  492. if c.relay != nil {
  493. for _, v := range c.relay.relay {
  494. relays = append(relays, v)
  495. }
  496. }
  497. }
  498. dnsAddrs := r.hr.GetAddrs()
  499. for _, addr := range dnsAddrs {
  500. if r.shouldAdd == nil || r.shouldAdd(addr.Addr()) {
  501. if !r.unlockedIsBad(addr) {
  502. addrs = append(addrs, addr)
  503. }
  504. }
  505. }
  506. r.addrs = addrs
  507. r.relays = relays
  508. }
  509. // unlockedSort assumes you have the write lock and performs the deduping and sorting of the address list
  510. func (r *RemoteList) unlockedSort(preferredRanges []netip.Prefix) {
  511. n := len(r.addrs)
  512. if n < 2 {
  513. return
  514. }
  515. lessFunc := func(i, j int) bool {
  516. a := r.addrs[i]
  517. b := r.addrs[j]
  518. // Preferred addresses first
  519. aPref := isPreferred(a.Addr(), preferredRanges)
  520. bPref := isPreferred(b.Addr(), preferredRanges)
  521. switch {
  522. case aPref && !bPref:
  523. // If i is preferred and j is not, i is less than j
  524. return true
  525. case !aPref && bPref:
  526. // If j is preferred then i is not due to the else, i is not less than j
  527. return false
  528. default:
  529. // Both i an j are either preferred or not, sort within that
  530. }
  531. // ipv6 addresses 2nd
  532. a4 := a.Addr().Is4()
  533. b4 := b.Addr().Is4()
  534. switch {
  535. case a4 == false && b4 == true:
  536. // If i is v6 and j is v4, i is less than j
  537. return true
  538. case a4 == true && b4 == false:
  539. // If j is v6 and i is v4, i is not less than j
  540. return false
  541. case a4 == true && b4 == true:
  542. // i and j are both ipv4
  543. aPrivate := a.Addr().IsPrivate()
  544. bPrivate := b.Addr().IsPrivate()
  545. switch {
  546. case !aPrivate && bPrivate:
  547. // If i is a public ip (not private) and j is a private ip, i is less then j
  548. return true
  549. case aPrivate && !bPrivate:
  550. // If j is public (not private) then i is private due to the else, i is not less than j
  551. return false
  552. default:
  553. // Both i an j are either public or private, sort within that
  554. }
  555. default:
  556. // Both i an j are either ipv4 or ipv6, sort within that
  557. }
  558. // lexical order of ips 3rd
  559. c := a.Addr().Compare(b.Addr())
  560. if c == 0 {
  561. // Ips are the same, Lexical order of ports 4th
  562. return a.Port() < b.Port()
  563. }
  564. // Ip wasn't the same
  565. return c < 0
  566. }
  567. // Sort it
  568. sort.Slice(r.addrs, lessFunc)
  569. // Deduplicate
  570. a, b := 0, 1
  571. for b < n {
  572. if r.addrs[a] != r.addrs[b] {
  573. a++
  574. if a != b {
  575. r.addrs[a], r.addrs[b] = r.addrs[b], r.addrs[a]
  576. }
  577. }
  578. b++
  579. }
  580. r.addrs = r.addrs[:a+1]
  581. return
  582. }
  583. // minInt returns the minimum integer of a or b
  584. func minInt(a, b int) int {
  585. if a < b {
  586. return a
  587. }
  588. return b
  589. }
  590. // isPreferred returns true of the ip is contained in the preferredRanges list
  591. func isPreferred(ip netip.Addr, preferredRanges []netip.Prefix) bool {
  592. //TODO: this would be better in a CIDR6Tree
  593. for _, p := range preferredRanges {
  594. if p.Contains(ip) {
  595. return true
  596. }
  597. }
  598. return false
  599. }