remote_list.go 19 KB

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