remote_list.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859
  1. package nebula
  2. import (
  3. "context"
  4. "errors"
  5. "log/slog"
  6. "net"
  7. "net/netip"
  8. "slices"
  9. "sort"
  10. "strconv"
  11. "sync"
  12. "sync/atomic"
  13. "time"
  14. )
  15. // forEachFunc is used to benefit folks that want to do work inside the lock
  16. type forEachFunc func(addr netip.AddrPort, preferred bool)
  17. // The checkFuncs here are to simplify bulk importing LH query response logic into a single function (reset slice and iterate)
  18. type checkFuncV4 func(vpnIp netip.Addr, to *V4AddrPort) bool
  19. type checkFuncV6 func(vpnIp netip.Addr, to *V6AddrPort) bool
  20. // CacheMap is a struct that better represents the lighthouse cache for humans
  21. // The string key is the owners vpnIp
  22. type CacheMap map[string]*Cache
  23. // Cache is the other part of CacheMap to better represent the lighthouse cache for humans
  24. // We don't reason about ipv4 vs ipv6 here
  25. type Cache struct {
  26. Learned []netip.AddrPort `json:"learned,omitempty"`
  27. Reported []netip.AddrPort `json:"reported,omitempty"`
  28. Relay []netip.Addr `json:"relay"`
  29. }
  30. // cache is an internal struct that splits v4 and v6 addresses inside the cache map
  31. type cache struct {
  32. v4 *cacheV4
  33. v6 *cacheV6
  34. relay *cacheRelay
  35. }
  36. type cacheRelay struct {
  37. relay []netip.Addr
  38. }
  39. // cacheV4 stores learned and reported ipv4 records under cache
  40. type cacheV4 struct {
  41. learned *V4AddrPort
  42. reported []*V4AddrPort
  43. }
  44. // cacheV4 stores learned and reported ipv6 records under cache
  45. type cacheV6 struct {
  46. learned *V6AddrPort
  47. reported []*V6AddrPort
  48. }
  49. type hostnamePort struct {
  50. name string
  51. port uint16
  52. // addr is set when name is an ip literal, these never need a lookup
  53. addr netip.Addr
  54. }
  55. type hostnamesResults struct {
  56. hostnames []hostnamePort
  57. network string
  58. lookupTimeout time.Duration
  59. cancelFn func()
  60. resolveNow chan struct{}
  61. l *slog.Logger
  62. ips atomic.Pointer[map[netip.AddrPort]struct{}]
  63. // known is the last known good addresses per hostname, kept so a reload can carry them forward
  64. known atomic.Pointer[map[hostnamePort][]netip.AddrPort]
  65. }
  66. // NewHostnameResults starts resolving hostPorts. Any hostnames also in prev start with its last known good addresses.
  67. func NewHostnameResults(ctx context.Context, l *slog.Logger, d time.Duration, network string, timeout time.Duration, hostPorts []string, prev *hostnamesResults, onUpdate func()) (*hostnamesResults, error) {
  68. r := &hostnamesResults{
  69. hostnames: make([]hostnamePort, len(hostPorts)),
  70. network: network,
  71. lookupTimeout: timeout,
  72. resolveNow: make(chan struct{}, 1),
  73. l: l,
  74. }
  75. // Fastrack IP addresses to ensure they're immediately available for use.
  76. // DNS lookups for hostnames that aren't hardcoded IP's will happen in a background goroutine.
  77. performBackgroundLookup := false
  78. ips := map[netip.AddrPort]struct{}{}
  79. known := make([][]netip.AddrPort, len(hostPorts))
  80. var prevKnown map[hostnamePort][]netip.AddrPort
  81. if prev != nil && prev.network == network {
  82. if p := prev.known.Load(); p != nil {
  83. prevKnown = *p
  84. }
  85. }
  86. for idx, hostPort := range hostPorts {
  87. rIp, sPort, err := net.SplitHostPort(hostPort)
  88. if err != nil {
  89. return nil, err
  90. }
  91. iPort, err := strconv.Atoi(sPort)
  92. if err != nil {
  93. return nil, err
  94. }
  95. r.hostnames[idx] = hostnamePort{name: rIp, port: uint16(iPort)}
  96. addr, err := netip.ParseAddr(rIp)
  97. if err != nil {
  98. // This address is a hostname, not an IP address
  99. performBackgroundLookup = true
  100. known[idx] = prevKnown[r.hostnames[idx]]
  101. for _, a := range known[idx] {
  102. ips[a] = struct{}{}
  103. }
  104. continue
  105. }
  106. // Save the IP address immediately
  107. r.hostnames[idx].addr = addr
  108. ips[netip.AddrPortFrom(addr, uint16(iPort))] = struct{}{}
  109. }
  110. r.ips.Store(&ips)
  111. r.storeKnown(known)
  112. // Time for the DNS lookup goroutine
  113. if performBackgroundLookup {
  114. newCtx, cancel := context.WithCancel(ctx)
  115. r.cancelFn = cancel
  116. ticker := time.NewTicker(d)
  117. go func() {
  118. defer ticker.Stop()
  119. for {
  120. r.resolve(newCtx, known)
  121. r.storeKnown(known)
  122. netipAddrs := map[netip.AddrPort]struct{}{}
  123. for _, addrs := range known {
  124. for _, a := range addrs {
  125. netipAddrs[a] = struct{}{}
  126. }
  127. }
  128. origSet := r.ips.Load()
  129. different := false
  130. for a := range *origSet {
  131. if _, ok := netipAddrs[a]; !ok {
  132. different = true
  133. break
  134. }
  135. }
  136. if !different {
  137. for a := range netipAddrs {
  138. if _, ok := (*origSet)[a]; !ok {
  139. different = true
  140. break
  141. }
  142. }
  143. }
  144. if different {
  145. l.Info("DNS results changed for host list",
  146. "origSet", origSet,
  147. "newSet", netipAddrs,
  148. )
  149. r.ips.Store(&netipAddrs)
  150. onUpdate()
  151. }
  152. select {
  153. case <-newCtx.Done():
  154. return
  155. case <-ticker.C:
  156. case <-r.resolveNow:
  157. }
  158. }
  159. }()
  160. }
  161. return r, nil
  162. }
  163. // resolve looks up every hostname in parallel and folds the results into known
  164. func (hr *hostnamesResults) resolve(ctx context.Context, known [][]netip.AddrPort) {
  165. var wg sync.WaitGroup
  166. for i, hostPort := range hr.hostnames {
  167. if hostPort.addr.IsValid() {
  168. known[i] = []netip.AddrPort{netip.AddrPortFrom(hostPort.addr, hostPort.port)}
  169. continue
  170. }
  171. wg.Go(func() {
  172. timeoutCtx, timeoutCancel := context.WithTimeout(ctx, hr.lookupTimeout)
  173. addrs, err := net.DefaultResolver.LookupNetIP(timeoutCtx, hr.network, hostPort.name)
  174. timeoutCancel()
  175. known[i] = applyLookup(known[i], hostPort.port, addrs, err)
  176. // A canceled ctx means we are reloading or shutting down, not that DNS failed
  177. if err != nil && ctx.Err() == nil {
  178. hr.l.Error("DNS resolution failed for static_map host",
  179. "hostname", hostPort.name,
  180. "network", hr.network,
  181. "error", err,
  182. "usingAddrs", known[i],
  183. )
  184. }
  185. })
  186. }
  187. wg.Wait()
  188. }
  189. // applyLookup returns the addresses to use for a hostname given the previous ones and a lookup result.
  190. // Only a not found answer clears them, a stale lighthouse address costs a handshake but an empty set costs everything.
  191. // darwin also reports not found while offline, that's harmless since nothing is reachable and the next handshake
  192. // triggers a fresh lookup once we're back.
  193. func applyLookup(prev []netip.AddrPort, port uint16, addrs []netip.Addr, err error) []netip.AddrPort {
  194. if err != nil {
  195. var dnsErr *net.DNSError
  196. if errors.As(err, &dnsErr) && dnsErr.IsNotFound {
  197. return nil
  198. }
  199. return prev
  200. }
  201. out := make([]netip.AddrPort, 0, len(addrs))
  202. for _, a := range addrs {
  203. out = append(out, netip.AddrPortFrom(a.Unmap(), port))
  204. }
  205. return out
  206. }
  207. func (hr *hostnamesResults) storeKnown(known [][]netip.AddrPort) {
  208. byName := make(map[hostnamePort][]netip.AddrPort, len(known))
  209. for i, addrs := range known {
  210. byName[hr.hostnames[i]] = addrs
  211. }
  212. hr.known.Store(&byName)
  213. }
  214. // literalAddrs returns the entries that were configured as ip addresses rather than hostnames
  215. func (hr *hostnamesResults) literalAddrs() []netip.AddrPort {
  216. var out []netip.AddrPort
  217. for _, hostPort := range hr.hostnames {
  218. if hostPort.addr.IsValid() {
  219. out = append(out, netip.AddrPortFrom(hostPort.addr, hostPort.port))
  220. }
  221. }
  222. return out
  223. }
  224. // ResolveNow asks the background goroutine to look up the hostnames again without waiting for the next tick
  225. func (hr *hostnamesResults) ResolveNow() {
  226. if hr == nil || hr.resolveNow == nil {
  227. return
  228. }
  229. select {
  230. case hr.resolveNow <- struct{}{}:
  231. default:
  232. }
  233. }
  234. func (hr *hostnamesResults) Cancel() {
  235. if hr != nil && hr.cancelFn != nil {
  236. hr.cancelFn()
  237. }
  238. }
  239. func (hr *hostnamesResults) GetAddrs() []netip.AddrPort {
  240. var retSlice []netip.AddrPort
  241. if hr != nil {
  242. p := hr.ips.Load()
  243. if p != nil {
  244. for k := range *p {
  245. retSlice = append(retSlice, k)
  246. }
  247. }
  248. }
  249. return retSlice
  250. }
  251. // RemoteList is a unifying concept for lighthouse servers and clients as well as hostinfos.
  252. // It serves as a local cache of query replies, host update notifications, and locally learned addresses
  253. type RemoteList struct {
  254. // Every interaction with internals requires a lock!
  255. sync.RWMutex
  256. // The full list of vpn addresses assigned to this host
  257. vpnAddrs []netip.Addr
  258. // A deduplicated set of underlay addresses. Any accessor should lock beforehand.
  259. addrs []netip.AddrPort
  260. // A set of relay addresses. VpnIp addresses that the remote identified as relays.
  261. relays []netip.Addr
  262. // These are maps to store v4 and v6 addresses per lighthouse
  263. // Map key is the vpnIp of the person that told us about this the cached entries underneath.
  264. // For learned addresses, this is the vpnIp that sent the packet
  265. cache map[netip.Addr]*cache
  266. hr *hostnamesResults
  267. // shouldAdd is a nillable function that decides if x should be added to addrs.
  268. shouldAdd func(vpnAddrs []netip.Addr, x netip.Addr) bool
  269. // This is a list of remotes that we have tried to handshake with and have returned from the wrong vpn ip.
  270. // They should not be tried again during a handshake
  271. badRemotes []netip.AddrPort
  272. // A flag that the cache may have changed and addrs needs to be rebuilt
  273. shouldRebuild bool
  274. }
  275. // NewRemoteList creates a new empty RemoteList
  276. func NewRemoteList(vpnAddrs []netip.Addr, shouldAdd func([]netip.Addr, netip.Addr) bool) *RemoteList {
  277. r := &RemoteList{
  278. vpnAddrs: make([]netip.Addr, len(vpnAddrs)),
  279. addrs: make([]netip.AddrPort, 0),
  280. relays: make([]netip.Addr, 0),
  281. cache: make(map[netip.Addr]*cache),
  282. shouldAdd: shouldAdd,
  283. }
  284. copy(r.vpnAddrs, vpnAddrs)
  285. return r
  286. }
  287. func (r *RemoteList) unlockedSetHostnamesResults(hr *hostnamesResults) {
  288. // Cancel any existing hostnamesResults DNS goroutine to release resources
  289. r.hr.Cancel()
  290. r.hr = hr
  291. }
  292. // ResetForOwner zeros the reported address slices for the given owner and marks the addrs list dirty.
  293. // Any pending hostname resolution will be canceled.
  294. func (r *RemoteList) ResetForOwner(ownerVpnAddr netip.Addr) {
  295. r.Lock()
  296. defer r.Unlock()
  297. r.hr.Cancel()
  298. if c, ok := r.cache[ownerVpnAddr]; ok {
  299. if c.v4 != nil {
  300. c.v4.reported = c.v4.reported[:0]
  301. }
  302. if c.v6 != nil {
  303. c.v6.reported = c.v6.reported[:0]
  304. }
  305. }
  306. r.shouldRebuild = true
  307. }
  308. // ResolveHostnames kicks a fresh DNS lookup of any static_map hostnames for this host
  309. func (r *RemoteList) ResolveHostnames() {
  310. r.RLock()
  311. defer r.RUnlock()
  312. r.hr.ResolveNow()
  313. }
  314. // ClearHostnameResults cancels the in-flight DNS resolver goroutine (if any) and drops the resolved IP cache.
  315. func (r *RemoteList) ClearHostnameResults() {
  316. r.Lock()
  317. defer r.Unlock()
  318. r.unlockedSetHostnamesResults(nil)
  319. r.shouldRebuild = true
  320. }
  321. // Len locks and reports the size of the deduplicated address list
  322. // The deduplication work may need to occur here, so you must pass preferredRanges
  323. func (r *RemoteList) Len(preferredRanges []netip.Prefix) int {
  324. r.Rebuild(preferredRanges)
  325. r.RLock()
  326. defer r.RUnlock()
  327. return len(r.addrs)
  328. }
  329. // ForEach locks and will call the forEachFunc for every deduplicated address in the list
  330. // The deduplication work may need to occur here, so you must pass preferredRanges
  331. func (r *RemoteList) ForEach(preferredRanges []netip.Prefix, forEach forEachFunc) {
  332. r.Rebuild(preferredRanges)
  333. r.RLock()
  334. for _, v := range r.addrs {
  335. forEach(v, isPreferred(v.Addr(), preferredRanges))
  336. }
  337. r.RUnlock()
  338. }
  339. // CopyAddrs locks and makes a deep copy of the deduplicated address list
  340. // The deduplication work may need to occur here, so you must pass preferredRanges
  341. func (r *RemoteList) CopyAddrs(preferredRanges []netip.Prefix) []netip.AddrPort {
  342. if r == nil {
  343. return nil
  344. }
  345. r.Rebuild(preferredRanges)
  346. r.RLock()
  347. defer r.RUnlock()
  348. c := make([]netip.AddrPort, len(r.addrs))
  349. for i, v := range r.addrs {
  350. c[i] = v
  351. }
  352. return c
  353. }
  354. // LearnRemote locks and sets the learned slot for the owner vpn ip to the provided addr
  355. // Currently this is only needed when HostInfo.SetRemote is called as that should cover both handshaking and roaming.
  356. // It will mark the deduplicated address list as dirty, so do not call it unless new information is available
  357. func (r *RemoteList) LearnRemote(ownerVpnIp netip.Addr, remote netip.AddrPort) {
  358. r.Lock()
  359. defer r.Unlock()
  360. if remote.Addr().Is4() {
  361. r.unlockedSetLearnedV4(ownerVpnIp, netAddrToProtoV4AddrPort(remote.Addr(), remote.Port()))
  362. } else {
  363. r.unlockedSetLearnedV6(ownerVpnIp, netAddrToProtoV6AddrPort(remote.Addr(), remote.Port()))
  364. }
  365. }
  366. // CopyCache locks and creates a more human friendly form of the internal address cache.
  367. // This may contain duplicates and blocked addresses
  368. func (r *RemoteList) CopyCache() *CacheMap {
  369. r.RLock()
  370. defer r.RUnlock()
  371. cm := make(CacheMap)
  372. getOrMake := func(vpnIp string) *Cache {
  373. c := cm[vpnIp]
  374. if c == nil {
  375. c = &Cache{
  376. Learned: make([]netip.AddrPort, 0),
  377. Reported: make([]netip.AddrPort, 0),
  378. Relay: make([]netip.Addr, 0),
  379. }
  380. cm[vpnIp] = c
  381. }
  382. return c
  383. }
  384. for owner, mc := range r.cache {
  385. c := getOrMake(owner.String())
  386. if mc.v4 != nil {
  387. if mc.v4.learned != nil {
  388. c.Learned = append(c.Learned, protoV4AddrPortToNetAddrPort(mc.v4.learned))
  389. }
  390. for _, a := range mc.v4.reported {
  391. if a == nil {
  392. continue
  393. }
  394. c.Reported = append(c.Reported, protoV4AddrPortToNetAddrPort(a))
  395. }
  396. }
  397. if mc.v6 != nil {
  398. if mc.v6.learned != nil {
  399. c.Learned = append(c.Learned, protoV6AddrPortToNetAddrPort(mc.v6.learned))
  400. }
  401. for _, a := range mc.v6.reported {
  402. if a == nil {
  403. continue
  404. }
  405. c.Reported = append(c.Reported, protoV6AddrPortToNetAddrPort(a))
  406. }
  407. }
  408. if mc.relay != nil {
  409. for _, a := range mc.relay.relay {
  410. c.Relay = append(c.Relay, a)
  411. }
  412. }
  413. }
  414. return &cm
  415. }
  416. // BlockRemote locks and records the address as bad, it will be excluded from the deduplicated address list
  417. func (r *RemoteList) BlockRemote(bad ViaSender) {
  418. if bad.IsRelayed {
  419. return
  420. }
  421. r.Lock()
  422. defer r.Unlock()
  423. // Check if we already blocked this addr
  424. if r.unlockedIsBad(bad.UdpAddr) {
  425. return
  426. }
  427. // We copy here because we are taking something else's memory and we can't trust everything
  428. r.badRemotes = append(r.badRemotes, bad.UdpAddr)
  429. // Mark the next interaction must recollect/dedupe
  430. r.shouldRebuild = true
  431. }
  432. // CopyBlockedRemotes locks and makes a deep copy of the blocked remotes list
  433. func (r *RemoteList) CopyBlockedRemotes() []netip.AddrPort {
  434. r.RLock()
  435. defer r.RUnlock()
  436. c := make([]netip.AddrPort, len(r.badRemotes))
  437. for i, v := range r.badRemotes {
  438. c[i] = v
  439. }
  440. return c
  441. }
  442. // RefreshFromHandshake locks and updates the RemoteList to account for data learned upon a completed handshake
  443. func (r *RemoteList) RefreshFromHandshake(vpnAddrs []netip.Addr) {
  444. r.Lock()
  445. r.badRemotes = nil
  446. r.vpnAddrs = make([]netip.Addr, len(vpnAddrs))
  447. copy(r.vpnAddrs, vpnAddrs)
  448. r.Unlock()
  449. }
  450. // ResetBlockedRemotes locks and clears the blocked remotes list
  451. func (r *RemoteList) ResetBlockedRemotes() {
  452. r.Lock()
  453. r.badRemotes = nil
  454. r.Unlock()
  455. }
  456. // Rebuild locks and generates the deduplicated address list only if there is work to be done
  457. // There is generally no reason to call this directly but it is safe to do so
  458. func (r *RemoteList) Rebuild(preferredRanges []netip.Prefix) {
  459. r.Lock()
  460. defer r.Unlock()
  461. // Only rebuild if the cache changed
  462. if r.shouldRebuild {
  463. r.unlockedCollect()
  464. r.shouldRebuild = false
  465. }
  466. // Always re-sort, preferredRanges can change via HUP
  467. r.unlockedSort(preferredRanges)
  468. }
  469. // unlockedIsBad assumes you have the write lock and checks if the remote matches any entry in the blocked address list
  470. func (r *RemoteList) unlockedIsBad(remote netip.AddrPort) bool {
  471. return slices.Contains(r.badRemotes, remote)
  472. }
  473. // unlockedSetLearnedV4 assumes you have the write lock and sets the current learned address for this owner and marks the
  474. // deduplicated address list as dirty
  475. func (r *RemoteList) unlockedSetLearnedV4(ownerVpnIp netip.Addr, to *V4AddrPort) {
  476. r.shouldRebuild = true
  477. r.unlockedGetOrMakeV4(ownerVpnIp).learned = to
  478. }
  479. // unlockedSetV4 assumes you have the write lock and resets the reported list of ips for this owner to the list provided
  480. // and marks the deduplicated address list as dirty
  481. func (r *RemoteList) unlockedSetV4(ownerVpnIp, vpnIp netip.Addr, to []*V4AddrPort, check checkFuncV4) {
  482. r.shouldRebuild = true
  483. c := r.unlockedGetOrMakeV4(ownerVpnIp)
  484. // Reset the slice
  485. c.reported = c.reported[:0]
  486. // We can't take their array but we can take their pointers
  487. for _, v := range to[:minInt(len(to), MaxRemotes)] {
  488. if check(vpnIp, v) {
  489. c.reported = append(c.reported, v)
  490. }
  491. }
  492. }
  493. func (r *RemoteList) unlockedSetRelay(ownerVpnIp netip.Addr, to []netip.Addr) {
  494. r.shouldRebuild = true
  495. c := r.unlockedGetOrMakeRelay(ownerVpnIp)
  496. // Reset the slice
  497. c.relay = c.relay[:0]
  498. // We can't take their array but we can take their pointers
  499. c.relay = append(c.relay, to[:minInt(len(to), MaxRemotes)]...)
  500. }
  501. // unlockedPrependV4 assumes you have the write lock and prepends the address in the reported list for this owner
  502. // This is only useful for establishing static hosts
  503. func (r *RemoteList) unlockedPrependV4(ownerVpnIp netip.Addr, to *V4AddrPort) {
  504. r.shouldRebuild = true
  505. c := r.unlockedGetOrMakeV4(ownerVpnIp)
  506. // We are doing the easy append because this is rarely called
  507. c.reported = append([]*V4AddrPort{to}, c.reported...)
  508. if len(c.reported) > MaxRemotes {
  509. c.reported = c.reported[:MaxRemotes]
  510. }
  511. }
  512. // unlockedSetLearnedV6 assumes you have the write lock and sets the current learned address for this owner and marks the
  513. // deduplicated address list as dirty
  514. func (r *RemoteList) unlockedSetLearnedV6(ownerVpnIp netip.Addr, to *V6AddrPort) {
  515. r.shouldRebuild = true
  516. r.unlockedGetOrMakeV6(ownerVpnIp).learned = to
  517. }
  518. // unlockedSetV6 assumes you have the write lock and resets the reported list of ips for this owner to the list provided
  519. // and marks the deduplicated address list as dirty
  520. func (r *RemoteList) unlockedSetV6(ownerVpnIp, vpnIp netip.Addr, to []*V6AddrPort, check checkFuncV6) {
  521. r.shouldRebuild = true
  522. c := r.unlockedGetOrMakeV6(ownerVpnIp)
  523. // Reset the slice
  524. c.reported = c.reported[:0]
  525. // We can't take their array but we can take their pointers
  526. for _, v := range to[:minInt(len(to), MaxRemotes)] {
  527. if check(vpnIp, v) {
  528. c.reported = append(c.reported, v)
  529. }
  530. }
  531. }
  532. // unlockedPrependV6 assumes you have the write lock and prepends the address in the reported list for this owner
  533. // This is only useful for establishing static hosts
  534. func (r *RemoteList) unlockedPrependV6(ownerVpnIp netip.Addr, to *V6AddrPort) {
  535. r.shouldRebuild = true
  536. c := r.unlockedGetOrMakeV6(ownerVpnIp)
  537. // We are doing the easy append because this is rarely called
  538. c.reported = append([]*V6AddrPort{to}, c.reported...)
  539. if len(c.reported) > MaxRemotes {
  540. c.reported = c.reported[:MaxRemotes]
  541. }
  542. }
  543. func (r *RemoteList) unlockedGetOrMakeRelay(ownerVpnIp netip.Addr) *cacheRelay {
  544. am := r.cache[ownerVpnIp]
  545. if am == nil {
  546. am = &cache{}
  547. r.cache[ownerVpnIp] = am
  548. }
  549. // Avoid occupying memory for relay if we never have any
  550. if am.relay == nil {
  551. am.relay = &cacheRelay{}
  552. }
  553. return am.relay
  554. }
  555. // unlockedGetOrMakeV4 assumes you have the write lock and builds the cache and owner entry. Only the v4 pointer is established.
  556. // The caller must dirty the learned address cache if required
  557. func (r *RemoteList) unlockedGetOrMakeV4(ownerVpnIp netip.Addr) *cacheV4 {
  558. am := r.cache[ownerVpnIp]
  559. if am == nil {
  560. am = &cache{}
  561. r.cache[ownerVpnIp] = am
  562. }
  563. // Avoid occupying memory for v6 addresses if we never have any
  564. if am.v4 == nil {
  565. am.v4 = &cacheV4{}
  566. }
  567. return am.v4
  568. }
  569. // unlockedGetOrMakeV6 assumes you have the write lock and builds the cache and owner entry. Only the v6 pointer is established.
  570. // The caller must dirty the learned address cache if required
  571. func (r *RemoteList) unlockedGetOrMakeV6(ownerVpnIp netip.Addr) *cacheV6 {
  572. am := r.cache[ownerVpnIp]
  573. if am == nil {
  574. am = &cache{}
  575. r.cache[ownerVpnIp] = am
  576. }
  577. // Avoid occupying memory for v4 addresses if we never have any
  578. if am.v6 == nil {
  579. am.v6 = &cacheV6{}
  580. }
  581. return am.v6
  582. }
  583. // unlockedCollect assumes you have the write lock and collects/transforms the cache into the deduped address list.
  584. // The result of this function can contain duplicates. unlockedSort handles cleaning it.
  585. func (r *RemoteList) unlockedCollect() {
  586. addrs := r.addrs[:0]
  587. relays := r.relays[:0]
  588. for _, c := range r.cache {
  589. if c.v4 != nil {
  590. if c.v4.learned != nil {
  591. u := protoV4AddrPortToNetAddrPort(c.v4.learned)
  592. if !r.unlockedIsBad(u) {
  593. addrs = append(addrs, u)
  594. }
  595. }
  596. for _, v := range c.v4.reported {
  597. if v == nil {
  598. continue
  599. }
  600. u := protoV4AddrPortToNetAddrPort(v)
  601. if !r.unlockedIsBad(u) {
  602. addrs = append(addrs, u)
  603. }
  604. }
  605. }
  606. if c.v6 != nil {
  607. if c.v6.learned != nil {
  608. u := protoV6AddrPortToNetAddrPort(c.v6.learned)
  609. if !r.unlockedIsBad(u) {
  610. addrs = append(addrs, u)
  611. }
  612. }
  613. for _, v := range c.v6.reported {
  614. if v == nil {
  615. continue
  616. }
  617. u := protoV6AddrPortToNetAddrPort(v)
  618. if !r.unlockedIsBad(u) {
  619. addrs = append(addrs, u)
  620. }
  621. }
  622. }
  623. if c.relay != nil {
  624. for _, v := range c.relay.relay {
  625. relays = append(relays, v)
  626. }
  627. }
  628. }
  629. dnsAddrs := r.hr.GetAddrs()
  630. for _, addr := range dnsAddrs {
  631. if r.shouldAdd == nil || r.shouldAdd(r.vpnAddrs, addr.Addr()) {
  632. if !r.unlockedIsBad(addr) {
  633. addrs = append(addrs, addr)
  634. }
  635. }
  636. }
  637. r.addrs = addrs
  638. r.relays = relays
  639. }
  640. // unlockedSort assumes you have the write lock and performs the deduping and sorting of the address list
  641. func (r *RemoteList) unlockedSort(preferredRanges []netip.Prefix) {
  642. // Use a map to deduplicate any relay addresses
  643. dedupedRelays := map[netip.Addr]struct{}{}
  644. for _, relay := range r.relays {
  645. dedupedRelays[relay] = struct{}{}
  646. }
  647. r.relays = r.relays[:0]
  648. for relay := range dedupedRelays {
  649. r.relays = append(r.relays, relay)
  650. }
  651. // Put them in a somewhat consistent order after de-duplication
  652. slices.SortFunc(r.relays, func(a, b netip.Addr) int {
  653. return a.Compare(b)
  654. })
  655. // Now the addrs
  656. n := len(r.addrs)
  657. if n < 2 {
  658. return
  659. }
  660. lessFunc := func(i, j int) bool {
  661. a := r.addrs[i]
  662. b := r.addrs[j]
  663. // Preferred addresses first
  664. aPref := isPreferred(a.Addr(), preferredRanges)
  665. bPref := isPreferred(b.Addr(), preferredRanges)
  666. switch {
  667. case aPref && !bPref:
  668. // If i is preferred and j is not, i is less than j
  669. return true
  670. case !aPref && bPref:
  671. // If j is preferred then i is not due to the else, i is not less than j
  672. return false
  673. default:
  674. // Both i an j are either preferred or not, sort within that
  675. }
  676. // ipv6 addresses 2nd
  677. a4 := a.Addr().Is4()
  678. b4 := b.Addr().Is4()
  679. switch {
  680. case a4 == false && b4 == true:
  681. // If i is v6 and j is v4, i is less than j
  682. return true
  683. case a4 == true && b4 == false:
  684. // If j is v6 and i is v4, i is not less than j
  685. return false
  686. case a4 == true && b4 == true:
  687. // i and j are both ipv4
  688. aPrivate := a.Addr().IsPrivate()
  689. bPrivate := b.Addr().IsPrivate()
  690. switch {
  691. case !aPrivate && bPrivate:
  692. // If i is a public ip (not private) and j is a private ip, i is less then j
  693. return true
  694. case aPrivate && !bPrivate:
  695. // If j is public (not private) then i is private due to the else, i is not less than j
  696. return false
  697. default:
  698. // Both i an j are either public or private, sort within that
  699. }
  700. default:
  701. // Both i an j are either ipv4 or ipv6, sort within that
  702. }
  703. // lexical order of ips 3rd
  704. c := a.Addr().Compare(b.Addr())
  705. if c == 0 {
  706. // Ips are the same, Lexical order of ports 4th
  707. return a.Port() < b.Port()
  708. }
  709. // Ip wasn't the same
  710. return c < 0
  711. }
  712. // Sort it
  713. sort.Slice(r.addrs, lessFunc)
  714. // Deduplicate
  715. a, b := 0, 1
  716. for b < n {
  717. if r.addrs[a] != r.addrs[b] {
  718. a++
  719. if a != b {
  720. r.addrs[a], r.addrs[b] = r.addrs[b], r.addrs[a]
  721. }
  722. }
  723. b++
  724. }
  725. r.addrs = r.addrs[:a+1]
  726. return
  727. }
  728. // minInt returns the minimum integer of a or b
  729. func minInt(a, b int) int {
  730. if a < b {
  731. return a
  732. }
  733. return b
  734. }
  735. // isPreferred returns true of the ip is contained in the preferredRanges list
  736. func isPreferred(ip netip.Addr, preferredRanges []netip.Prefix) bool {
  737. for _, p := range preferredRanges {
  738. if p.Contains(ip) {
  739. return true
  740. }
  741. }
  742. return false
  743. }