1
0

remote_list.go 19 KB

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