hostmap.go 20 KB

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