hostmap.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808
  1. package nebula
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "net"
  7. "sync"
  8. "time"
  9. "github.com/rcrowley/go-metrics"
  10. "github.com/sirupsen/logrus"
  11. "github.com/slackhq/nebula/cert"
  12. )
  13. //const ProbeLen = 100
  14. const PromoteEvery = 1000
  15. const MaxRemotes = 10
  16. // How long we should prevent roaming back to the previous IP.
  17. // This helps prevent flapping due to packets already in flight
  18. const RoamingSupressSeconds = 2
  19. type HostMap struct {
  20. sync.RWMutex //Because we concurrently read and write to our maps
  21. name string
  22. Indexes map[uint32]*HostInfo
  23. Hosts map[uint32]*HostInfo
  24. preferredRanges []*net.IPNet
  25. vpnCIDR *net.IPNet
  26. defaultRoute uint32
  27. unsafeRoutes *CIDRTree
  28. metricsEnabled bool
  29. }
  30. type HostInfo struct {
  31. remote *udpAddr
  32. Remotes []*HostInfoDest
  33. promoteCounter uint32
  34. ConnectionState *ConnectionState
  35. handshakeStart time.Time
  36. HandshakeReady bool
  37. HandshakeCounter int
  38. HandshakeComplete bool
  39. HandshakePacket map[uint8][]byte
  40. packetStore []*cachedPacket
  41. remoteIndexId uint32
  42. localIndexId uint32
  43. hostId uint32
  44. recvError int
  45. remoteCidr *CIDRTree
  46. lastRoam time.Time
  47. lastRoamRemote *udpAddr
  48. }
  49. type cachedPacket struct {
  50. messageType NebulaMessageType
  51. messageSubType NebulaMessageSubType
  52. callback packetCallback
  53. packet []byte
  54. }
  55. type packetCallback func(t NebulaMessageType, st NebulaMessageSubType, h *HostInfo, p, nb, out []byte)
  56. type HostInfoDest struct {
  57. active bool
  58. addr *udpAddr
  59. //probes [ProbeLen]bool
  60. probeCounter int
  61. }
  62. type Probe struct {
  63. Addr *net.UDPAddr
  64. Counter int
  65. }
  66. func NewHostMap(name string, vpnCIDR *net.IPNet, preferredRanges []*net.IPNet) *HostMap {
  67. h := map[uint32]*HostInfo{}
  68. i := map[uint32]*HostInfo{}
  69. m := HostMap{
  70. name: name,
  71. Indexes: i,
  72. Hosts: h,
  73. preferredRanges: preferredRanges,
  74. vpnCIDR: vpnCIDR,
  75. defaultRoute: 0,
  76. unsafeRoutes: NewCIDRTree(),
  77. }
  78. return &m
  79. }
  80. // UpdateStats takes a name and reports host and index counts to the stats collection system
  81. func (hm *HostMap) EmitStats(name string) {
  82. hm.RLock()
  83. hostLen := len(hm.Hosts)
  84. indexLen := len(hm.Indexes)
  85. hm.RUnlock()
  86. metrics.GetOrRegisterGauge("hostmap."+name+".hosts", nil).Update(int64(hostLen))
  87. metrics.GetOrRegisterGauge("hostmap."+name+".indexes", nil).Update(int64(indexLen))
  88. }
  89. func (hm *HostMap) GetIndexByVpnIP(vpnIP uint32) (uint32, error) {
  90. hm.RLock()
  91. if i, ok := hm.Hosts[vpnIP]; ok {
  92. index := i.localIndexId
  93. hm.RUnlock()
  94. return index, nil
  95. }
  96. hm.RUnlock()
  97. return 0, errors.New("vpn IP not found")
  98. }
  99. func (hm *HostMap) GetVpnIPByIndex(index uint32) (uint32, error) {
  100. hm.RLock()
  101. if i, ok := hm.Indexes[index]; ok {
  102. vpnIP := i.hostId
  103. hm.RUnlock()
  104. return vpnIP, nil
  105. }
  106. hm.RUnlock()
  107. return 0, errors.New("vpn IP not found")
  108. }
  109. func (hm *HostMap) Add(ip uint32, hostinfo *HostInfo) {
  110. hm.Lock()
  111. hm.Hosts[ip] = hostinfo
  112. hm.Unlock()
  113. }
  114. func (hm *HostMap) AddVpnIP(vpnIP uint32) *HostInfo {
  115. h := &HostInfo{}
  116. hm.RLock()
  117. if _, ok := hm.Hosts[vpnIP]; !ok {
  118. hm.RUnlock()
  119. h = &HostInfo{
  120. Remotes: []*HostInfoDest{},
  121. promoteCounter: 0,
  122. hostId: vpnIP,
  123. HandshakePacket: make(map[uint8][]byte, 0),
  124. }
  125. hm.Lock()
  126. hm.Hosts[vpnIP] = h
  127. hm.Unlock()
  128. return h
  129. } else {
  130. h = hm.Hosts[vpnIP]
  131. hm.RUnlock()
  132. return h
  133. }
  134. }
  135. func (hm *HostMap) DeleteVpnIP(vpnIP uint32) {
  136. hm.Lock()
  137. delete(hm.Hosts, vpnIP)
  138. if len(hm.Hosts) == 0 {
  139. hm.Hosts = map[uint32]*HostInfo{}
  140. }
  141. hm.Unlock()
  142. if l.Level >= logrus.DebugLevel {
  143. l.WithField("hostMap", m{"mapName": hm.name, "vpnIp": IntIp(vpnIP), "mapTotalSize": len(hm.Hosts)}).
  144. Debug("Hostmap vpnIp deleted")
  145. }
  146. }
  147. func (hm *HostMap) AddIndex(index uint32, ci *ConnectionState) (*HostInfo, error) {
  148. hm.Lock()
  149. if _, ok := hm.Indexes[index]; !ok {
  150. h := &HostInfo{
  151. ConnectionState: ci,
  152. Remotes: []*HostInfoDest{},
  153. localIndexId: index,
  154. HandshakePacket: make(map[uint8][]byte, 0),
  155. }
  156. hm.Indexes[index] = h
  157. l.WithField("hostMap", m{"mapName": hm.name, "indexNumber": index, "mapTotalSize": len(hm.Indexes),
  158. "hostinfo": m{"existing": false, "localIndexId": h.localIndexId, "hostId": IntIp(h.hostId)}}).
  159. Debug("Hostmap index added")
  160. hm.Unlock()
  161. return h, nil
  162. }
  163. hm.Unlock()
  164. return nil, fmt.Errorf("refusing to overwrite existing index: %d", index)
  165. }
  166. func (hm *HostMap) AddIndexHostInfo(index uint32, h *HostInfo) {
  167. hm.Lock()
  168. h.localIndexId = index
  169. hm.Indexes[index] = h
  170. hm.Unlock()
  171. if l.Level > logrus.DebugLevel {
  172. l.WithField("hostMap", m{"mapName": hm.name, "indexNumber": index, "mapTotalSize": len(hm.Indexes),
  173. "hostinfo": m{"existing": true, "localIndexId": h.localIndexId, "hostId": IntIp(h.hostId)}}).
  174. Debug("Hostmap index added")
  175. }
  176. }
  177. func (hm *HostMap) AddVpnIPHostInfo(vpnIP uint32, h *HostInfo) {
  178. hm.Lock()
  179. h.hostId = vpnIP
  180. hm.Hosts[vpnIP] = h
  181. hm.Unlock()
  182. if l.Level > logrus.DebugLevel {
  183. l.WithField("hostMap", m{"mapName": hm.name, "vpnIp": IntIp(vpnIP), "mapTotalSize": len(hm.Hosts),
  184. "hostinfo": m{"existing": true, "localIndexId": h.localIndexId, "hostId": IntIp(h.hostId)}}).
  185. Debug("Hostmap vpnIp added")
  186. }
  187. }
  188. func (hm *HostMap) DeleteIndex(index uint32) {
  189. hm.Lock()
  190. delete(hm.Indexes, index)
  191. if len(hm.Indexes) == 0 {
  192. hm.Indexes = map[uint32]*HostInfo{}
  193. }
  194. hm.Unlock()
  195. if l.Level >= logrus.DebugLevel {
  196. l.WithField("hostMap", m{"mapName": hm.name, "indexNumber": index, "mapTotalSize": len(hm.Indexes)}).
  197. Debug("Hostmap index deleted")
  198. }
  199. }
  200. func (hm *HostMap) QueryIndex(index uint32) (*HostInfo, error) {
  201. //TODO: we probably just want ot return bool instead of error, or at least a static error
  202. hm.RLock()
  203. if h, ok := hm.Indexes[index]; ok {
  204. hm.RUnlock()
  205. return h, nil
  206. } else {
  207. hm.RUnlock()
  208. return nil, errors.New("unable to find index")
  209. }
  210. }
  211. // This function needs to range because we don't keep a map of remote indexes.
  212. func (hm *HostMap) QueryReverseIndex(index uint32) (*HostInfo, error) {
  213. hm.RLock()
  214. for _, h := range hm.Indexes {
  215. if h.ConnectionState != nil && h.remoteIndexId == index {
  216. hm.RUnlock()
  217. return h, nil
  218. }
  219. }
  220. for _, h := range hm.Hosts {
  221. if h.ConnectionState != nil && h.remoteIndexId == index {
  222. hm.RUnlock()
  223. return h, nil
  224. }
  225. }
  226. hm.RUnlock()
  227. return nil, fmt.Errorf("unable to find reverse index or connectionstate nil in %s hostmap", hm.name)
  228. }
  229. func (hm *HostMap) AddRemote(vpnIp uint32, remote *udpAddr) *HostInfo {
  230. hm.Lock()
  231. i, v := hm.Hosts[vpnIp]
  232. if v {
  233. i.AddRemote(*remote)
  234. } else {
  235. i = &HostInfo{
  236. Remotes: []*HostInfoDest{NewHostInfoDest(remote)},
  237. promoteCounter: 0,
  238. hostId: vpnIp,
  239. HandshakePacket: make(map[uint8][]byte, 0),
  240. }
  241. i.remote = i.Remotes[0].addr
  242. hm.Hosts[vpnIp] = i
  243. l.WithField("hostMap", m{"mapName": hm.name, "vpnIp": IntIp(vpnIp), "udpAddr": remote, "mapTotalSize": len(hm.Hosts)}).
  244. Debug("Hostmap remote ip added")
  245. }
  246. i.ForcePromoteBest(hm.preferredRanges)
  247. hm.Unlock()
  248. return i
  249. }
  250. func (hm *HostMap) QueryVpnIP(vpnIp uint32) (*HostInfo, error) {
  251. return hm.queryVpnIP(vpnIp, nil)
  252. }
  253. // PromoteBestQueryVpnIP will attempt to lazily switch to the best remote every
  254. // `PromoteEvery` calls to this function for a given host.
  255. func (hm *HostMap) PromoteBestQueryVpnIP(vpnIp uint32, ifce *Interface) (*HostInfo, error) {
  256. return hm.queryVpnIP(vpnIp, ifce)
  257. }
  258. func (hm *HostMap) queryVpnIP(vpnIp uint32, promoteIfce *Interface) (*HostInfo, error) {
  259. hm.RLock()
  260. if h, ok := hm.Hosts[vpnIp]; ok {
  261. if promoteIfce != nil {
  262. h.TryPromoteBest(hm.preferredRanges, promoteIfce)
  263. }
  264. //fmt.Println(h.remote)
  265. hm.RUnlock()
  266. return h, nil
  267. } else {
  268. //return &net.UDPAddr{}, nil, errors.New("Unable to find host")
  269. hm.RUnlock()
  270. /*
  271. if lightHouse != nil {
  272. lightHouse.Query(vpnIp)
  273. return nil, errors.New("Unable to find host")
  274. }
  275. */
  276. return nil, errors.New("unable to find host")
  277. }
  278. }
  279. func (hm *HostMap) queryUnsafeRoute(ip uint32) uint32 {
  280. r := hm.unsafeRoutes.MostSpecificContains(ip)
  281. if r != nil {
  282. return r.(uint32)
  283. } else {
  284. return 0
  285. }
  286. }
  287. func (hm *HostMap) CheckHandshakeCompleteIP(vpnIP uint32) bool {
  288. hm.RLock()
  289. if i, ok := hm.Hosts[vpnIP]; ok {
  290. if i == nil {
  291. hm.RUnlock()
  292. return false
  293. }
  294. complete := i.HandshakeComplete
  295. hm.RUnlock()
  296. return complete
  297. }
  298. hm.RUnlock()
  299. return false
  300. }
  301. func (hm *HostMap) CheckHandshakeCompleteIndex(index uint32) bool {
  302. hm.RLock()
  303. if i, ok := hm.Indexes[index]; ok {
  304. if i == nil {
  305. hm.RUnlock()
  306. return false
  307. }
  308. complete := i.HandshakeComplete
  309. hm.RUnlock()
  310. return complete
  311. }
  312. hm.RUnlock()
  313. return false
  314. }
  315. func (hm *HostMap) ClearRemotes(vpnIP uint32) {
  316. hm.Lock()
  317. i := hm.Hosts[vpnIP]
  318. if i == nil {
  319. hm.Unlock()
  320. return
  321. }
  322. i.remote = nil
  323. i.Remotes = nil
  324. hm.Unlock()
  325. }
  326. func (hm *HostMap) SetDefaultRoute(ip uint32) {
  327. hm.defaultRoute = ip
  328. }
  329. func (hm *HostMap) PunchList() []*udpAddr {
  330. var list []*udpAddr
  331. hm.RLock()
  332. for _, v := range hm.Hosts {
  333. for _, r := range v.Remotes {
  334. list = append(list, r.addr)
  335. }
  336. // if h, ok := hm.Hosts[vpnIp]; ok {
  337. // hm.Hosts[vpnIp].PromoteBest(hm.preferredRanges, false)
  338. //fmt.Println(h.remote)
  339. // }
  340. }
  341. hm.RUnlock()
  342. return list
  343. }
  344. func (hm *HostMap) Punchy(conn *udpConn) {
  345. var metricsTxPunchy metrics.Counter
  346. if hm.metricsEnabled {
  347. metricsTxPunchy = metrics.GetOrRegisterCounter("messages.tx.punchy", nil)
  348. } else {
  349. metricsTxPunchy = metrics.NilCounter{}
  350. }
  351. for {
  352. for _, addr := range hm.PunchList() {
  353. metricsTxPunchy.Inc(1)
  354. conn.WriteTo([]byte{1}, addr)
  355. }
  356. time.Sleep(time.Second * 30)
  357. }
  358. }
  359. func (hm *HostMap) addUnsafeRoutes(routes *[]route) {
  360. for _, r := range *routes {
  361. l.WithField("route", r.route).WithField("via", r.via).Warn("Adding UNSAFE Route")
  362. hm.unsafeRoutes.AddCIDR(r.route, ip2int(*r.via))
  363. }
  364. }
  365. func (i *HostInfo) MarshalJSON() ([]byte, error) {
  366. return json.Marshal(m{
  367. "remote": i.remote,
  368. "remotes": i.Remotes,
  369. "promote_counter": i.promoteCounter,
  370. "connection_state": i.ConnectionState,
  371. "handshake_start": i.handshakeStart,
  372. "handshake_ready": i.HandshakeReady,
  373. "handshake_counter": i.HandshakeCounter,
  374. "handshake_complete": i.HandshakeComplete,
  375. "handshake_packet": i.HandshakePacket,
  376. "packet_store": i.packetStore,
  377. "remote_index": i.remoteIndexId,
  378. "local_index": i.localIndexId,
  379. "host_id": int2ip(i.hostId),
  380. "receive_errors": i.recvError,
  381. "last_roam": i.lastRoam,
  382. "last_roam_remote": i.lastRoamRemote,
  383. })
  384. }
  385. func (i *HostInfo) BindConnectionState(cs *ConnectionState) {
  386. i.ConnectionState = cs
  387. }
  388. func (i *HostInfo) TryPromoteBest(preferredRanges []*net.IPNet, ifce *Interface) {
  389. if i.remote == nil {
  390. i.ForcePromoteBest(preferredRanges)
  391. return
  392. }
  393. i.promoteCounter++
  394. if i.promoteCounter%PromoteEvery == 0 {
  395. // return early if we are already on a preferred remote
  396. rIP := udp2ip(i.remote)
  397. for _, l := range preferredRanges {
  398. if l.Contains(rIP) {
  399. return
  400. }
  401. }
  402. // We re-query the lighthouse periodically while sending packets, so
  403. // check for new remotes in our local lighthouse cache
  404. ips := ifce.lightHouse.QueryCache(i.hostId)
  405. for _, ip := range ips {
  406. i.AddRemote(ip)
  407. }
  408. best, preferred := i.getBestRemote(preferredRanges)
  409. if preferred && !best.Equals(i.remote) {
  410. // Try to send a test packet to that host, this should
  411. // cause it to detect a roaming event and switch remotes
  412. ifce.send(test, testRequest, i.ConnectionState, i, best, []byte(""), make([]byte, 12, 12), make([]byte, mtu))
  413. }
  414. }
  415. }
  416. func (i *HostInfo) ForcePromoteBest(preferredRanges []*net.IPNet) {
  417. best, _ := i.getBestRemote(preferredRanges)
  418. if best != nil {
  419. i.remote = best
  420. }
  421. }
  422. func (i *HostInfo) getBestRemote(preferredRanges []*net.IPNet) (best *udpAddr, preferred bool) {
  423. if len(i.Remotes) > 0 {
  424. for _, r := range i.Remotes {
  425. rIP := udp2ip(r.addr)
  426. for _, l := range preferredRanges {
  427. if l.Contains(rIP) {
  428. return r.addr, true
  429. }
  430. }
  431. if best == nil || !PrivateIP(rIP) {
  432. best = r.addr
  433. }
  434. /*
  435. for _, r := range i.Remotes {
  436. // Must have > 80% probe success to be considered.
  437. //fmt.Println("GRADE:", r.addr.IP, r.Grade())
  438. if r.Grade() > float64(.8) {
  439. if localToMe.Contains(r.addr.IP) == true {
  440. best = r.addr
  441. break
  442. //i.remote = i.Remotes[c].addr
  443. } else {
  444. //}
  445. }
  446. */
  447. }
  448. return best, false
  449. }
  450. return nil, false
  451. }
  452. // rotateRemote will move remote to the next ip in the list of remote ips for this host
  453. // This is different than PromoteBest in that what is algorithmically best may not actually work.
  454. // Only known use case is when sending a stage 0 handshake.
  455. // It may be better to just send stage 0 handshakes to all known ips and sort it out in the receiver.
  456. func (i *HostInfo) rotateRemote() {
  457. // We have 0, can't rotate
  458. if len(i.Remotes) < 1 {
  459. return
  460. }
  461. if i.remote == nil {
  462. i.remote = i.Remotes[0].addr
  463. return
  464. }
  465. // We want to look at all but the very last entry since that is handled at the end
  466. for x := 0; x < len(i.Remotes)-1; x++ {
  467. // Find our current position and move to the next one in the list
  468. if i.Remotes[x].addr.Equals(i.remote) {
  469. i.remote = i.Remotes[x+1].addr
  470. return
  471. }
  472. }
  473. // Our current position was likely the last in the list, start over at 0
  474. i.remote = i.Remotes[0].addr
  475. }
  476. func (i *HostInfo) cachePacket(t NebulaMessageType, st NebulaMessageSubType, packet []byte, f packetCallback) {
  477. //TODO: return the error so we can log with more context
  478. if len(i.packetStore) < 100 {
  479. tempPacket := make([]byte, len(packet))
  480. copy(tempPacket, packet)
  481. //l.WithField("trace", string(debug.Stack())).Error("Caching packet", tempPacket)
  482. i.packetStore = append(i.packetStore, &cachedPacket{t, st, f, tempPacket})
  483. i.logger().
  484. WithField("length", len(i.packetStore)).
  485. WithField("stored", true).
  486. Debugf("Packet store")
  487. } else if l.Level >= logrus.DebugLevel {
  488. i.logger().
  489. WithField("length", len(i.packetStore)).
  490. WithField("stored", false).
  491. Debugf("Packet store")
  492. }
  493. }
  494. // handshakeComplete will set the connection as ready to communicate, as well as flush any stored packets
  495. func (i *HostInfo) handshakeComplete() {
  496. //TODO: I'm not certain the distinction between handshake complete and ConnectionState being ready matters because:
  497. //TODO: HandshakeComplete means send stored packets and ConnectionState.ready means we are ready to send
  498. //TODO: if the transition from HandhsakeComplete to ConnectionState.ready happens all within this function they are identical
  499. i.ConnectionState.queueLock.Lock()
  500. i.HandshakeComplete = true
  501. //TODO: this should be managed by the handshake state machine to set it based on how many handshake were seen.
  502. // Clamping it to 2 gets us out of the woods for now
  503. *i.ConnectionState.messageCounter = 2
  504. i.logger().Debugf("Sending %d stored packets", len(i.packetStore))
  505. nb := make([]byte, 12, 12)
  506. out := make([]byte, mtu)
  507. for _, cp := range i.packetStore {
  508. cp.callback(cp.messageType, cp.messageSubType, i, cp.packet, nb, out)
  509. }
  510. i.packetStore = make([]*cachedPacket, 0)
  511. i.ConnectionState.ready = true
  512. i.ConnectionState.queueLock.Unlock()
  513. i.ConnectionState.certState = nil
  514. }
  515. func (i *HostInfo) RemoteUDPAddrs() []*udpAddr {
  516. var addrs []*udpAddr
  517. for _, r := range i.Remotes {
  518. addrs = append(addrs, r.addr)
  519. }
  520. return addrs
  521. }
  522. func (i *HostInfo) GetCert() *cert.NebulaCertificate {
  523. if i.ConnectionState != nil {
  524. return i.ConnectionState.peerCert
  525. }
  526. return nil
  527. }
  528. func (i *HostInfo) AddRemote(r udpAddr) *udpAddr {
  529. remote := &r
  530. //add := true
  531. for _, r := range i.Remotes {
  532. if r.addr.Equals(remote) {
  533. return r.addr
  534. //add = false
  535. }
  536. }
  537. // Trim this down if necessary
  538. if len(i.Remotes) > MaxRemotes {
  539. i.Remotes = i.Remotes[len(i.Remotes)-MaxRemotes:]
  540. }
  541. i.Remotes = append(i.Remotes, NewHostInfoDest(remote))
  542. return remote
  543. //l.Debugf("Added remote %s for vpn ip", remote)
  544. }
  545. func (i *HostInfo) SetRemote(remote udpAddr) {
  546. i.remote = i.AddRemote(remote)
  547. }
  548. func (i *HostInfo) ClearRemotes() {
  549. i.remote = nil
  550. i.Remotes = []*HostInfoDest{}
  551. }
  552. func (i *HostInfo) ClearConnectionState() {
  553. i.ConnectionState = nil
  554. }
  555. func (i *HostInfo) RecvErrorExceeded() bool {
  556. if i.recvError < 3 {
  557. i.recvError += 1
  558. return false
  559. }
  560. return true
  561. }
  562. func (i *HostInfo) CreateRemoteCIDR(c *cert.NebulaCertificate) {
  563. if len(c.Details.Ips) == 1 && len(c.Details.Subnets) == 0 {
  564. // Simple case, no CIDRTree needed
  565. return
  566. }
  567. remoteCidr := NewCIDRTree()
  568. for _, ip := range c.Details.Ips {
  569. remoteCidr.AddCIDR(&net.IPNet{IP: ip.IP, Mask: net.IPMask{255, 255, 255, 255}}, struct{}{})
  570. }
  571. for _, n := range c.Details.Subnets {
  572. remoteCidr.AddCIDR(n, struct{}{})
  573. }
  574. i.remoteCidr = remoteCidr
  575. }
  576. func (i *HostInfo) logger() *logrus.Entry {
  577. if i == nil {
  578. return logrus.NewEntry(l)
  579. }
  580. li := l.WithField("vpnIp", IntIp(i.hostId))
  581. if connState := i.ConnectionState; connState != nil {
  582. if peerCert := connState.peerCert; peerCert != nil {
  583. li = li.WithField("certName", peerCert.Details.Name)
  584. }
  585. }
  586. return li
  587. }
  588. //########################
  589. func NewHostInfoDest(addr *udpAddr) *HostInfoDest {
  590. i := &HostInfoDest{
  591. addr: addr,
  592. }
  593. return i
  594. }
  595. func (hid *HostInfoDest) MarshalJSON() ([]byte, error) {
  596. return json.Marshal(m{
  597. "active": hid.active,
  598. "address": hid.addr,
  599. "probe_count": hid.probeCounter,
  600. })
  601. }
  602. /*
  603. func (hm *HostMap) DebugRemotes(vpnIp uint32) string {
  604. s := "\n"
  605. for _, h := range hm.Hosts {
  606. for _, r := range h.Remotes {
  607. s += fmt.Sprintf("%s : %d ## %v\n", r.addr.IP.String(), r.addr.Port, r.probes)
  608. }
  609. }
  610. return s
  611. }
  612. func (d *HostInfoDest) Grade() float64 {
  613. c1 := ProbeLen
  614. for n := len(d.probes) - 1; n >= 0; n-- {
  615. if d.probes[n] == true {
  616. c1 -= 1
  617. }
  618. }
  619. return float64(c1) / float64(ProbeLen)
  620. }
  621. func (d *HostInfoDest) Grade() (float64, float64, float64) {
  622. c1 := ProbeLen
  623. c2 := ProbeLen / 2
  624. c2c := ProbeLen - ProbeLen/2
  625. c3 := ProbeLen / 5
  626. c3c := ProbeLen - ProbeLen/5
  627. for n := len(d.probes) - 1; n >= 0; n-- {
  628. if d.probes[n] == true {
  629. c1 -= 1
  630. if n >= c2c {
  631. c2 -= 1
  632. if n >= c3c {
  633. c3 -= 1
  634. }
  635. }
  636. }
  637. //if n >= d {
  638. }
  639. return float64(c3) / float64(ProbeLen/5), float64(c2) / float64(ProbeLen/2), float64(c1) / float64(ProbeLen)
  640. //return float64(c1) / float64(ProbeLen), float64(c2) / float64(ProbeLen/2), float64(c3) / float64(ProbeLen/5)
  641. }
  642. func (i *HostInfo) HandleReply(addr *net.UDPAddr, counter int) {
  643. for _, r := range i.Remotes {
  644. if r.addr.IP.Equal(addr.IP) && r.addr.Port == addr.Port {
  645. r.ProbeReceived(counter)
  646. }
  647. }
  648. }
  649. func (i *HostInfo) Probes() []*Probe {
  650. p := []*Probe{}
  651. for _, d := range i.Remotes {
  652. p = append(p, &Probe{Addr: d.addr, Counter: d.Probe()})
  653. }
  654. return p
  655. }
  656. func (d *HostInfoDest) Probe() int {
  657. //d.probes = append(d.probes, true)
  658. d.probeCounter++
  659. d.probes[d.probeCounter%ProbeLen] = true
  660. return d.probeCounter
  661. //return d.probeCounter
  662. }
  663. func (d *HostInfoDest) ProbeReceived(probeCount int) {
  664. if probeCount >= (d.probeCounter - ProbeLen) {
  665. //fmt.Println("PROBE WORKED", probeCount)
  666. //fmt.Println(d.addr, d.Grade())
  667. d.probes[probeCount%ProbeLen] = false
  668. }
  669. }
  670. */
  671. // Utility functions
  672. func localIps(allowList *AllowList) *[]net.IP {
  673. //FIXME: This function is pretty garbage
  674. var ips []net.IP
  675. ifaces, _ := net.Interfaces()
  676. for _, i := range ifaces {
  677. allow := allowList.AllowName(i.Name)
  678. l.WithField("interfaceName", i.Name).WithField("allow", allow).Debug("localAllowList.AllowName")
  679. if !allow {
  680. continue
  681. }
  682. addrs, _ := i.Addrs()
  683. for _, addr := range addrs {
  684. var ip net.IP
  685. switch v := addr.(type) {
  686. case *net.IPNet:
  687. //continue
  688. ip = v.IP
  689. case *net.IPAddr:
  690. ip = v.IP
  691. }
  692. if ip.To4() != nil && ip.IsLoopback() == false {
  693. allow := allowList.Allow(ip2int(ip))
  694. l.WithField("localIp", ip).WithField("allow", allow).Debug("localAllowList.Allow")
  695. if !allow {
  696. continue
  697. }
  698. ips = append(ips, ip)
  699. }
  700. }
  701. }
  702. return &ips
  703. }
  704. func PrivateIP(ip net.IP) bool {
  705. private := false
  706. _, private24BitBlock, _ := net.ParseCIDR("10.0.0.0/8")
  707. _, private20BitBlock, _ := net.ParseCIDR("172.16.0.0/12")
  708. _, private16BitBlock, _ := net.ParseCIDR("192.168.0.0/16")
  709. private = private24BitBlock.Contains(ip) || private20BitBlock.Contains(ip) || private16BitBlock.Contains(ip)
  710. return private
  711. }