remote_list.go 19 KB

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