remote_list.go 20 KB

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