remote_list.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  1. package nebula
  2. import (
  3. "bytes"
  4. "context"
  5. "net"
  6. "net/netip"
  7. "sort"
  8. "strconv"
  9. "sync"
  10. "sync/atomic"
  11. "time"
  12. "github.com/sirupsen/logrus"
  13. "github.com/slackhq/nebula/iputil"
  14. "github.com/slackhq/nebula/udp"
  15. )
  16. // forEachFunc is used to benefit folks that want to do work inside the lock
  17. type forEachFunc func(addr *udp.Addr, preferred bool)
  18. // The checkFuncs here are to simplify bulk importing LH query response logic into a single function (reset slice and iterate)
  19. type checkFuncV4 func(vpnIp iputil.VpnIp, to *Ip4AndPort) bool
  20. type checkFuncV6 func(vpnIp iputil.VpnIp, to *Ip6AndPort) bool
  21. // CacheMap is a struct that better represents the lighthouse cache for humans
  22. // The string key is the owners vpnIp
  23. type CacheMap map[string]*Cache
  24. // Cache is the other part of CacheMap to better represent the lighthouse cache for humans
  25. // We don't reason about ipv4 vs ipv6 here
  26. type Cache struct {
  27. Learned []*udp.Addr `json:"learned,omitempty"`
  28. Reported []*udp.Addr `json:"reported,omitempty"`
  29. Relay []*net.IP `json:"relay"`
  30. }
  31. //TODO: Seems like we should plop static host entries in here too since the are protected by the lighthouse from deletion
  32. // We will never clean learned/reported information for them as it stands today
  33. // cache is an internal struct that splits v4 and v6 addresses inside the cache map
  34. type cache struct {
  35. v4 *cacheV4
  36. v6 *cacheV6
  37. relay *cacheRelay
  38. }
  39. type cacheRelay struct {
  40. relay []uint32
  41. }
  42. // cacheV4 stores learned and reported ipv4 records under cache
  43. type cacheV4 struct {
  44. learned *Ip4AndPort
  45. reported []*Ip4AndPort
  46. }
  47. // cacheV4 stores learned and reported ipv6 records under cache
  48. type cacheV6 struct {
  49. learned *Ip6AndPort
  50. reported []*Ip6AndPort
  51. }
  52. type hostnamePort struct {
  53. name string
  54. port uint16
  55. }
  56. type hostnamesResults struct {
  57. hostnames []hostnamePort
  58. network string
  59. lookupTimeout time.Duration
  60. cancelFn func()
  61. l *logrus.Logger
  62. ips atomic.Pointer[map[netip.AddrPort]struct{}]
  63. }
  64. func NewHostnameResults(ctx context.Context, l *logrus.Logger, d time.Duration, network string, timeout time.Duration, hostPorts []string, onUpdate func()) (*hostnamesResults, error) {
  65. r := &hostnamesResults{
  66. hostnames: make([]hostnamePort, len(hostPorts)),
  67. network: network,
  68. lookupTimeout: timeout,
  69. l: l,
  70. }
  71. // Fastrack IP addresses to ensure they're immediately available for use.
  72. // DNS lookups for hostnames that aren't hardcoded IP's will happen in a background goroutine.
  73. performBackgroundLookup := false
  74. ips := map[netip.AddrPort]struct{}{}
  75. for idx, hostPort := range hostPorts {
  76. rIp, sPort, err := net.SplitHostPort(hostPort)
  77. if err != nil {
  78. return nil, err
  79. }
  80. iPort, err := strconv.Atoi(sPort)
  81. if err != nil {
  82. return nil, err
  83. }
  84. r.hostnames[idx] = hostnamePort{name: rIp, port: uint16(iPort)}
  85. addr, err := netip.ParseAddr(rIp)
  86. if err != nil {
  87. // This address is a hostname, not an IP address
  88. performBackgroundLookup = true
  89. continue
  90. }
  91. // Save the IP address immediately
  92. ips[netip.AddrPortFrom(addr, uint16(iPort))] = struct{}{}
  93. }
  94. r.ips.Store(&ips)
  95. // Time for the DNS lookup goroutine
  96. if performBackgroundLookup {
  97. newCtx, cancel := context.WithCancel(ctx)
  98. r.cancelFn = cancel
  99. ticker := time.NewTicker(d)
  100. go func() {
  101. defer ticker.Stop()
  102. for {
  103. netipAddrs := map[netip.AddrPort]struct{}{}
  104. for _, hostPort := range r.hostnames {
  105. timeoutCtx, timeoutCancel := context.WithTimeout(ctx, r.lookupTimeout)
  106. addrs, err := net.DefaultResolver.LookupNetIP(timeoutCtx, r.network, hostPort.name)
  107. timeoutCancel()
  108. if err != nil {
  109. l.WithFields(logrus.Fields{"hostname": hostPort.name, "network": r.network}).WithError(err).Error("DNS resolution failed for static_map host")
  110. continue
  111. }
  112. for _, a := range addrs {
  113. netipAddrs[netip.AddrPortFrom(a, 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.WithFields(logrus.Fields{"origSet": origSet, "newSet": netipAddrs}).Info("DNS results changed for host list")
  134. r.ips.Store(&netipAddrs)
  135. onUpdate()
  136. }
  137. select {
  138. case <-newCtx.Done():
  139. return
  140. case <-ticker.C:
  141. continue
  142. }
  143. }
  144. }()
  145. }
  146. return r, nil
  147. }
  148. func (hr *hostnamesResults) Cancel() {
  149. if hr != nil && hr.cancelFn != nil {
  150. hr.cancelFn()
  151. }
  152. }
  153. func (hr *hostnamesResults) GetIPs() []netip.AddrPort {
  154. var retSlice []netip.AddrPort
  155. if hr != nil {
  156. p := hr.ips.Load()
  157. if p != nil {
  158. for k := range *p {
  159. retSlice = append(retSlice, k)
  160. }
  161. }
  162. }
  163. return retSlice
  164. }
  165. // RemoteList is a unifying concept for lighthouse servers and clients as well as hostinfos.
  166. // It serves as a local cache of query replies, host update notifications, and locally learned addresses
  167. type RemoteList struct {
  168. // Every interaction with internals requires a lock!
  169. sync.RWMutex
  170. // A deduplicated set of addresses. Any accessor should lock beforehand.
  171. addrs []*udp.Addr
  172. // A set of relay addresses. VpnIp addresses that the remote identified as relays.
  173. relays []*iputil.VpnIp
  174. // These are maps to store v4 and v6 addresses per lighthouse
  175. // Map key is the vpnIp of the person that told us about this the cached entries underneath.
  176. // For learned addresses, this is the vpnIp that sent the packet
  177. cache map[iputil.VpnIp]*cache
  178. hr *hostnamesResults
  179. shouldAdd func(netip.Addr) bool
  180. // This is a list of remotes that we have tried to handshake with and have returned from the wrong vpn ip.
  181. // They should not be tried again during a handshake
  182. badRemotes []*udp.Addr
  183. // A flag that the cache may have changed and addrs needs to be rebuilt
  184. shouldRebuild bool
  185. }
  186. // NewRemoteList creates a new empty RemoteList
  187. func NewRemoteList(shouldAdd func(netip.Addr) bool) *RemoteList {
  188. return &RemoteList{
  189. addrs: make([]*udp.Addr, 0),
  190. relays: make([]*iputil.VpnIp, 0),
  191. cache: make(map[iputil.VpnIp]*cache),
  192. shouldAdd: shouldAdd,
  193. }
  194. }
  195. func (r *RemoteList) unlockedSetHostnamesResults(hr *hostnamesResults) {
  196. // Cancel any existing hostnamesResults DNS goroutine to release resources
  197. r.hr.Cancel()
  198. r.hr = hr
  199. }
  200. // Len locks and reports the size of the deduplicated address list
  201. // The deduplication work may need to occur here, so you must pass preferredRanges
  202. func (r *RemoteList) Len(preferredRanges []*net.IPNet) int {
  203. r.Rebuild(preferredRanges)
  204. r.RLock()
  205. defer r.RUnlock()
  206. return len(r.addrs)
  207. }
  208. // ForEach locks and will call the forEachFunc for every deduplicated address in the list
  209. // The deduplication work may need to occur here, so you must pass preferredRanges
  210. func (r *RemoteList) ForEach(preferredRanges []*net.IPNet, forEach forEachFunc) {
  211. r.Rebuild(preferredRanges)
  212. r.RLock()
  213. for _, v := range r.addrs {
  214. forEach(v, isPreferred(v.IP, preferredRanges))
  215. }
  216. r.RUnlock()
  217. }
  218. // CopyAddrs locks and makes a deep copy of the deduplicated address list
  219. // The deduplication work may need to occur here, so you must pass preferredRanges
  220. func (r *RemoteList) CopyAddrs(preferredRanges []*net.IPNet) []*udp.Addr {
  221. if r == nil {
  222. return nil
  223. }
  224. r.Rebuild(preferredRanges)
  225. r.RLock()
  226. defer r.RUnlock()
  227. c := make([]*udp.Addr, len(r.addrs))
  228. for i, v := range r.addrs {
  229. c[i] = v.Copy()
  230. }
  231. return c
  232. }
  233. // LearnRemote locks and sets the learned slot for the owner vpn ip to the provided addr
  234. // Currently this is only needed when HostInfo.SetRemote is called as that should cover both handshaking and roaming.
  235. // It will mark the deduplicated address list as dirty, so do not call it unless new information is available
  236. // TODO: this needs to support the allow list list
  237. func (r *RemoteList) LearnRemote(ownerVpnIp iputil.VpnIp, addr *udp.Addr) {
  238. r.Lock()
  239. defer r.Unlock()
  240. if v4 := addr.IP.To4(); v4 != nil {
  241. r.unlockedSetLearnedV4(ownerVpnIp, NewIp4AndPort(v4, uint32(addr.Port)))
  242. } else {
  243. r.unlockedSetLearnedV6(ownerVpnIp, NewIp6AndPort(addr.IP, uint32(addr.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([]*udp.Addr, 0),
  257. Reported: make([]*udp.Addr, 0),
  258. Relay: make([]*net.IP, 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, NewUDPAddrFromLH4(mc.v4.learned))
  269. }
  270. for _, a := range mc.v4.reported {
  271. c.Reported = append(c.Reported, NewUDPAddrFromLH4(a))
  272. }
  273. }
  274. if mc.v6 != nil {
  275. if mc.v6.learned != nil {
  276. c.Learned = append(c.Learned, NewUDPAddrFromLH6(mc.v6.learned))
  277. }
  278. for _, a := range mc.v6.reported {
  279. c.Reported = append(c.Reported, NewUDPAddrFromLH6(a))
  280. }
  281. }
  282. if mc.relay != nil {
  283. for _, a := range mc.relay.relay {
  284. nip := iputil.VpnIp(a).ToIP()
  285. c.Relay = append(c.Relay, &nip)
  286. }
  287. }
  288. }
  289. return &cm
  290. }
  291. // BlockRemote locks and records the address as bad, it will be excluded from the deduplicated address list
  292. func (r *RemoteList) BlockRemote(bad *udp.Addr) {
  293. if bad == nil {
  294. // relays can have nil udp Addrs
  295. return
  296. }
  297. r.Lock()
  298. defer r.Unlock()
  299. // Check if we already blocked this addr
  300. if r.unlockedIsBad(bad) {
  301. return
  302. }
  303. // We copy here because we are taking something else's memory and we can't trust everything
  304. r.badRemotes = append(r.badRemotes, bad.Copy())
  305. // Mark the next interaction must recollect/dedupe
  306. r.shouldRebuild = true
  307. }
  308. // CopyBlockedRemotes locks and makes a deep copy of the blocked remotes list
  309. func (r *RemoteList) CopyBlockedRemotes() []*udp.Addr {
  310. r.RLock()
  311. defer r.RUnlock()
  312. c := make([]*udp.Addr, len(r.badRemotes))
  313. for i, v := range r.badRemotes {
  314. c[i] = v.Copy()
  315. }
  316. return c
  317. }
  318. // ResetBlockedRemotes locks and clears the blocked remotes list
  319. func (r *RemoteList) ResetBlockedRemotes() {
  320. r.Lock()
  321. r.badRemotes = nil
  322. r.Unlock()
  323. }
  324. // Rebuild locks and generates the deduplicated address list only if there is work to be done
  325. // There is generally no reason to call this directly but it is safe to do so
  326. func (r *RemoteList) Rebuild(preferredRanges []*net.IPNet) {
  327. r.Lock()
  328. defer r.Unlock()
  329. // Only rebuild if the cache changed
  330. //TODO: shouldRebuild is probably pointless as we don't check for actual change when lighthouse updates come in
  331. if r.shouldRebuild {
  332. r.unlockedCollect()
  333. r.shouldRebuild = false
  334. }
  335. // Always re-sort, preferredRanges can change via HUP
  336. r.unlockedSort(preferredRanges)
  337. }
  338. // unlockedIsBad assumes you have the write lock and checks if the remote matches any entry in the blocked address list
  339. func (r *RemoteList) unlockedIsBad(remote *udp.Addr) bool {
  340. for _, v := range r.badRemotes {
  341. if v.Equals(remote) {
  342. return true
  343. }
  344. }
  345. return false
  346. }
  347. // unlockedSetLearnedV4 assumes you have the write lock and sets the current learned address for this owner and marks the
  348. // deduplicated address list as dirty
  349. func (r *RemoteList) unlockedSetLearnedV4(ownerVpnIp iputil.VpnIp, to *Ip4AndPort) {
  350. r.shouldRebuild = true
  351. r.unlockedGetOrMakeV4(ownerVpnIp).learned = to
  352. }
  353. // unlockedSetV4 assumes you have the write lock and resets the reported list of ips for this owner to the list provided
  354. // and marks the deduplicated address list as dirty
  355. func (r *RemoteList) unlockedSetV4(ownerVpnIp iputil.VpnIp, vpnIp iputil.VpnIp, to []*Ip4AndPort, check checkFuncV4) {
  356. r.shouldRebuild = true
  357. c := r.unlockedGetOrMakeV4(ownerVpnIp)
  358. // Reset the slice
  359. c.reported = c.reported[:0]
  360. // We can't take their array but we can take their pointers
  361. for _, v := range to[:minInt(len(to), MaxRemotes)] {
  362. if check(vpnIp, v) {
  363. c.reported = append(c.reported, v)
  364. }
  365. }
  366. }
  367. func (r *RemoteList) unlockedSetRelay(ownerVpnIp iputil.VpnIp, vpnIp iputil.VpnIp, to []uint32) {
  368. r.shouldRebuild = true
  369. c := r.unlockedGetOrMakeRelay(ownerVpnIp)
  370. // Reset the slice
  371. c.relay = c.relay[:0]
  372. // We can't take their array but we can take their pointers
  373. c.relay = append(c.relay, to[:minInt(len(to), MaxRemotes)]...)
  374. }
  375. // unlockedPrependV4 assumes you have the write lock and prepends the address in the reported list for this owner
  376. // This is only useful for establishing static hosts
  377. func (r *RemoteList) unlockedPrependV4(ownerVpnIp iputil.VpnIp, to *Ip4AndPort) {
  378. r.shouldRebuild = true
  379. c := r.unlockedGetOrMakeV4(ownerVpnIp)
  380. // We are doing the easy append because this is rarely called
  381. c.reported = append([]*Ip4AndPort{to}, c.reported...)
  382. if len(c.reported) > MaxRemotes {
  383. c.reported = c.reported[:MaxRemotes]
  384. }
  385. }
  386. // unlockedSetLearnedV6 assumes you have the write lock and sets the current learned address for this owner and marks the
  387. // deduplicated address list as dirty
  388. func (r *RemoteList) unlockedSetLearnedV6(ownerVpnIp iputil.VpnIp, to *Ip6AndPort) {
  389. r.shouldRebuild = true
  390. r.unlockedGetOrMakeV6(ownerVpnIp).learned = to
  391. }
  392. // unlockedSetV6 assumes you have the write lock and resets the reported list of ips for this owner to the list provided
  393. // and marks the deduplicated address list as dirty
  394. func (r *RemoteList) unlockedSetV6(ownerVpnIp iputil.VpnIp, vpnIp iputil.VpnIp, to []*Ip6AndPort, check checkFuncV6) {
  395. r.shouldRebuild = true
  396. c := r.unlockedGetOrMakeV6(ownerVpnIp)
  397. // Reset the slice
  398. c.reported = c.reported[:0]
  399. // We can't take their array but we can take their pointers
  400. for _, v := range to[:minInt(len(to), MaxRemotes)] {
  401. if check(vpnIp, v) {
  402. c.reported = append(c.reported, v)
  403. }
  404. }
  405. }
  406. // unlockedPrependV6 assumes you have the write lock and prepends the address in the reported list for this owner
  407. // This is only useful for establishing static hosts
  408. func (r *RemoteList) unlockedPrependV6(ownerVpnIp iputil.VpnIp, to *Ip6AndPort) {
  409. r.shouldRebuild = true
  410. c := r.unlockedGetOrMakeV6(ownerVpnIp)
  411. // We are doing the easy append because this is rarely called
  412. c.reported = append([]*Ip6AndPort{to}, c.reported...)
  413. if len(c.reported) > MaxRemotes {
  414. c.reported = c.reported[:MaxRemotes]
  415. }
  416. }
  417. func (r *RemoteList) unlockedGetOrMakeRelay(ownerVpnIp iputil.VpnIp) *cacheRelay {
  418. am := r.cache[ownerVpnIp]
  419. if am == nil {
  420. am = &cache{}
  421. r.cache[ownerVpnIp] = am
  422. }
  423. // Avoid occupying memory for relay if we never have any
  424. if am.relay == nil {
  425. am.relay = &cacheRelay{}
  426. }
  427. return am.relay
  428. }
  429. // unlockedGetOrMakeV4 assumes you have the write lock and builds the cache and owner entry. Only the v4 pointer is established.
  430. // The caller must dirty the learned address cache if required
  431. func (r *RemoteList) unlockedGetOrMakeV4(ownerVpnIp iputil.VpnIp) *cacheV4 {
  432. am := r.cache[ownerVpnIp]
  433. if am == nil {
  434. am = &cache{}
  435. r.cache[ownerVpnIp] = am
  436. }
  437. // Avoid occupying memory for v6 addresses if we never have any
  438. if am.v4 == nil {
  439. am.v4 = &cacheV4{}
  440. }
  441. return am.v4
  442. }
  443. // unlockedGetOrMakeV6 assumes you have the write lock and builds the cache and owner entry. Only the v6 pointer is established.
  444. // The caller must dirty the learned address cache if required
  445. func (r *RemoteList) unlockedGetOrMakeV6(ownerVpnIp iputil.VpnIp) *cacheV6 {
  446. am := r.cache[ownerVpnIp]
  447. if am == nil {
  448. am = &cache{}
  449. r.cache[ownerVpnIp] = am
  450. }
  451. // Avoid occupying memory for v4 addresses if we never have any
  452. if am.v6 == nil {
  453. am.v6 = &cacheV6{}
  454. }
  455. return am.v6
  456. }
  457. // unlockedCollect assumes you have the write lock and collects/transforms the cache into the deduped address list.
  458. // The result of this function can contain duplicates. unlockedSort handles cleaning it.
  459. func (r *RemoteList) unlockedCollect() {
  460. addrs := r.addrs[:0]
  461. relays := r.relays[:0]
  462. for _, c := range r.cache {
  463. if c.v4 != nil {
  464. if c.v4.learned != nil {
  465. u := NewUDPAddrFromLH4(c.v4.learned)
  466. if !r.unlockedIsBad(u) {
  467. addrs = append(addrs, u)
  468. }
  469. }
  470. for _, v := range c.v4.reported {
  471. u := NewUDPAddrFromLH4(v)
  472. if !r.unlockedIsBad(u) {
  473. addrs = append(addrs, u)
  474. }
  475. }
  476. }
  477. if c.v6 != nil {
  478. if c.v6.learned != nil {
  479. u := NewUDPAddrFromLH6(c.v6.learned)
  480. if !r.unlockedIsBad(u) {
  481. addrs = append(addrs, u)
  482. }
  483. }
  484. for _, v := range c.v6.reported {
  485. u := NewUDPAddrFromLH6(v)
  486. if !r.unlockedIsBad(u) {
  487. addrs = append(addrs, u)
  488. }
  489. }
  490. }
  491. if c.relay != nil {
  492. for _, v := range c.relay.relay {
  493. ip := iputil.VpnIp(v)
  494. relays = append(relays, &ip)
  495. }
  496. }
  497. }
  498. dnsAddrs := r.hr.GetIPs()
  499. for _, addr := range dnsAddrs {
  500. if r.shouldAdd == nil || r.shouldAdd(addr.Addr()) {
  501. v6 := addr.Addr().As16()
  502. addrs = append(addrs, &udp.Addr{
  503. IP: v6[:],
  504. Port: addr.Port(),
  505. })
  506. }
  507. }
  508. r.addrs = addrs
  509. r.relays = relays
  510. }
  511. // unlockedSort assumes you have the write lock and performs the deduping and sorting of the address list
  512. func (r *RemoteList) unlockedSort(preferredRanges []*net.IPNet) {
  513. n := len(r.addrs)
  514. if n < 2 {
  515. return
  516. }
  517. lessFunc := func(i, j int) bool {
  518. a := r.addrs[i]
  519. b := r.addrs[j]
  520. // Preferred addresses first
  521. aPref := isPreferred(a.IP, preferredRanges)
  522. bPref := isPreferred(b.IP, preferredRanges)
  523. switch {
  524. case aPref && !bPref:
  525. // If i is preferred and j is not, i is less than j
  526. return true
  527. case !aPref && bPref:
  528. // If j is preferred then i is not due to the else, i is not less than j
  529. return false
  530. default:
  531. // Both i an j are either preferred or not, sort within that
  532. }
  533. // ipv6 addresses 2nd
  534. a4 := a.IP.To4()
  535. b4 := b.IP.To4()
  536. switch {
  537. case a4 == nil && b4 != nil:
  538. // If i is v6 and j is v4, i is less than j
  539. return true
  540. case a4 != nil && b4 == nil:
  541. // If j is v6 and i is v4, i is not less than j
  542. return false
  543. case a4 != nil && b4 != nil:
  544. // Special case for ipv4, a4 and b4 are not nil
  545. aPrivate := isPrivateIP(a4)
  546. bPrivate := isPrivateIP(b4)
  547. switch {
  548. case !aPrivate && bPrivate:
  549. // If i is a public ip (not private) and j is a private ip, i is less then j
  550. return true
  551. case aPrivate && !bPrivate:
  552. // If j is public (not private) then i is private due to the else, i is not less than j
  553. return false
  554. default:
  555. // Both i an j are either public or private, sort within that
  556. }
  557. default:
  558. // Both i an j are either ipv4 or ipv6, sort within that
  559. }
  560. // lexical order of ips 3rd
  561. c := bytes.Compare(a.IP, b.IP)
  562. if c == 0 {
  563. // Ips are the same, Lexical order of ports 4th
  564. return a.Port < b.Port
  565. }
  566. // Ip wasn't the same
  567. return c < 0
  568. }
  569. // Sort it
  570. sort.Slice(r.addrs, lessFunc)
  571. // Deduplicate
  572. a, b := 0, 1
  573. for b < n {
  574. if !r.addrs[a].Equals(r.addrs[b]) {
  575. a++
  576. if a != b {
  577. r.addrs[a], r.addrs[b] = r.addrs[b], r.addrs[a]
  578. }
  579. }
  580. b++
  581. }
  582. r.addrs = r.addrs[:a+1]
  583. return
  584. }
  585. // minInt returns the minimum integer of a or b
  586. func minInt(a, b int) int {
  587. if a < b {
  588. return a
  589. }
  590. return b
  591. }
  592. // isPreferred returns true of the ip is contained in the preferredRanges list
  593. func isPreferred(ip net.IP, preferredRanges []*net.IPNet) bool {
  594. //TODO: this would be better in a CIDR6Tree
  595. for _, p := range preferredRanges {
  596. if p.Contains(ip) {
  597. return true
  598. }
  599. }
  600. return false
  601. }
  602. var _, private24BitBlock, _ = net.ParseCIDR("10.0.0.0/8")
  603. var _, private20BitBlock, _ = net.ParseCIDR("172.16.0.0/12")
  604. var _, private16BitBlock, _ = net.ParseCIDR("192.168.0.0/16")
  605. // isPrivateIP returns true if the ip is contained by a rfc 1918 private range
  606. func isPrivateIP(ip net.IP) bool {
  607. //TODO: another great cidrtree option
  608. //TODO: Private for ipv6 or just let it ride?
  609. return private24BitBlock.Contains(ip) || private20BitBlock.Contains(ip) || private16BitBlock.Contains(ip)
  610. }