lighthouse.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  1. package nebula
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "net"
  7. "sync"
  8. "time"
  9. "github.com/golang/protobuf/proto"
  10. "github.com/rcrowley/go-metrics"
  11. "github.com/sirupsen/logrus"
  12. )
  13. //TODO: if the pb code for ipv6 used a fixed data type we could save more work
  14. //TODO: nodes are roaming lighthouses, this is bad. How are they learning?
  15. //TODO: as a lh client, ignore any address within my nebula network?????
  16. var ErrHostNotKnown = errors.New("host not known")
  17. // The maximum number of ip addresses to store for a given vpnIp per address family
  18. const maxAddrs = 10
  19. type ip4And6 struct {
  20. //TODO: adding a lock here could allow us to release the lock on lh.addrMap quicker
  21. // v4 and v6 store addresses that have been self reported by the client
  22. v4 []*Ip4AndPort
  23. v6 []*Ip6AndPort
  24. // Learned addresses are ones that a client does not know about but a lighthouse learned from as a result of the received packet
  25. learnedV4 []*Ip4AndPort
  26. learnedV6 []*Ip6AndPort
  27. }
  28. type LightHouse struct {
  29. //TODO: We need a timer wheel to kick out vpnIps that haven't reported in a long time
  30. sync.RWMutex //Because we concurrently read and write to our maps
  31. amLighthouse bool
  32. myIp uint32
  33. punchConn *udpConn
  34. // Local cache of answers from light houses
  35. addrMap map[uint32]*ip4And6
  36. // filters remote addresses allowed for each host
  37. // - When we are a lighthouse, this filters what addresses we store and
  38. // respond with.
  39. // - When we are not a lighthouse, this filters which addresses we accept
  40. // from lighthouses.
  41. remoteAllowList *AllowList
  42. // filters local addresses that we advertise to lighthouses
  43. localAllowList *AllowList
  44. // used to trigger the HandshakeManager when we receive HostQueryReply
  45. handshakeTrigger chan<- uint32
  46. // staticList exists to avoid having a bool in each addrMap entry
  47. // since static should be rare
  48. staticList map[uint32]struct{}
  49. lighthouses map[uint32]struct{}
  50. interval int
  51. nebulaPort uint32 // 32 bits because protobuf does not have a uint16
  52. punchBack bool
  53. punchDelay time.Duration
  54. metrics *MessageMetrics
  55. metricHolepunchTx metrics.Counter
  56. l *logrus.Logger
  57. }
  58. type EncWriter interface {
  59. SendMessageToVpnIp(t NebulaMessageType, st NebulaMessageSubType, vpnIp uint32, p, nb, out []byte)
  60. }
  61. func NewLightHouse(l *logrus.Logger, amLighthouse bool, myIp uint32, ips []uint32, interval int, nebulaPort uint32, pc *udpConn, punchBack bool, punchDelay time.Duration, metricsEnabled bool) *LightHouse {
  62. h := LightHouse{
  63. amLighthouse: amLighthouse,
  64. myIp: myIp,
  65. addrMap: make(map[uint32]*ip4And6),
  66. nebulaPort: nebulaPort,
  67. lighthouses: make(map[uint32]struct{}),
  68. staticList: make(map[uint32]struct{}),
  69. interval: interval,
  70. punchConn: pc,
  71. punchBack: punchBack,
  72. punchDelay: punchDelay,
  73. l: l,
  74. }
  75. if metricsEnabled {
  76. h.metrics = newLighthouseMetrics()
  77. h.metricHolepunchTx = metrics.GetOrRegisterCounter("messages.tx.holepunch", nil)
  78. } else {
  79. h.metricHolepunchTx = metrics.NilCounter{}
  80. }
  81. for _, ip := range ips {
  82. h.lighthouses[ip] = struct{}{}
  83. }
  84. return &h
  85. }
  86. func (lh *LightHouse) SetRemoteAllowList(allowList *AllowList) {
  87. lh.Lock()
  88. defer lh.Unlock()
  89. lh.remoteAllowList = allowList
  90. }
  91. func (lh *LightHouse) SetLocalAllowList(allowList *AllowList) {
  92. lh.Lock()
  93. defer lh.Unlock()
  94. lh.localAllowList = allowList
  95. }
  96. func (lh *LightHouse) ValidateLHStaticEntries() error {
  97. for lhIP, _ := range lh.lighthouses {
  98. if _, ok := lh.staticList[lhIP]; !ok {
  99. return fmt.Errorf("Lighthouse %s does not have a static_host_map entry", IntIp(lhIP))
  100. }
  101. }
  102. return nil
  103. }
  104. func (lh *LightHouse) Query(ip uint32, f EncWriter) ([]*udpAddr, error) {
  105. //TODO: we need to hold the lock through the next func
  106. if !lh.IsLighthouseIP(ip) {
  107. lh.QueryServer(ip, f)
  108. }
  109. lh.RLock()
  110. if v, ok := lh.addrMap[ip]; ok {
  111. lh.RUnlock()
  112. return TransformLHReplyToUdpAddrs(v), nil
  113. }
  114. lh.RUnlock()
  115. return nil, ErrHostNotKnown
  116. }
  117. // This is asynchronous so no reply should be expected
  118. func (lh *LightHouse) QueryServer(ip uint32, f EncWriter) {
  119. if !lh.amLighthouse {
  120. // Send a query to the lighthouses and hope for the best next time
  121. query, err := proto.Marshal(NewLhQueryByInt(ip))
  122. if err != nil {
  123. lh.l.WithError(err).WithField("vpnIp", IntIp(ip)).Error("Failed to marshal lighthouse query payload")
  124. return
  125. }
  126. lh.metricTx(NebulaMeta_HostQuery, int64(len(lh.lighthouses)))
  127. nb := make([]byte, 12, 12)
  128. out := make([]byte, mtu)
  129. for n := range lh.lighthouses {
  130. f.SendMessageToVpnIp(lightHouse, 0, n, query, nb, out)
  131. }
  132. }
  133. }
  134. func (lh *LightHouse) QueryCache(ip uint32) []*udpAddr {
  135. //TODO: we need to hold the lock through the next func
  136. lh.RLock()
  137. if v, ok := lh.addrMap[ip]; ok {
  138. lh.RUnlock()
  139. return TransformLHReplyToUdpAddrs(v)
  140. }
  141. lh.RUnlock()
  142. return nil
  143. }
  144. //
  145. func (lh *LightHouse) queryAndPrepMessage(ip uint32, f func(*ip4And6) (int, error)) (bool, int, error) {
  146. lh.RLock()
  147. if v, ok := lh.addrMap[ip]; ok {
  148. n, err := f(v)
  149. lh.RUnlock()
  150. return true, n, err
  151. }
  152. lh.RUnlock()
  153. return false, 0, nil
  154. }
  155. func (lh *LightHouse) DeleteVpnIP(vpnIP uint32) {
  156. // First we check the static mapping
  157. // and do nothing if it is there
  158. if _, ok := lh.staticList[vpnIP]; ok {
  159. return
  160. }
  161. lh.Lock()
  162. //l.Debugln(lh.addrMap)
  163. delete(lh.addrMap, vpnIP)
  164. if lh.l.Level >= logrus.DebugLevel {
  165. lh.l.Debugf("deleting %s from lighthouse.", IntIp(vpnIP))
  166. }
  167. lh.Unlock()
  168. }
  169. // AddRemote is correct way for non LightHouse members to add an address. toAddr will be placed in the learned map
  170. // static means this is a static host entry from the config file, it should only be used on start up
  171. func (lh *LightHouse) AddRemote(vpnIP uint32, toAddr *udpAddr, static bool) {
  172. if ipv4 := toAddr.IP.To4(); ipv4 != nil {
  173. lh.addRemoteV4(vpnIP, NewIp4AndPort(ipv4, uint32(toAddr.Port)), static, true)
  174. } else {
  175. lh.addRemoteV6(vpnIP, NewIp6AndPort(toAddr.IP, uint32(toAddr.Port)), static, true)
  176. }
  177. //TODO: if we do not add due to a config filter we may end up not having any addresses here
  178. if static {
  179. lh.staticList[vpnIP] = struct{}{}
  180. }
  181. }
  182. // unsafeGetAddrs assumes you have the lh lock
  183. func (lh *LightHouse) unsafeGetAddrs(vpnIP uint32) *ip4And6 {
  184. am, ok := lh.addrMap[vpnIP]
  185. if !ok {
  186. am = &ip4And6{
  187. v4: make([]*Ip4AndPort, 0),
  188. v6: make([]*Ip6AndPort, 0),
  189. learnedV4: make([]*Ip4AndPort, 0),
  190. learnedV6: make([]*Ip6AndPort, 0),
  191. }
  192. lh.addrMap[vpnIP] = am
  193. }
  194. return am
  195. }
  196. // addRemoteV4 is a lighthouse internal method that prepends a remote if it is allowed by the allow list and not duplicated
  197. func (lh *LightHouse) addRemoteV4(vpnIP uint32, to *Ip4AndPort, static bool, learned bool) {
  198. // First we check if the sender thinks this is a static entry
  199. // and do nothing if it is not, but should be considered static
  200. if static == false {
  201. if _, ok := lh.staticList[vpnIP]; ok {
  202. return
  203. }
  204. }
  205. lh.Lock()
  206. defer lh.Unlock()
  207. am := lh.unsafeGetAddrs(vpnIP)
  208. if learned {
  209. if !lh.unlockedShouldAddV4(am.learnedV4, to) {
  210. return
  211. }
  212. am.learnedV4 = prependAndLimitV4(am.learnedV4, to)
  213. } else {
  214. if !lh.unlockedShouldAddV4(am.v4, to) {
  215. return
  216. }
  217. am.v4 = prependAndLimitV4(am.v4, to)
  218. }
  219. }
  220. func prependAndLimitV4(cache []*Ip4AndPort, to *Ip4AndPort) []*Ip4AndPort {
  221. cache = append(cache, nil)
  222. copy(cache[1:], cache)
  223. cache[0] = to
  224. if len(cache) > MaxRemotes {
  225. cache = cache[:maxAddrs]
  226. }
  227. return cache
  228. }
  229. // unlockedShouldAddV4 checks if to is allowed by our allow list and is not already present in the cache
  230. func (lh *LightHouse) unlockedShouldAddV4(am []*Ip4AndPort, to *Ip4AndPort) bool {
  231. ip := int2ip(to.Ip)
  232. allow := lh.remoteAllowList.Allow(ip)
  233. if lh.l.Level >= logrus.DebugLevel {
  234. lh.l.WithField("remoteIp", ip).WithField("allow", allow).Debug("remoteAllowList.Allow")
  235. }
  236. if !allow {
  237. return false
  238. }
  239. for _, v := range am {
  240. if v.Ip == to.Ip && v.Port == to.Port {
  241. return false
  242. }
  243. }
  244. return true
  245. }
  246. // addRemoteV6 is a lighthouse internal method that prepends a remote if it is allowed by the allow list and not duplicated
  247. func (lh *LightHouse) addRemoteV6(vpnIP uint32, to *Ip6AndPort, static bool, learned bool) {
  248. // First we check if the sender thinks this is a static entry
  249. // and do nothing if it is not, but should be considered static
  250. if static == false {
  251. if _, ok := lh.staticList[vpnIP]; ok {
  252. return
  253. }
  254. }
  255. lh.Lock()
  256. defer lh.Unlock()
  257. am := lh.unsafeGetAddrs(vpnIP)
  258. if learned {
  259. if !lh.unlockedShouldAddV6(am.learnedV6, to) {
  260. return
  261. }
  262. am.learnedV6 = prependAndLimitV6(am.learnedV6, to)
  263. } else {
  264. if !lh.unlockedShouldAddV6(am.v6, to) {
  265. return
  266. }
  267. am.v6 = prependAndLimitV6(am.v6, to)
  268. }
  269. }
  270. func prependAndLimitV6(cache []*Ip6AndPort, to *Ip6AndPort) []*Ip6AndPort {
  271. cache = append(cache, nil)
  272. copy(cache[1:], cache)
  273. cache[0] = to
  274. if len(cache) > MaxRemotes {
  275. cache = cache[:maxAddrs]
  276. }
  277. return cache
  278. }
  279. // unlockedShouldAddV6 checks if to is allowed by our allow list and is not already present in the cache
  280. func (lh *LightHouse) unlockedShouldAddV6(am []*Ip6AndPort, to *Ip6AndPort) bool {
  281. ip := net.IP(to.Ip)
  282. allow := lh.remoteAllowList.Allow(ip)
  283. if lh.l.Level >= logrus.DebugLevel {
  284. lh.l.WithField("remoteIp", ip).WithField("allow", allow).Debug("remoteAllowList.Allow")
  285. }
  286. if !allow {
  287. return false
  288. }
  289. for _, v := range am {
  290. if bytes.Equal(v.Ip, to.Ip) && v.Port == to.Port {
  291. return false
  292. }
  293. }
  294. return true
  295. }
  296. func (lh *LightHouse) AddRemoteAndReset(vpnIP uint32, toIp *udpAddr) {
  297. if lh.amLighthouse {
  298. lh.DeleteVpnIP(vpnIP)
  299. lh.AddRemote(vpnIP, toIp, false)
  300. }
  301. }
  302. func (lh *LightHouse) IsLighthouseIP(vpnIP uint32) bool {
  303. if _, ok := lh.lighthouses[vpnIP]; ok {
  304. return true
  305. }
  306. return false
  307. }
  308. func NewLhQueryByInt(VpnIp uint32) *NebulaMeta {
  309. return &NebulaMeta{
  310. Type: NebulaMeta_HostQuery,
  311. Details: &NebulaMetaDetails{
  312. VpnIp: VpnIp,
  313. },
  314. }
  315. }
  316. func NewIp4AndPort(ip net.IP, port uint32) *Ip4AndPort {
  317. ipp := Ip4AndPort{Port: port}
  318. ipp.Ip = ip2int(ip)
  319. return &ipp
  320. }
  321. func NewIp6AndPort(ip net.IP, port uint32) *Ip6AndPort {
  322. ipp := Ip6AndPort{Port: port}
  323. ipp.Ip = make([]byte, len(ip))
  324. copy(ipp.Ip, ip)
  325. return &ipp
  326. }
  327. func NewUDPAddrFromLH4(ipp *Ip4AndPort) *udpAddr {
  328. ip := ipp.Ip
  329. return NewUDPAddr(
  330. net.IPv4(byte(ip&0xff000000>>24), byte(ip&0x00ff0000>>16), byte(ip&0x0000ff00>>8), byte(ip&0x000000ff)),
  331. uint16(ipp.Port),
  332. )
  333. }
  334. func NewUDPAddrFromLH6(ipp *Ip6AndPort) *udpAddr {
  335. return NewUDPAddr(ipp.Ip, uint16(ipp.Port))
  336. }
  337. func (lh *LightHouse) LhUpdateWorker(f EncWriter) {
  338. if lh.amLighthouse || lh.interval == 0 {
  339. return
  340. }
  341. for {
  342. lh.SendUpdate(f)
  343. time.Sleep(time.Second * time.Duration(lh.interval))
  344. }
  345. }
  346. func (lh *LightHouse) SendUpdate(f EncWriter) {
  347. var v4 []*Ip4AndPort
  348. var v6 []*Ip6AndPort
  349. for _, e := range *localIps(lh.l, lh.localAllowList) {
  350. if ip2int(e) == lh.myIp {
  351. continue
  352. }
  353. // Only add IPs that aren't my VPN/tun IP
  354. if ip := e.To4(); ip != nil {
  355. v4 = append(v4, NewIp4AndPort(e, lh.nebulaPort))
  356. } else {
  357. v6 = append(v6, NewIp6AndPort(e, lh.nebulaPort))
  358. }
  359. }
  360. m := &NebulaMeta{
  361. Type: NebulaMeta_HostUpdateNotification,
  362. Details: &NebulaMetaDetails{
  363. VpnIp: lh.myIp,
  364. Ip4AndPorts: v4,
  365. Ip6AndPorts: v6,
  366. },
  367. }
  368. lh.metricTx(NebulaMeta_HostUpdateNotification, int64(len(lh.lighthouses)))
  369. nb := make([]byte, 12, 12)
  370. out := make([]byte, mtu)
  371. for vpnIp := range lh.lighthouses {
  372. mm, err := proto.Marshal(m)
  373. if err != nil && lh.l.Level >= logrus.DebugLevel {
  374. lh.l.Debugf("Invalid marshal to update")
  375. }
  376. //l.Error("LIGHTHOUSE PACKET SEND", mm)
  377. f.SendMessageToVpnIp(lightHouse, 0, vpnIp, mm, nb, out)
  378. }
  379. }
  380. type LightHouseHandler struct {
  381. lh *LightHouse
  382. nb []byte
  383. out []byte
  384. pb []byte
  385. meta *NebulaMeta
  386. l *logrus.Logger
  387. }
  388. func (lh *LightHouse) NewRequestHandler() *LightHouseHandler {
  389. lhh := &LightHouseHandler{
  390. lh: lh,
  391. nb: make([]byte, 12, 12),
  392. out: make([]byte, mtu),
  393. l: lh.l,
  394. pb: make([]byte, mtu),
  395. meta: &NebulaMeta{
  396. Details: &NebulaMetaDetails{},
  397. },
  398. }
  399. return lhh
  400. }
  401. func (lh *LightHouse) metricRx(t NebulaMeta_MessageType, i int64) {
  402. lh.metrics.Rx(NebulaMessageType(t), 0, i)
  403. }
  404. func (lh *LightHouse) metricTx(t NebulaMeta_MessageType, i int64) {
  405. lh.metrics.Tx(NebulaMessageType(t), 0, i)
  406. }
  407. // This method is similar to Reset(), but it re-uses the pointer structs
  408. // so that we don't have to re-allocate them
  409. func (lhh *LightHouseHandler) resetMeta() *NebulaMeta {
  410. details := lhh.meta.Details
  411. lhh.meta.Reset()
  412. // Keep the array memory around
  413. details.Ip4AndPorts = details.Ip4AndPorts[:0]
  414. details.Ip6AndPorts = details.Ip6AndPorts[:0]
  415. lhh.meta.Details = details
  416. return lhh.meta
  417. }
  418. //TODO: do we need c here?
  419. func (lhh *LightHouseHandler) HandleRequest(rAddr *udpAddr, vpnIp uint32, p []byte, w EncWriter) {
  420. n := lhh.resetMeta()
  421. err := n.Unmarshal(p)
  422. if err != nil {
  423. lhh.l.WithError(err).WithField("vpnIp", IntIp(vpnIp)).WithField("udpAddr", rAddr).
  424. Error("Failed to unmarshal lighthouse packet")
  425. //TODO: send recv_error?
  426. return
  427. }
  428. if n.Details == nil {
  429. lhh.l.WithField("vpnIp", IntIp(vpnIp)).WithField("udpAddr", rAddr).
  430. Error("Invalid lighthouse update")
  431. //TODO: send recv_error?
  432. return
  433. }
  434. lhh.lh.metricRx(n.Type, 1)
  435. switch n.Type {
  436. case NebulaMeta_HostQuery:
  437. lhh.handleHostQuery(n, vpnIp, rAddr, w)
  438. case NebulaMeta_HostQueryReply:
  439. lhh.handleHostQueryReply(n, vpnIp)
  440. case NebulaMeta_HostUpdateNotification:
  441. lhh.handleHostUpdateNotification(n, vpnIp)
  442. case NebulaMeta_HostMovedNotification:
  443. case NebulaMeta_HostPunchNotification:
  444. lhh.handleHostPunchNotification(n, vpnIp, w)
  445. }
  446. }
  447. func (lhh *LightHouseHandler) handleHostQuery(n *NebulaMeta, vpnIp uint32, addr *udpAddr, w EncWriter) {
  448. // Exit if we don't answer queries
  449. if !lhh.lh.amLighthouse {
  450. if lhh.l.Level >= logrus.DebugLevel {
  451. lhh.l.Debugln("I don't answer queries, but received from: ", addr)
  452. }
  453. return
  454. }
  455. //TODO: we can DRY this further
  456. reqVpnIP := n.Details.VpnIp
  457. //TODO: Maybe instead of marshalling into n we marshal into a new `r` to not nuke our current request data
  458. //TODO: If we use a lock on cache we can avoid holding it on lh.addrMap and keep things moving better
  459. found, ln, err := lhh.lh.queryAndPrepMessage(n.Details.VpnIp, func(cache *ip4And6) (int, error) {
  460. n = lhh.resetMeta()
  461. n.Type = NebulaMeta_HostQueryReply
  462. n.Details.VpnIp = reqVpnIP
  463. lhh.coalesceAnswers(cache, n)
  464. return n.MarshalTo(lhh.pb)
  465. })
  466. if !found {
  467. return
  468. }
  469. if err != nil {
  470. lhh.l.WithError(err).WithField("vpnIp", IntIp(vpnIp)).Error("Failed to marshal lighthouse host query reply")
  471. return
  472. }
  473. lhh.lh.metricTx(NebulaMeta_HostQueryReply, 1)
  474. w.SendMessageToVpnIp(lightHouse, 0, vpnIp, lhh.pb[:ln], lhh.nb, lhh.out[:0])
  475. // This signals the other side to punch some zero byte udp packets
  476. found, ln, err = lhh.lh.queryAndPrepMessage(vpnIp, func(cache *ip4And6) (int, error) {
  477. n = lhh.resetMeta()
  478. n.Type = NebulaMeta_HostPunchNotification
  479. n.Details.VpnIp = vpnIp
  480. lhh.coalesceAnswers(cache, n)
  481. return n.MarshalTo(lhh.pb)
  482. })
  483. if !found {
  484. return
  485. }
  486. if err != nil {
  487. lhh.l.WithError(err).WithField("vpnIp", IntIp(vpnIp)).Error("Failed to marshal lighthouse host was queried for")
  488. return
  489. }
  490. lhh.lh.metricTx(NebulaMeta_HostPunchNotification, 1)
  491. w.SendMessageToVpnIp(lightHouse, 0, reqVpnIP, lhh.pb[:ln], lhh.nb, lhh.out[:0])
  492. }
  493. func (lhh *LightHouseHandler) coalesceAnswers(cache *ip4And6, n *NebulaMeta) {
  494. n.Details.Ip4AndPorts = append(n.Details.Ip4AndPorts, cache.v4...)
  495. n.Details.Ip4AndPorts = append(n.Details.Ip4AndPorts, cache.learnedV4...)
  496. n.Details.Ip6AndPorts = append(n.Details.Ip6AndPorts, cache.v6...)
  497. n.Details.Ip6AndPorts = append(n.Details.Ip6AndPorts, cache.learnedV6...)
  498. }
  499. func (lhh *LightHouseHandler) handleHostQueryReply(n *NebulaMeta, vpnIp uint32) {
  500. if !lhh.lh.IsLighthouseIP(vpnIp) {
  501. return
  502. }
  503. // We can't just slam the responses in as they may come from multiple lighthouses and we should coalesce the answers
  504. for _, to := range n.Details.Ip4AndPorts {
  505. lhh.lh.addRemoteV4(n.Details.VpnIp, to, false, false)
  506. }
  507. for _, to := range n.Details.Ip6AndPorts {
  508. lhh.lh.addRemoteV6(n.Details.VpnIp, to, false, false)
  509. }
  510. // Non-blocking attempt to trigger, skip if it would block
  511. select {
  512. case lhh.lh.handshakeTrigger <- n.Details.VpnIp:
  513. default:
  514. }
  515. }
  516. func (lhh *LightHouseHandler) handleHostUpdateNotification(n *NebulaMeta, vpnIp uint32) {
  517. if !lhh.lh.amLighthouse {
  518. if lhh.l.Level >= logrus.DebugLevel {
  519. lhh.l.Debugln("I am not a lighthouse, do not take host updates: ", vpnIp)
  520. }
  521. return
  522. }
  523. //Simple check that the host sent this not someone else
  524. if n.Details.VpnIp != vpnIp {
  525. if lhh.l.Level >= logrus.DebugLevel {
  526. lhh.l.WithField("vpnIp", IntIp(vpnIp)).WithField("answer", IntIp(n.Details.VpnIp)).Debugln("Host sent invalid update")
  527. }
  528. return
  529. }
  530. lhh.lh.Lock()
  531. defer lhh.lh.Unlock()
  532. am := lhh.lh.unsafeGetAddrs(vpnIp)
  533. //TODO: other note on a lock for am so we can release more quickly and lock our real unit of change which is far less contended
  534. //TODO: we are not filtering by local or remote allowed addrs here, is this an ok change to make?
  535. // We don't accumulate addresses being told to us
  536. am.v4 = am.v4[:0]
  537. am.v6 = am.v6[:0]
  538. for _, v := range n.Details.Ip4AndPorts {
  539. if lhh.lh.unlockedShouldAddV4(am.v4, v) {
  540. am.v4 = append(am.v4, v)
  541. }
  542. }
  543. for _, v := range n.Details.Ip6AndPorts {
  544. if lhh.lh.unlockedShouldAddV6(am.v6, v) {
  545. am.v6 = append(am.v6, v)
  546. }
  547. }
  548. // We prefer the first n addresses if we got too big
  549. if len(am.v4) > MaxRemotes {
  550. am.v4 = am.v4[:MaxRemotes]
  551. }
  552. if len(am.v6) > MaxRemotes {
  553. am.v6 = am.v6[:MaxRemotes]
  554. }
  555. }
  556. func (lhh *LightHouseHandler) handleHostPunchNotification(n *NebulaMeta, vpnIp uint32, w EncWriter) {
  557. if !lhh.lh.IsLighthouseIP(vpnIp) {
  558. return
  559. }
  560. empty := []byte{0}
  561. punch := func(vpnPeer *udpAddr) {
  562. if vpnPeer == nil {
  563. return
  564. }
  565. go func() {
  566. time.Sleep(lhh.lh.punchDelay)
  567. lhh.lh.metricHolepunchTx.Inc(1)
  568. lhh.lh.punchConn.WriteTo(empty, vpnPeer)
  569. }()
  570. if lhh.l.Level >= logrus.DebugLevel {
  571. //TODO: lacking the ip we are actually punching on, old: l.Debugf("Punching %s on %d for %s", IntIp(a.Ip), a.Port, IntIp(n.Details.VpnIp))
  572. lhh.l.Debugf("Punching on %d for %s", vpnPeer.Port, IntIp(n.Details.VpnIp))
  573. }
  574. }
  575. for _, a := range n.Details.Ip4AndPorts {
  576. punch(NewUDPAddrFromLH4(a))
  577. }
  578. for _, a := range n.Details.Ip6AndPorts {
  579. punch(NewUDPAddrFromLH6(a))
  580. }
  581. // This sends a nebula test packet to the host trying to contact us. In the case
  582. // of a double nat or other difficult scenario, this may help establish
  583. // a tunnel.
  584. if lhh.lh.punchBack {
  585. go func() {
  586. time.Sleep(time.Second * 5)
  587. if lhh.l.Level >= logrus.DebugLevel {
  588. lhh.l.Debugf("Sending a nebula test packet to vpn ip %s", IntIp(n.Details.VpnIp))
  589. }
  590. //NOTE: we have to allocate a new output buffer here since we are spawning a new goroutine
  591. // for each punchBack packet. We should move this into a timerwheel or a single goroutine
  592. // managed by a channel.
  593. w.SendMessageToVpnIp(test, testRequest, n.Details.VpnIp, []byte(""), make([]byte, 12, 12), make([]byte, mtu))
  594. }()
  595. }
  596. }
  597. func TransformLHReplyToUdpAddrs(ips *ip4And6) []*udpAddr {
  598. addrs := make([]*udpAddr, len(ips.v4)+len(ips.v6)+len(ips.learnedV4)+len(ips.learnedV6))
  599. i := 0
  600. for _, v := range ips.learnedV4 {
  601. addrs[i] = NewUDPAddrFromLH4(v)
  602. i++
  603. }
  604. for _, v := range ips.v4 {
  605. addrs[i] = NewUDPAddrFromLH4(v)
  606. i++
  607. }
  608. for _, v := range ips.learnedV6 {
  609. addrs[i] = NewUDPAddrFromLH6(v)
  610. i++
  611. }
  612. for _, v := range ips.v6 {
  613. addrs[i] = NewUDPAddrFromLH6(v)
  614. i++
  615. }
  616. return addrs
  617. }