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"
  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. 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. }