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