remote_list.go 19 KB

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