remote_list.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  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 underlay 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 is a nillable function that decides if x should be added to addrs.
  178. shouldAdd func(vpnAddrs []netip.Addr, x 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, 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. func (r *RemoteList) LearnRemote(ownerVpnIp netip.Addr, remote netip.AddrPort) {
  239. r.Lock()
  240. defer r.Unlock()
  241. if remote.Addr().Is4() {
  242. r.unlockedSetLearnedV4(ownerVpnIp, netAddrToProtoV4AddrPort(remote.Addr(), remote.Port()))
  243. } else {
  244. r.unlockedSetLearnedV6(ownerVpnIp, netAddrToProtoV6AddrPort(remote.Addr(), remote.Port()))
  245. }
  246. }
  247. // CopyCache locks and creates a more human friendly form of the internal address cache.
  248. // This may contain duplicates and blocked addresses
  249. func (r *RemoteList) CopyCache() *CacheMap {
  250. r.RLock()
  251. defer r.RUnlock()
  252. cm := make(CacheMap)
  253. getOrMake := func(vpnIp string) *Cache {
  254. c := cm[vpnIp]
  255. if c == nil {
  256. c = &Cache{
  257. Learned: make([]netip.AddrPort, 0),
  258. Reported: make([]netip.AddrPort, 0),
  259. Relay: make([]netip.Addr, 0),
  260. }
  261. cm[vpnIp] = c
  262. }
  263. return c
  264. }
  265. for owner, mc := range r.cache {
  266. c := getOrMake(owner.String())
  267. if mc.v4 != nil {
  268. if mc.v4.learned != nil {
  269. c.Learned = append(c.Learned, protoV4AddrPortToNetAddrPort(mc.v4.learned))
  270. }
  271. for _, a := range mc.v4.reported {
  272. c.Reported = append(c.Reported, protoV4AddrPortToNetAddrPort(a))
  273. }
  274. }
  275. if mc.v6 != nil {
  276. if mc.v6.learned != nil {
  277. c.Learned = append(c.Learned, protoV6AddrPortToNetAddrPort(mc.v6.learned))
  278. }
  279. for _, a := range mc.v6.reported {
  280. c.Reported = append(c.Reported, protoV6AddrPortToNetAddrPort(a))
  281. }
  282. }
  283. if mc.relay != nil {
  284. for _, a := range mc.relay.relay {
  285. c.Relay = append(c.Relay, a)
  286. }
  287. }
  288. }
  289. return &cm
  290. }
  291. // BlockRemote locks and records the address as bad, it will be excluded from the deduplicated address list
  292. func (r *RemoteList) BlockRemote(bad netip.AddrPort) {
  293. if !bad.IsValid() {
  294. // relays can have nil udp Addrs
  295. return
  296. }
  297. r.Lock()
  298. defer r.Unlock()
  299. // Check if we already blocked this addr
  300. if r.unlockedIsBad(bad) {
  301. return
  302. }
  303. // We copy here because we are taking something else's memory and we can't trust everything
  304. r.badRemotes = append(r.badRemotes, bad)
  305. // Mark the next interaction must recollect/dedupe
  306. r.shouldRebuild = true
  307. }
  308. // CopyBlockedRemotes locks and makes a deep copy of the blocked remotes list
  309. func (r *RemoteList) CopyBlockedRemotes() []netip.AddrPort {
  310. r.RLock()
  311. defer r.RUnlock()
  312. c := make([]netip.AddrPort, len(r.badRemotes))
  313. for i, v := range r.badRemotes {
  314. c[i] = v
  315. }
  316. return c
  317. }
  318. // RefreshFromHandshake locks and updates the RemoteList to account for data learned upon a completed handshake
  319. func (r *RemoteList) RefreshFromHandshake(vpnAddrs []netip.Addr) {
  320. r.Lock()
  321. r.badRemotes = nil
  322. r.vpnAddrs = make([]netip.Addr, len(vpnAddrs))
  323. copy(r.vpnAddrs, vpnAddrs)
  324. r.Unlock()
  325. }
  326. // ResetBlockedRemotes locks and clears the blocked remotes list
  327. func (r *RemoteList) ResetBlockedRemotes() {
  328. r.Lock()
  329. r.badRemotes = nil
  330. r.Unlock()
  331. }
  332. // Rebuild locks and generates the deduplicated address list only if there is work to be done
  333. // There is generally no reason to call this directly but it is safe to do so
  334. func (r *RemoteList) Rebuild(preferredRanges []netip.Prefix) {
  335. r.Lock()
  336. defer r.Unlock()
  337. // Only rebuild if the cache changed
  338. if r.shouldRebuild {
  339. r.unlockedCollect()
  340. r.shouldRebuild = false
  341. }
  342. // Always re-sort, preferredRanges can change via HUP
  343. r.unlockedSort(preferredRanges)
  344. }
  345. // unlockedIsBad assumes you have the write lock and checks if the remote matches any entry in the blocked address list
  346. func (r *RemoteList) unlockedIsBad(remote netip.AddrPort) bool {
  347. for _, v := range r.badRemotes {
  348. if v == remote {
  349. return true
  350. }
  351. }
  352. return false
  353. }
  354. // unlockedSetLearnedV4 assumes you have the write lock and sets the current learned address for this owner and marks the
  355. // deduplicated address list as dirty
  356. func (r *RemoteList) unlockedSetLearnedV4(ownerVpnIp netip.Addr, to *V4AddrPort) {
  357. r.shouldRebuild = true
  358. r.unlockedGetOrMakeV4(ownerVpnIp).learned = to
  359. }
  360. // unlockedSetV4 assumes you have the write lock and resets the reported list of ips for this owner to the list provided
  361. // and marks the deduplicated address list as dirty
  362. func (r *RemoteList) unlockedSetV4(ownerVpnIp, vpnIp netip.Addr, to []*V4AddrPort, check checkFuncV4) {
  363. r.shouldRebuild = true
  364. c := r.unlockedGetOrMakeV4(ownerVpnIp)
  365. // Reset the slice
  366. c.reported = c.reported[:0]
  367. // We can't take their array but we can take their pointers
  368. for _, v := range to[:minInt(len(to), MaxRemotes)] {
  369. if check(vpnIp, v) {
  370. c.reported = append(c.reported, v)
  371. }
  372. }
  373. }
  374. func (r *RemoteList) unlockedSetRelay(ownerVpnIp netip.Addr, to []netip.Addr) {
  375. r.shouldRebuild = true
  376. c := r.unlockedGetOrMakeRelay(ownerVpnIp)
  377. // Reset the slice
  378. c.relay = c.relay[:0]
  379. // We can't take their array but we can take their pointers
  380. c.relay = append(c.relay, to[:minInt(len(to), MaxRemotes)]...)
  381. }
  382. // unlockedPrependV4 assumes you have the write lock and prepends the address in the reported list for this owner
  383. // This is only useful for establishing static hosts
  384. func (r *RemoteList) unlockedPrependV4(ownerVpnIp netip.Addr, to *V4AddrPort) {
  385. r.shouldRebuild = true
  386. c := r.unlockedGetOrMakeV4(ownerVpnIp)
  387. // We are doing the easy append because this is rarely called
  388. c.reported = append([]*V4AddrPort{to}, c.reported...)
  389. if len(c.reported) > MaxRemotes {
  390. c.reported = c.reported[:MaxRemotes]
  391. }
  392. }
  393. // unlockedSetLearnedV6 assumes you have the write lock and sets the current learned address for this owner and marks the
  394. // deduplicated address list as dirty
  395. func (r *RemoteList) unlockedSetLearnedV6(ownerVpnIp netip.Addr, to *V6AddrPort) {
  396. r.shouldRebuild = true
  397. r.unlockedGetOrMakeV6(ownerVpnIp).learned = to
  398. }
  399. // unlockedSetV6 assumes you have the write lock and resets the reported list of ips for this owner to the list provided
  400. // and marks the deduplicated address list as dirty
  401. func (r *RemoteList) unlockedSetV6(ownerVpnIp, vpnIp netip.Addr, to []*V6AddrPort, check checkFuncV6) {
  402. r.shouldRebuild = true
  403. c := r.unlockedGetOrMakeV6(ownerVpnIp)
  404. // Reset the slice
  405. c.reported = c.reported[:0]
  406. // We can't take their array but we can take their pointers
  407. for _, v := range to[:minInt(len(to), MaxRemotes)] {
  408. if check(vpnIp, v) {
  409. c.reported = append(c.reported, v)
  410. }
  411. }
  412. }
  413. // unlockedPrependV6 assumes you have the write lock and prepends the address in the reported list for this owner
  414. // This is only useful for establishing static hosts
  415. func (r *RemoteList) unlockedPrependV6(ownerVpnIp netip.Addr, to *V6AddrPort) {
  416. r.shouldRebuild = true
  417. c := r.unlockedGetOrMakeV6(ownerVpnIp)
  418. // We are doing the easy append because this is rarely called
  419. c.reported = append([]*V6AddrPort{to}, c.reported...)
  420. if len(c.reported) > MaxRemotes {
  421. c.reported = c.reported[:MaxRemotes]
  422. }
  423. }
  424. func (r *RemoteList) unlockedGetOrMakeRelay(ownerVpnIp netip.Addr) *cacheRelay {
  425. am := r.cache[ownerVpnIp]
  426. if am == nil {
  427. am = &cache{}
  428. r.cache[ownerVpnIp] = am
  429. }
  430. // Avoid occupying memory for relay if we never have any
  431. if am.relay == nil {
  432. am.relay = &cacheRelay{}
  433. }
  434. return am.relay
  435. }
  436. // unlockedGetOrMakeV4 assumes you have the write lock and builds the cache and owner entry. Only the v4 pointer is established.
  437. // The caller must dirty the learned address cache if required
  438. func (r *RemoteList) unlockedGetOrMakeV4(ownerVpnIp netip.Addr) *cacheV4 {
  439. am := r.cache[ownerVpnIp]
  440. if am == nil {
  441. am = &cache{}
  442. r.cache[ownerVpnIp] = am
  443. }
  444. // Avoid occupying memory for v6 addresses if we never have any
  445. if am.v4 == nil {
  446. am.v4 = &cacheV4{}
  447. }
  448. return am.v4
  449. }
  450. // unlockedGetOrMakeV6 assumes you have the write lock and builds the cache and owner entry. Only the v6 pointer is established.
  451. // The caller must dirty the learned address cache if required
  452. func (r *RemoteList) unlockedGetOrMakeV6(ownerVpnIp netip.Addr) *cacheV6 {
  453. am := r.cache[ownerVpnIp]
  454. if am == nil {
  455. am = &cache{}
  456. r.cache[ownerVpnIp] = am
  457. }
  458. // Avoid occupying memory for v4 addresses if we never have any
  459. if am.v6 == nil {
  460. am.v6 = &cacheV6{}
  461. }
  462. return am.v6
  463. }
  464. // unlockedCollect assumes you have the write lock and collects/transforms the cache into the deduped address list.
  465. // The result of this function can contain duplicates. unlockedSort handles cleaning it.
  466. func (r *RemoteList) unlockedCollect() {
  467. addrs := r.addrs[:0]
  468. relays := r.relays[:0]
  469. for _, c := range r.cache {
  470. if c.v4 != nil {
  471. if c.v4.learned != nil {
  472. u := protoV4AddrPortToNetAddrPort(c.v4.learned)
  473. if !r.unlockedIsBad(u) {
  474. addrs = append(addrs, u)
  475. }
  476. }
  477. for _, v := range c.v4.reported {
  478. u := protoV4AddrPortToNetAddrPort(v)
  479. if !r.unlockedIsBad(u) {
  480. addrs = append(addrs, u)
  481. }
  482. }
  483. }
  484. if c.v6 != nil {
  485. if c.v6.learned != nil {
  486. u := protoV6AddrPortToNetAddrPort(c.v6.learned)
  487. if !r.unlockedIsBad(u) {
  488. addrs = append(addrs, u)
  489. }
  490. }
  491. for _, v := range c.v6.reported {
  492. u := protoV6AddrPortToNetAddrPort(v)
  493. if !r.unlockedIsBad(u) {
  494. addrs = append(addrs, u)
  495. }
  496. }
  497. }
  498. if c.relay != nil {
  499. for _, v := range c.relay.relay {
  500. relays = append(relays, v)
  501. }
  502. }
  503. }
  504. dnsAddrs := r.hr.GetAddrs()
  505. for _, addr := range dnsAddrs {
  506. if r.shouldAdd == nil || r.shouldAdd(r.vpnAddrs, addr.Addr()) {
  507. if !r.unlockedIsBad(addr) {
  508. addrs = append(addrs, addr)
  509. }
  510. }
  511. }
  512. r.addrs = addrs
  513. r.relays = relays
  514. }
  515. // unlockedSort assumes you have the write lock and performs the deduping and sorting of the address list
  516. func (r *RemoteList) unlockedSort(preferredRanges []netip.Prefix) {
  517. // Use a map to deduplicate any relay addresses
  518. dedupedRelays := map[netip.Addr]struct{}{}
  519. for _, relay := range r.relays {
  520. dedupedRelays[relay] = struct{}{}
  521. }
  522. r.relays = r.relays[:0]
  523. for relay := range dedupedRelays {
  524. r.relays = append(r.relays, relay)
  525. }
  526. // Put them in a somewhat consistent order after de-duplication
  527. slices.SortFunc(r.relays, func(a, b netip.Addr) int {
  528. return a.Compare(b)
  529. })
  530. // Now the addrs
  531. n := len(r.addrs)
  532. if n < 2 {
  533. return
  534. }
  535. lessFunc := func(i, j int) bool {
  536. a := r.addrs[i]
  537. b := r.addrs[j]
  538. // Preferred addresses first
  539. aPref := isPreferred(a.Addr(), preferredRanges)
  540. bPref := isPreferred(b.Addr(), preferredRanges)
  541. switch {
  542. case aPref && !bPref:
  543. // If i is preferred and j is not, i is less than j
  544. return true
  545. case !aPref && bPref:
  546. // If j is preferred then i is not due to the else, i is not less than j
  547. return false
  548. default:
  549. // Both i an j are either preferred or not, sort within that
  550. }
  551. // ipv6 addresses 2nd
  552. a4 := a.Addr().Is4()
  553. b4 := b.Addr().Is4()
  554. switch {
  555. case a4 == false && b4 == true:
  556. // If i is v6 and j is v4, i is less than j
  557. return true
  558. case a4 == true && b4 == false:
  559. // If j is v6 and i is v4, i is not less than j
  560. return false
  561. case a4 == true && b4 == true:
  562. // i and j are both ipv4
  563. aPrivate := a.Addr().IsPrivate()
  564. bPrivate := b.Addr().IsPrivate()
  565. switch {
  566. case !aPrivate && bPrivate:
  567. // If i is a public ip (not private) and j is a private ip, i is less then j
  568. return true
  569. case aPrivate && !bPrivate:
  570. // If j is public (not private) then i is private due to the else, i is not less than j
  571. return false
  572. default:
  573. // Both i an j are either public or private, sort within that
  574. }
  575. default:
  576. // Both i an j are either ipv4 or ipv6, sort within that
  577. }
  578. // lexical order of ips 3rd
  579. c := a.Addr().Compare(b.Addr())
  580. if c == 0 {
  581. // Ips are the same, Lexical order of ports 4th
  582. return a.Port() < b.Port()
  583. }
  584. // Ip wasn't the same
  585. return c < 0
  586. }
  587. // Sort it
  588. sort.Slice(r.addrs, lessFunc)
  589. // Deduplicate
  590. a, b := 0, 1
  591. for b < n {
  592. if r.addrs[a] != r.addrs[b] {
  593. a++
  594. if a != b {
  595. r.addrs[a], r.addrs[b] = r.addrs[b], r.addrs[a]
  596. }
  597. }
  598. b++
  599. }
  600. r.addrs = r.addrs[:a+1]
  601. return
  602. }
  603. // minInt returns the minimum integer of a or b
  604. func minInt(a, b int) int {
  605. if a < b {
  606. return a
  607. }
  608. return b
  609. }
  610. // isPreferred returns true of the ip is contained in the preferredRanges list
  611. func isPreferred(ip netip.Addr, preferredRanges []netip.Prefix) bool {
  612. for _, p := range preferredRanges {
  613. if p.Contains(ip) {
  614. return true
  615. }
  616. }
  617. return false
  618. }