remote_list.go 20 KB

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