hostmap.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  1. package nebula
  2. import (
  3. "errors"
  4. "fmt"
  5. "net"
  6. "sync"
  7. "sync/atomic"
  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 ReQueryEvery = 5000
  16. const MaxRemotes = 10
  17. // How long we should prevent roaming back to the previous IP.
  18. // This helps prevent flapping due to packets already in flight
  19. const RoamingSuppressSeconds = 2
  20. type HostMap struct {
  21. sync.RWMutex //Because we concurrently read and write to our maps
  22. name string
  23. Indexes map[uint32]*HostInfo
  24. RemoteIndexes map[uint32]*HostInfo
  25. Hosts map[uint32]*HostInfo
  26. preferredRanges []*net.IPNet
  27. vpnCIDR *net.IPNet
  28. unsafeRoutes *CIDRTree
  29. metricsEnabled bool
  30. l *logrus.Logger
  31. }
  32. type HostInfo struct {
  33. sync.RWMutex
  34. remote *udpAddr
  35. remotes *RemoteList
  36. promoteCounter uint32
  37. ConnectionState *ConnectionState
  38. handshakeStart time.Time //todo: this an entry in the handshake manager
  39. HandshakeReady bool //todo: being in the manager means you are ready
  40. HandshakeCounter int //todo: another handshake manager entry
  41. HandshakeComplete bool //todo: this should go away in favor of ConnectionState.ready
  42. HandshakePacket map[uint8][]byte //todo: this is other handshake manager entry
  43. packetStore []*cachedPacket //todo: this is other handshake manager entry
  44. remoteIndexId uint32
  45. localIndexId uint32
  46. hostId uint32
  47. recvError int
  48. remoteCidr *CIDRTree
  49. // lastRebindCount is the other side of Interface.rebindCount, if these values don't match then we need to ask LH
  50. // for a punch from the remote end of this tunnel. The goal being to prime their conntrack for our traffic just like
  51. // with a handshake
  52. lastRebindCount int8
  53. // lastHandshakeTime records the time the remote side told us about at the stage when the handshake was completed locally
  54. // Stage 1 packet will contain it if I am a responder, stage 2 packet if I am an initiator
  55. // This is used to avoid an attack where a handshake packet is replayed after some time
  56. lastHandshakeTime uint64
  57. lastRoam time.Time
  58. lastRoamRemote *udpAddr
  59. }
  60. type cachedPacket struct {
  61. messageType NebulaMessageType
  62. messageSubType NebulaMessageSubType
  63. callback packetCallback
  64. packet []byte
  65. }
  66. type packetCallback func(t NebulaMessageType, st NebulaMessageSubType, h *HostInfo, p, nb, out []byte)
  67. type cachedPacketMetrics struct {
  68. sent metrics.Counter
  69. dropped metrics.Counter
  70. }
  71. func NewHostMap(l *logrus.Logger, name string, vpnCIDR *net.IPNet, preferredRanges []*net.IPNet) *HostMap {
  72. h := map[uint32]*HostInfo{}
  73. i := map[uint32]*HostInfo{}
  74. r := map[uint32]*HostInfo{}
  75. m := HostMap{
  76. name: name,
  77. Indexes: i,
  78. RemoteIndexes: r,
  79. Hosts: h,
  80. preferredRanges: preferredRanges,
  81. vpnCIDR: vpnCIDR,
  82. unsafeRoutes: NewCIDRTree(),
  83. l: l,
  84. }
  85. return &m
  86. }
  87. // UpdateStats takes a name and reports host and index counts to the stats collection system
  88. func (hm *HostMap) EmitStats(name string) {
  89. hm.RLock()
  90. hostLen := len(hm.Hosts)
  91. indexLen := len(hm.Indexes)
  92. remoteIndexLen := len(hm.RemoteIndexes)
  93. hm.RUnlock()
  94. metrics.GetOrRegisterGauge("hostmap."+name+".hosts", nil).Update(int64(hostLen))
  95. metrics.GetOrRegisterGauge("hostmap."+name+".indexes", nil).Update(int64(indexLen))
  96. metrics.GetOrRegisterGauge("hostmap."+name+".remoteIndexes", nil).Update(int64(remoteIndexLen))
  97. }
  98. func (hm *HostMap) GetIndexByVpnIP(vpnIP uint32) (uint32, error) {
  99. hm.RLock()
  100. if i, ok := hm.Hosts[vpnIP]; ok {
  101. index := i.localIndexId
  102. hm.RUnlock()
  103. return index, 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. promoteCounter: 0,
  120. hostId: vpnIP,
  121. HandshakePacket: make(map[uint8][]byte, 0),
  122. }
  123. hm.Lock()
  124. hm.Hosts[vpnIP] = h
  125. hm.Unlock()
  126. return h
  127. } else {
  128. h = hm.Hosts[vpnIP]
  129. hm.RUnlock()
  130. return h
  131. }
  132. }
  133. func (hm *HostMap) DeleteVpnIP(vpnIP uint32) {
  134. hm.Lock()
  135. delete(hm.Hosts, vpnIP)
  136. if len(hm.Hosts) == 0 {
  137. hm.Hosts = map[uint32]*HostInfo{}
  138. }
  139. hm.Unlock()
  140. if hm.l.Level >= logrus.DebugLevel {
  141. hm.l.WithField("hostMap", m{"mapName": hm.name, "vpnIp": IntIp(vpnIP), "mapTotalSize": len(hm.Hosts)}).
  142. Debug("Hostmap vpnIp deleted")
  143. }
  144. }
  145. // Only used by pendingHostMap when the remote index is not initially known
  146. func (hm *HostMap) addRemoteIndexHostInfo(index uint32, h *HostInfo) {
  147. hm.Lock()
  148. h.remoteIndexId = index
  149. hm.RemoteIndexes[index] = h
  150. hm.Unlock()
  151. if hm.l.Level > logrus.DebugLevel {
  152. hm.l.WithField("hostMap", m{"mapName": hm.name, "indexNumber": index, "mapTotalSize": len(hm.Indexes),
  153. "hostinfo": m{"existing": true, "localIndexId": h.localIndexId, "hostId": IntIp(h.hostId)}}).
  154. Debug("Hostmap remoteIndex added")
  155. }
  156. }
  157. func (hm *HostMap) AddVpnIPHostInfo(vpnIP uint32, h *HostInfo) {
  158. hm.Lock()
  159. h.hostId = vpnIP
  160. hm.Hosts[vpnIP] = h
  161. hm.Indexes[h.localIndexId] = h
  162. hm.RemoteIndexes[h.remoteIndexId] = h
  163. hm.Unlock()
  164. if hm.l.Level > logrus.DebugLevel {
  165. hm.l.WithField("hostMap", m{"mapName": hm.name, "vpnIp": IntIp(vpnIP), "mapTotalSize": len(hm.Hosts),
  166. "hostinfo": m{"existing": true, "localIndexId": h.localIndexId, "hostId": IntIp(h.hostId)}}).
  167. Debug("Hostmap vpnIp added")
  168. }
  169. }
  170. // This is only called in pendingHostmap, to cleanup an inbound handshake
  171. func (hm *HostMap) DeleteIndex(index uint32) {
  172. hm.Lock()
  173. hostinfo, ok := hm.Indexes[index]
  174. if ok {
  175. delete(hm.Indexes, index)
  176. delete(hm.RemoteIndexes, hostinfo.remoteIndexId)
  177. // Check if we have an entry under hostId that matches the same hostinfo
  178. // instance. Clean it up as well if we do.
  179. hostinfo2, ok := hm.Hosts[hostinfo.hostId]
  180. if ok && hostinfo2 == hostinfo {
  181. delete(hm.Hosts, hostinfo.hostId)
  182. }
  183. }
  184. hm.Unlock()
  185. if hm.l.Level >= logrus.DebugLevel {
  186. hm.l.WithField("hostMap", m{"mapName": hm.name, "indexNumber": index, "mapTotalSize": len(hm.Indexes)}).
  187. Debug("Hostmap index deleted")
  188. }
  189. }
  190. // This is used to cleanup on recv_error
  191. func (hm *HostMap) DeleteReverseIndex(index uint32) {
  192. hm.Lock()
  193. hostinfo, ok := hm.RemoteIndexes[index]
  194. if ok {
  195. delete(hm.Indexes, hostinfo.localIndexId)
  196. delete(hm.RemoteIndexes, index)
  197. // Check if we have an entry under hostId that matches the same hostinfo
  198. // instance. Clean it up as well if we do (they might not match in pendingHostmap)
  199. var hostinfo2 *HostInfo
  200. hostinfo2, ok = hm.Hosts[hostinfo.hostId]
  201. if ok && hostinfo2 == hostinfo {
  202. delete(hm.Hosts, hostinfo.hostId)
  203. }
  204. }
  205. hm.Unlock()
  206. if hm.l.Level >= logrus.DebugLevel {
  207. hm.l.WithField("hostMap", m{"mapName": hm.name, "indexNumber": index, "mapTotalSize": len(hm.Indexes)}).
  208. Debug("Hostmap remote index deleted")
  209. }
  210. }
  211. func (hm *HostMap) DeleteHostInfo(hostinfo *HostInfo) {
  212. hm.Lock()
  213. defer hm.Unlock()
  214. hm.unlockedDeleteHostInfo(hostinfo)
  215. }
  216. func (hm *HostMap) unlockedDeleteHostInfo(hostinfo *HostInfo) {
  217. // Check if this same hostId is in the hostmap with a different instance.
  218. // This could happen if we have an entry in the pending hostmap with different
  219. // index values than the one in the main hostmap.
  220. hostinfo2, ok := hm.Hosts[hostinfo.hostId]
  221. if ok && hostinfo2 != hostinfo {
  222. delete(hm.Hosts, hostinfo2.hostId)
  223. delete(hm.Indexes, hostinfo2.localIndexId)
  224. delete(hm.RemoteIndexes, hostinfo2.remoteIndexId)
  225. }
  226. delete(hm.Hosts, hostinfo.hostId)
  227. if len(hm.Hosts) == 0 {
  228. hm.Hosts = map[uint32]*HostInfo{}
  229. }
  230. delete(hm.Indexes, hostinfo.localIndexId)
  231. if len(hm.Indexes) == 0 {
  232. hm.Indexes = map[uint32]*HostInfo{}
  233. }
  234. delete(hm.RemoteIndexes, hostinfo.remoteIndexId)
  235. if len(hm.RemoteIndexes) == 0 {
  236. hm.RemoteIndexes = map[uint32]*HostInfo{}
  237. }
  238. if hm.l.Level >= logrus.DebugLevel {
  239. hm.l.WithField("hostMap", m{"mapName": hm.name, "mapTotalSize": len(hm.Hosts),
  240. "vpnIp": IntIp(hostinfo.hostId), "indexNumber": hostinfo.localIndexId, "remoteIndexNumber": hostinfo.remoteIndexId}).
  241. Debug("Hostmap hostInfo deleted")
  242. }
  243. }
  244. func (hm *HostMap) QueryIndex(index uint32) (*HostInfo, error) {
  245. //TODO: we probably just want ot return bool instead of error, or at least a static error
  246. hm.RLock()
  247. if h, ok := hm.Indexes[index]; ok {
  248. hm.RUnlock()
  249. return h, nil
  250. } else {
  251. hm.RUnlock()
  252. return nil, errors.New("unable to find index")
  253. }
  254. }
  255. func (hm *HostMap) QueryReverseIndex(index uint32) (*HostInfo, error) {
  256. hm.RLock()
  257. if h, ok := hm.RemoteIndexes[index]; ok {
  258. hm.RUnlock()
  259. return h, nil
  260. } else {
  261. hm.RUnlock()
  262. return nil, fmt.Errorf("unable to find reverse index or connectionstate nil in %s hostmap", hm.name)
  263. }
  264. }
  265. func (hm *HostMap) QueryVpnIP(vpnIp uint32) (*HostInfo, error) {
  266. return hm.queryVpnIP(vpnIp, nil)
  267. }
  268. // PromoteBestQueryVpnIP will attempt to lazily switch to the best remote every
  269. // `PromoteEvery` calls to this function for a given host.
  270. func (hm *HostMap) PromoteBestQueryVpnIP(vpnIp uint32, ifce *Interface) (*HostInfo, error) {
  271. return hm.queryVpnIP(vpnIp, ifce)
  272. }
  273. func (hm *HostMap) queryVpnIP(vpnIp uint32, promoteIfce *Interface) (*HostInfo, error) {
  274. hm.RLock()
  275. if h, ok := hm.Hosts[vpnIp]; ok {
  276. // Do not attempt promotion if you are a lighthouse
  277. if promoteIfce != nil && !promoteIfce.lightHouse.amLighthouse {
  278. h.TryPromoteBest(hm.preferredRanges, promoteIfce)
  279. }
  280. hm.RUnlock()
  281. return h, nil
  282. } else {
  283. //return &net.UDPAddr{}, nil, errors.New("Unable to find host")
  284. hm.RUnlock()
  285. /*
  286. if lightHouse != nil {
  287. lightHouse.Query(vpnIp)
  288. return nil, errors.New("Unable to find host")
  289. }
  290. */
  291. return nil, errors.New("unable to find host")
  292. }
  293. }
  294. func (hm *HostMap) queryUnsafeRoute(ip uint32) uint32 {
  295. r := hm.unsafeRoutes.MostSpecificContains(ip)
  296. if r != nil {
  297. return r.(uint32)
  298. } else {
  299. return 0
  300. }
  301. }
  302. // We already have the hm Lock when this is called, so make sure to not call
  303. // any other methods that might try to grab it again
  304. func (hm *HostMap) addHostInfo(hostinfo *HostInfo, f *Interface) {
  305. if f.serveDns {
  306. remoteCert := hostinfo.ConnectionState.peerCert
  307. dnsR.Add(remoteCert.Details.Name+".", remoteCert.Details.Ips[0].IP.String())
  308. }
  309. hm.Hosts[hostinfo.hostId] = hostinfo
  310. hm.Indexes[hostinfo.localIndexId] = hostinfo
  311. hm.RemoteIndexes[hostinfo.remoteIndexId] = hostinfo
  312. if hm.l.Level >= logrus.DebugLevel {
  313. hm.l.WithField("hostMap", m{"mapName": hm.name, "vpnIp": IntIp(hostinfo.hostId), "mapTotalSize": len(hm.Hosts),
  314. "hostinfo": m{"existing": true, "localIndexId": hostinfo.localIndexId, "hostId": IntIp(hostinfo.hostId)}}).
  315. Debug("Hostmap vpnIp added")
  316. }
  317. }
  318. // punchList assembles a list of all non nil RemoteList pointer entries in this hostmap
  319. // The caller can then do the its work outside of the read lock
  320. func (hm *HostMap) punchList(rl []*RemoteList) []*RemoteList {
  321. hm.RLock()
  322. defer hm.RUnlock()
  323. for _, v := range hm.Hosts {
  324. if v.remotes != nil {
  325. rl = append(rl, v.remotes)
  326. }
  327. }
  328. return rl
  329. }
  330. // Punchy iterates through the result of punchList() to assemble all known addresses and sends a hole punch packet to them
  331. func (hm *HostMap) Punchy(conn *udpConn) {
  332. var metricsTxPunchy metrics.Counter
  333. if hm.metricsEnabled {
  334. metricsTxPunchy = metrics.GetOrRegisterCounter("messages.tx.punchy", nil)
  335. } else {
  336. metricsTxPunchy = metrics.NilCounter{}
  337. }
  338. var remotes []*RemoteList
  339. b := []byte{1}
  340. for {
  341. remotes = hm.punchList(remotes[:0])
  342. for _, rl := range remotes {
  343. //TODO: CopyAddrs generates garbage but ForEach locks for the work here, figure out which way is better
  344. for _, addr := range rl.CopyAddrs(hm.preferredRanges) {
  345. metricsTxPunchy.Inc(1)
  346. conn.WriteTo(b, addr)
  347. }
  348. }
  349. time.Sleep(time.Second * 10)
  350. }
  351. }
  352. func (hm *HostMap) addUnsafeRoutes(routes *[]route) {
  353. for _, r := range *routes {
  354. hm.l.WithField("route", r.route).WithField("via", r.via).Warn("Adding UNSAFE Route")
  355. hm.unsafeRoutes.AddCIDR(r.route, ip2int(*r.via))
  356. }
  357. }
  358. func (i *HostInfo) BindConnectionState(cs *ConnectionState) {
  359. i.ConnectionState = cs
  360. }
  361. // TryPromoteBest handles re-querying lighthouses and probing for better paths
  362. // NOTE: It is an error to call this if you are a lighthouse since they should not roam clients!
  363. func (i *HostInfo) TryPromoteBest(preferredRanges []*net.IPNet, ifce *Interface) {
  364. c := atomic.AddUint32(&i.promoteCounter, 1)
  365. if c%PromoteEvery == 0 {
  366. // return early if we are already on a preferred remote
  367. rIP := i.remote.IP
  368. for _, l := range preferredRanges {
  369. if l.Contains(rIP) {
  370. return
  371. }
  372. }
  373. i.remotes.ForEach(preferredRanges, func(addr *udpAddr, preferred bool) {
  374. if addr == nil || !preferred {
  375. return
  376. }
  377. // Try to send a test packet to that host, this should
  378. // cause it to detect a roaming event and switch remotes
  379. ifce.send(test, testRequest, i.ConnectionState, i, addr, []byte(""), make([]byte, 12, 12), make([]byte, mtu))
  380. })
  381. }
  382. // Re query our lighthouses for new remotes occasionally
  383. if c%ReQueryEvery == 0 && ifce.lightHouse != nil {
  384. ifce.lightHouse.QueryServer(i.hostId, ifce)
  385. }
  386. }
  387. func (i *HostInfo) cachePacket(l *logrus.Logger, t NebulaMessageType, st NebulaMessageSubType, packet []byte, f packetCallback, m *cachedPacketMetrics) {
  388. //TODO: return the error so we can log with more context
  389. if len(i.packetStore) < 100 {
  390. tempPacket := make([]byte, len(packet))
  391. copy(tempPacket, packet)
  392. //l.WithField("trace", string(debug.Stack())).Error("Caching packet", tempPacket)
  393. i.packetStore = append(i.packetStore, &cachedPacket{t, st, f, tempPacket})
  394. if l.Level >= logrus.DebugLevel {
  395. i.logger(l).
  396. WithField("length", len(i.packetStore)).
  397. WithField("stored", true).
  398. Debugf("Packet store")
  399. }
  400. } else if l.Level >= logrus.DebugLevel {
  401. m.dropped.Inc(1)
  402. i.logger(l).
  403. WithField("length", len(i.packetStore)).
  404. WithField("stored", false).
  405. Debugf("Packet store")
  406. }
  407. }
  408. // handshakeComplete will set the connection as ready to communicate, as well as flush any stored packets
  409. func (i *HostInfo) handshakeComplete(l *logrus.Logger, m *cachedPacketMetrics) {
  410. //TODO: I'm not certain the distinction between handshake complete and ConnectionState being ready matters because:
  411. //TODO: HandshakeComplete means send stored packets and ConnectionState.ready means we are ready to send
  412. //TODO: if the transition from HandhsakeComplete to ConnectionState.ready happens all within this function they are identical
  413. i.ConnectionState.queueLock.Lock()
  414. i.HandshakeComplete = true
  415. //TODO: this should be managed by the handshake state machine to set it based on how many handshake were seen.
  416. // Clamping it to 2 gets us out of the woods for now
  417. atomic.StoreUint64(&i.ConnectionState.atomicMessageCounter, 2)
  418. if l.Level >= logrus.DebugLevel {
  419. i.logger(l).Debugf("Sending %d stored packets", len(i.packetStore))
  420. }
  421. if len(i.packetStore) > 0 {
  422. nb := make([]byte, 12, 12)
  423. out := make([]byte, mtu)
  424. for _, cp := range i.packetStore {
  425. cp.callback(cp.messageType, cp.messageSubType, i, cp.packet, nb, out)
  426. }
  427. m.sent.Inc(int64(len(i.packetStore)))
  428. }
  429. i.remotes.ResetBlockedRemotes()
  430. i.packetStore = make([]*cachedPacket, 0)
  431. i.ConnectionState.ready = true
  432. i.ConnectionState.queueLock.Unlock()
  433. i.ConnectionState.certState = nil
  434. }
  435. func (i *HostInfo) GetCert() *cert.NebulaCertificate {
  436. if i.ConnectionState != nil {
  437. return i.ConnectionState.peerCert
  438. }
  439. return nil
  440. }
  441. func (i *HostInfo) SetRemote(remote *udpAddr) {
  442. // We copy here because we likely got this remote from a source that reuses the object
  443. if !i.remote.Equals(remote) {
  444. i.remote = remote.Copy()
  445. i.remotes.LearnRemote(i.hostId, remote.Copy())
  446. }
  447. }
  448. func (i *HostInfo) ClearConnectionState() {
  449. i.ConnectionState = nil
  450. }
  451. func (i *HostInfo) RecvErrorExceeded() bool {
  452. if i.recvError < 3 {
  453. i.recvError += 1
  454. return false
  455. }
  456. return true
  457. }
  458. func (i *HostInfo) CreateRemoteCIDR(c *cert.NebulaCertificate) {
  459. if len(c.Details.Ips) == 1 && len(c.Details.Subnets) == 0 {
  460. // Simple case, no CIDRTree needed
  461. return
  462. }
  463. remoteCidr := NewCIDRTree()
  464. for _, ip := range c.Details.Ips {
  465. remoteCidr.AddCIDR(&net.IPNet{IP: ip.IP, Mask: net.IPMask{255, 255, 255, 255}}, struct{}{})
  466. }
  467. for _, n := range c.Details.Subnets {
  468. remoteCidr.AddCIDR(n, struct{}{})
  469. }
  470. i.remoteCidr = remoteCidr
  471. }
  472. func (i *HostInfo) logger(l *logrus.Logger) *logrus.Entry {
  473. if i == nil {
  474. return logrus.NewEntry(l)
  475. }
  476. li := l.WithField("vpnIp", IntIp(i.hostId))
  477. if connState := i.ConnectionState; connState != nil {
  478. if peerCert := connState.peerCert; peerCert != nil {
  479. li = li.WithField("certName", peerCert.Details.Name)
  480. }
  481. }
  482. return li
  483. }
  484. //########################
  485. /*
  486. func (hm *HostMap) DebugRemotes(vpnIp uint32) string {
  487. s := "\n"
  488. for _, h := range hm.Hosts {
  489. for _, r := range h.Remotes {
  490. s += fmt.Sprintf("%s : %d ## %v\n", r.addr.IP.String(), r.addr.Port, r.probes)
  491. }
  492. }
  493. return s
  494. }
  495. func (i *HostInfo) HandleReply(addr *net.UDPAddr, counter int) {
  496. for _, r := range i.Remotes {
  497. if r.addr.IP.Equal(addr.IP) && r.addr.Port == addr.Port {
  498. r.ProbeReceived(counter)
  499. }
  500. }
  501. }
  502. func (i *HostInfo) Probes() []*Probe {
  503. p := []*Probe{}
  504. for _, d := range i.Remotes {
  505. p = append(p, &Probe{Addr: d.addr, Counter: d.Probe()})
  506. }
  507. return p
  508. }
  509. */
  510. // Utility functions
  511. func localIps(l *logrus.Logger, allowList *AllowList) *[]net.IP {
  512. //FIXME: This function is pretty garbage
  513. var ips []net.IP
  514. ifaces, _ := net.Interfaces()
  515. for _, i := range ifaces {
  516. allow := allowList.AllowName(i.Name)
  517. if l.Level >= logrus.TraceLevel {
  518. l.WithField("interfaceName", i.Name).WithField("allow", allow).Trace("localAllowList.AllowName")
  519. }
  520. if !allow {
  521. continue
  522. }
  523. addrs, _ := i.Addrs()
  524. for _, addr := range addrs {
  525. var ip net.IP
  526. switch v := addr.(type) {
  527. case *net.IPNet:
  528. //continue
  529. ip = v.IP
  530. case *net.IPAddr:
  531. ip = v.IP
  532. }
  533. //TODO: Filtering out link local for now, this is probably the most correct thing
  534. //TODO: Would be nice to filter out SLAAC MAC based ips as well
  535. if ip.IsLoopback() == false && !ip.IsLinkLocalUnicast() {
  536. allow := allowList.Allow(ip)
  537. if l.Level >= logrus.TraceLevel {
  538. l.WithField("localIp", ip).WithField("allow", allow).Trace("localAllowList.Allow")
  539. }
  540. if !allow {
  541. continue
  542. }
  543. ips = append(ips, ip)
  544. }
  545. }
  546. }
  547. return &ips
  548. }