Debian Codegraph @

hostmap.go

raw
1 package nebula
2
3 import (
4 "context"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "log/slog"
9 "net"
10 "net/netip"
11 "slices"
12 "sync"
13 "sync/atomic"
14 "time"
15
16 "github.com/gaissmai/bart"
17 "github.com/rcrowley/go-metrics"
18 "github.com/slackhq/nebula/cert"
19 "github.com/slackhq/nebula/config"
20 "github.com/slackhq/nebula/header"
21 "github.com/slackhq/nebula/logging"
22 )
23
24 const defaultPromoteEvery = 1000 // Count of packets sent before we try moving a tunnel to a preferred underlay ip address
25 const defaultReQueryEvery = 5000 // Count of packets sent before re-querying a hostinfo to the lighthouse
26 const defaultReQueryWait = time.Minute // Minimum amount of seconds to wait before re-querying a hostinfo the lighthouse. Evaluated every ReQueryEvery
27 const MaxRemotes = 10
28
29 // MaxHostInfosPerVpnIp is the max number of hostinfos we will track for a given vpn ip
30 // 5 allows for an initial handshake and each host pair re-handshaking twice
31 const MaxHostInfosPerVpnIp = 5
32
33 // How long we should prevent roaming back to the previous IP.
34 // This helps prevent flapping due to packets already in flight
35 const RoamingSuppressSeconds = 2
36
37 const (
38 Requested = iota
39 PeerRequested
40 Established
41 Disestablished
42 )
43
44 const (
45 Unknowntype = iota
46 ForwardingType
47 TerminalType
48 )
49
50 type Relay struct {
51 Type int
52 State int
53 LocalIndex uint32
54 RemoteIndex uint32
55 PeerAddr netip.Addr
56 }
57
58 type HostMap struct {
59 sync.RWMutex //Because we concurrently read and write to our maps
60 Indexes map[uint32]*HostInfo
61 Relays map[uint32]*HostInfo // Maps a Relay IDX to a Relay HostInfo object
62 RemoteIndexes map[uint32]*HostInfo
63 // Hosts maps a vpn address to its primary hostinfo, one entry per address we hold a tunnel
64 // for. moreHosts only has an entry while an address is held by 2 or more hostinfos and stores
65 // the full most-recent-first list; moreHosts[a][0] is always the same hostinfo as Hosts[a].
66 // Each address gets its own independent list, so a hostinfo owning multiple addresses can
67 // never corrupt another address's ordering the way the old shared next/prev chain could.
68 // Entries in moreHosts are only ever written by unlockedSetHostsForAddr; Hosts is written
69 // directly only in the single-hostinfo fast paths where moreHosts is known to have no entry,
70 // and unlockedDeleteHostInfo swaps either map for a fresh one when it fully drains.
71 Hosts map[netip.Addr]*HostInfo
72 moreHosts map[netip.Addr][]*HostInfo
73 preferredRanges atomic.Pointer[[]netip.Prefix]
74 l *slog.Logger
75 }
76
77 // For synchronization, treat the pointed-to Relay struct as immutable. To edit the Relay
78 // struct, make a copy of an existing value, edit the fileds in the copy, and
79 // then store a pointer to the new copy in both realyForBy* maps.
80 type RelayState struct {
81 sync.RWMutex
82
83 relays []netip.Addr // Ordered set of VpnAddrs of Hosts to use as relays to access this peer
84 // For data race avoidance, the contents of a *Relay are treated immutably. To update a *Relay, copy the existing data,
85 // modify what needs to be updated, and store the new modified copy in the relayForByIp and relayForByIdx maps (with
86 // the RelayState Lock held)
87 relayForByAddr map[netip.Addr]*Relay // Maps vpnAddr of peers for which this HostInfo is a relay to some Relay info
88 relayForByIdx map[uint32]*Relay // Maps a local index to some Relay info
89 }
90
91 func (rs *RelayState) DeleteRelay(ip netip.Addr) {
92 rs.Lock()
93 defer rs.Unlock()
94 for idx, val := range rs.relays {
95 if val == ip {
96 rs.relays = append(rs.relays[:idx], rs.relays[idx+1:]...)
97 return
98 }
99 }
100 }
101
102 func (rs *RelayState) UpdateRelayForByIpState(vpnIp netip.Addr, state int) {
103 rs.Lock()
104 defer rs.Unlock()
105 if r, ok := rs.relayForByAddr[vpnIp]; ok {
106 newRelay := *r
107 newRelay.State = state
108 rs.relayForByAddr[newRelay.PeerAddr] = &newRelay
109 rs.relayForByIdx[newRelay.LocalIndex] = &newRelay
110 }
111 }
112
113 func (rs *RelayState) UpdateRelayForByIdxState(idx uint32, state int) {
114 rs.Lock()
115 defer rs.Unlock()
116 if r, ok := rs.relayForByIdx[idx]; ok {
117 newRelay := *r
118 newRelay.State = state
119 rs.relayForByAddr[newRelay.PeerAddr] = &newRelay
120 rs.relayForByIdx[newRelay.LocalIndex] = &newRelay
121 }
122 }
123
124 func (rs *RelayState) CopyAllRelayFor() []*Relay {
125 rs.RLock()
126 defer rs.RUnlock()
127 ret := make([]*Relay, 0, len(rs.relayForByIdx))
128 for _, r := range rs.relayForByIdx {
129 ret = append(ret, r)
130 }
131 return ret
132 }
133
134 func (rs *RelayState) GetRelayForByAddr(addr netip.Addr) (*Relay, bool) {
135 rs.RLock()
136 defer rs.RUnlock()
137 r, ok := rs.relayForByAddr[addr]
138 return r, ok
139 }
140
141 func (rs *RelayState) InsertRelayTo(ip netip.Addr) {
142 rs.Lock()
143 defer rs.Unlock()
144 if !slices.Contains(rs.relays, ip) {
145 rs.relays = append(rs.relays, ip)
146 }
147 }
148
149 func (rs *RelayState) CopyRelayIps() []netip.Addr {
150 rs.RLock()
151 defer rs.RUnlock()
152 ret := make([]netip.Addr, len(rs.relays))
153 copy(ret, rs.relays)
154 return ret
155 }
156
157 func (rs *RelayState) CopyRelayForIps() []netip.Addr {
158 rs.RLock()
159 defer rs.RUnlock()
160 currentRelays := make([]netip.Addr, 0, len(rs.relayForByAddr))
161 for relayIp := range rs.relayForByAddr {
162 currentRelays = append(currentRelays, relayIp)
163 }
164 return currentRelays
165 }
166
167 func (rs *RelayState) CopyRelayForIdxs() []uint32 {
168 rs.RLock()
169 defer rs.RUnlock()
170 ret := make([]uint32, 0, len(rs.relayForByIdx))
171 for i := range rs.relayForByIdx {
172 ret = append(ret, i)
173 }
174 return ret
175 }
176
177 func (rs *RelayState) CompleteRelayByIP(vpnIp netip.Addr, remoteIdx uint32) bool {
178 rs.Lock()
179 defer rs.Unlock()
180 r, ok := rs.relayForByAddr[vpnIp]
181 if !ok {
182 return false
183 }
184 newRelay := *r
185 newRelay.State = Established
186 newRelay.RemoteIndex = remoteIdx
187 rs.relayForByIdx[r.LocalIndex] = &newRelay
188 rs.relayForByAddr[r.PeerAddr] = &newRelay
189 return true
190 }
191
192 func (rs *RelayState) CompleteRelayByIdx(localIdx uint32, remoteIdx uint32) (*Relay, bool) {
193 rs.Lock()
194 defer rs.Unlock()
195 r, ok := rs.relayForByIdx[localIdx]
196 if !ok {
197 return nil, false
198 }
199 newRelay := *r
200 newRelay.State = Established
201 newRelay.RemoteIndex = remoteIdx
202 rs.relayForByIdx[r.LocalIndex] = &newRelay
203 rs.relayForByAddr[r.PeerAddr] = &newRelay
204 return &newRelay, true
205 }
206
207 func (rs *RelayState) QueryRelayForByIp(vpnIp netip.Addr) (*Relay, bool) {
208 rs.RLock()
209 defer rs.RUnlock()
210 r, ok := rs.relayForByAddr[vpnIp]
211 return r, ok
212 }
213
214 func (rs *RelayState) QueryRelayForByIdx(idx uint32) (*Relay, bool) {
215 rs.RLock()
216 defer rs.RUnlock()
217 r, ok := rs.relayForByIdx[idx]
218 return r, ok
219 }
220
221 func (rs *RelayState) InsertRelay(ip netip.Addr, idx uint32, r *Relay) {
222 rs.Lock()
223 defer rs.Unlock()
224 rs.relayForByAddr[ip] = r
225 rs.relayForByIdx[idx] = r
226 }
227
228 type NetworkType uint8
229
230 const (
231 NetworkTypeUnknown NetworkType = iota
232 // NetworkTypeVPN is a network that overlaps one or more of the vpnNetworks in our certificate
233 NetworkTypeVPN
234 // NetworkTypeVPNPeer is a network that does not overlap one of our networks
235 NetworkTypeVPNPeer
236 // NetworkTypeUnsafe is a network from Certificate.UnsafeNetworks()
237 NetworkTypeUnsafe
238 )
239
240 type HostInfo struct {
241 remote atomic.Pointer[netip.AddrPort]
242 remotes *RemoteList
243 promoteCounter atomic.Uint32
244 ConnectionState *ConnectionState
245 remoteIndexId uint32
246 localIndexId uint32
247
248 // vpnAddrs is a list of vpn addresses assigned to this host that are within our own vpn networks
249 // The host may have other vpn addresses that are outside our
250 // vpn networks but were removed because they are not usable
251 vpnAddrs []netip.Addr
252
253 // networks is a combination of specific vpn addresses (not prefixes!) and full unsafe networks assigned to this host.
254 networks *bart.Table[NetworkType]
255 relayState RelayState
256
257 // HandshakePacket records the packets used to create this hostinfo
258 // We need these to avoid replayed handshake packets creating new hostinfos which causes churn
259 HandshakePacket map[uint8][]byte
260
261 // nextLHQuery is the earliest we can ask the lighthouse for new information.
262 // This is used to limit lighthouse re-queries in chatty clients
263 nextLHQuery atomic.Int64
264
265 // lastRebindCount is the other side of Interface.rebindCount, if these values don't match then we need to ask LH
266 // for a punch from the remote end of this tunnel. The goal being to prime their conntrack for our traffic just like
267 // with a handshake
268 lastRebindCount int8
269
270 // lastHandshakeTime records the time the remote side told us about at the stage when the handshake was completed locally
271 // Stage 1 packet will contain it if I am a responder, stage 2 packet if I am an initiator
272 // This is used to avoid an attack where a handshake packet is replayed after some time
273 lastHandshakeTime uint64
274
275 lastRoam time.Time
276 lastRoamRemote netip.AddrPort
277
278 //TODO: in, out, and others might benefit from being an atomic.Int32. We could collapse connectionManager pendingDeletion, relayUsed, and in/out into this 1 thing
279 in, out, pendingDeletion atomic.Bool
280
281 // lastUsed tracks the last time ConnectionManager checked the tunnel and it was in use.
282 // This value will be behind against actual tunnel utilization in the hot path.
283 // This should only be used by the ConnectionManagers ticker routine.
284 lastUsed time.Time
285 }
286
287 type ViaSender struct {
288 UdpAddr netip.AddrPort
289 relayHI *HostInfo // relayHI is the host info object of the relay
290 relay *Relay // relay contains the rest of the relay information, including the PeerIP of the host trying to communicate with us.
291 IsRelayed bool // IsRelayed is true if the packet was sent through a relay
292 }
293
294 func (v ViaSender) String() string {
295 if v.IsRelayed {
296 return fmt.Sprintf("%s (relayed)", v.UdpAddr)
297 }
298 return v.UdpAddr.String()
299 }
300
301 func (v ViaSender) MarshalJSON() ([]byte, error) {
302 if v.IsRelayed {
303 return json.Marshal(m{"relay": v.UdpAddr})
304 }
305 return json.Marshal(m{"direct": v.UdpAddr})
306 }
307
308 type cachedPacket struct {
309 messageType header.MessageType
310 messageSubType header.MessageSubType
311 callback packetCallback
312 packet []byte
313 }
314
315 type packetCallback func(t header.MessageType, st header.MessageSubType, h *HostInfo, p, nb, out []byte)
316
317 type cachedPacketMetrics struct {
318 sent metrics.Counter
319 dropped metrics.Counter
320 }
321
322 func NewHostMapFromConfig(l *slog.Logger, c *config.C) *HostMap {
323 hm := newHostMap(l)
324
325 hm.reload(c, true)
326 c.RegisterReloadCallback(func(c *config.C) {
327 hm.reload(c, false)
328 })
329
330 l.Info("Main HostMap created", "preferredRanges", hm.GetPreferredRanges())
331
332 return hm
333 }
334
335 func newHostMap(l *slog.Logger) *HostMap {
336 return &HostMap{
337 Indexes: map[uint32]*HostInfo{},
338 Relays: map[uint32]*HostInfo{},
339 RemoteIndexes: map[uint32]*HostInfo{},
340 Hosts: map[netip.Addr]*HostInfo{},
341 moreHosts: map[netip.Addr][]*HostInfo{},
342 l: l,
343 }
344 }
345
346 func (hm *HostMap) reload(c *config.C, initial bool) {
347 if initial || c.HasChanged("preferred_ranges") {
348 var preferredRanges []netip.Prefix
349 rawPreferredRanges := c.GetStringSlice("preferred_ranges", []string{})
350
351 for _, rawPreferredRange := range rawPreferredRanges {
352 preferredRange, err := netip.ParsePrefix(rawPreferredRange)
353
354 if err != nil {
355 hm.l.Warn("Failed to parse preferred ranges, ignoring",
356 "error", err,
357 "range", rawPreferredRanges,
358 )
359 continue
360 }
361
362 preferredRanges = append(preferredRanges, preferredRange)
363 }
364
365 oldRanges := hm.preferredRanges.Swap(&preferredRanges)
366 if !initial {
367 hm.l.Info("preferred_ranges changed",
368 "oldPreferredRanges", *oldRanges,
369 "newPreferredRanges", preferredRanges,
370 )
371 }
372 }
373 }
374
375 // EmitStats reports host, index, and relay counts to the stats collection system
376 func (hm *HostMap) EmitStats() {
377 hm.RLock()
378 hostLen := len(hm.Hosts)
379 indexLen := len(hm.Indexes)
380 remoteIndexLen := len(hm.RemoteIndexes)
381 relaysLen := len(hm.Relays)
382 hm.RUnlock()
383
384 metrics.GetOrRegisterGauge("hostmap.main.hosts", nil).Update(int64(hostLen))
385 metrics.GetOrRegisterGauge("hostmap.main.indexes", nil).Update(int64(indexLen))
386 metrics.GetOrRegisterGauge("hostmap.main.remoteIndexes", nil).Update(int64(remoteIndexLen))
387 metrics.GetOrRegisterGauge("hostmap.main.relayIndexes", nil).Update(int64(relaysLen))
388 }
389
390 // unlockedSetHostsForAddr stores the per-address hostinfo list (list[0] is the primary). An empty
391 // list removes the address. This is the one place Hosts and moreHosts are written together, keep
392 // it that way. Callers must hold the write lock.
393 func (hm *HostMap) unlockedSetHostsForAddr(addr netip.Addr, list []*HostInfo) {
394 if len(list) == 0 {
395 delete(hm.Hosts, addr)
396 delete(hm.moreHosts, addr)
397 return
398 }
399 hm.Hosts[addr] = list[0]
400 if len(list) > 1 {
401 hm.moreHosts[addr] = list
402 } else {
403 delete(hm.moreHosts, addr)
404 }
405 }
406
407 // unlockedGetHostList returns every hostinfo holding addr, primary first, or nil if we have no
408 // tunnel for addr. The common single-hostinfo case builds a fresh one element list, so keep this
409 // off the packet hot path; the primary is a direct Hosts read. Callers must hold the lock (read
410 // or write).
411 func (hm *HostMap) unlockedGetHostList(addr netip.Addr) []*HostInfo {
412 if list, ok := hm.moreHosts[addr]; ok {
413 return list
414 }
415 if h, ok := hm.Hosts[addr]; ok {
416 return []*HostInfo{h}
417 }
418 return nil
419 }
420
421 // removeHostInfo returns list with hi removed (order preserved), or list unchanged if hi is
422 // absent. It deletes in place: every mutator holds the hostmap write lock and no reader ever
423 // retains a slice across a mutation (readers iterate under RLock), so there is no snapshot to
424 // invalidate.
425 func removeHostInfo(list []*HostInfo, hi *HostInfo) []*HostInfo {
426 idx := slices.Index(list, hi)
427 if idx < 0 {
428 return list
429 }
430 return slices.Delete(list, idx, idx+1)
431 }
432
433 // DeleteHostInfo will fully unlink the hostinfo and return true if no other hostinfo still holds
434 // any of its vpn addrs, meaning we no longer have a tunnel to the peer
435 func (hm *HostMap) DeleteHostInfo(hostinfo *HostInfo) bool {
436 // Delete the host itself, ensuring it's not modified anymore
437 hm.Lock()
438 final := hm.unlockedDeleteHostInfo(hostinfo)
439 hm.Unlock()
440
441 return final
442 }
443
444 func (hm *HostMap) MakePrimary(hostinfo *HostInfo) {
445 hm.Lock()
446 defer hm.Unlock()
447 hm.unlockedMakePrimary(hostinfo)
448 }
449
450 // unlockedMakePrimary reports whether hostinfo is (now) the primary for each of its addresses,
451 // false only when it is no longer in the hostmap at all.
452 func (hm *HostMap) unlockedMakePrimary(hostinfo *HostInfo) bool {
453 // A hostinfo that is no longer in the hostmap must not be re-inserted here. Callers can race
454 // tunnel teardown, deciding to promote under the read lock and only taking the write lock
455 // after a delete fully unlinked the hostinfo (connection manager swapPrimary, AddRelay). Every
456 // live hostinfo is registered in Indexes by unlockedAddHostInfo, so this is a membership test.
457 if hm.Indexes[hostinfo.localIndexId] != hostinfo {
458 return false
459 }
460
461 // Move hostinfo to the front (primary) of each of its address lists. The lists are
462 // independent per address, so this can never leave a dangling entry the way promoting
463 // against a single shared chain could.
464 for _, addr := range hostinfo.vpnAddrs {
465 if hm.Hosts[addr] == hostinfo {
466 // Already primary for this address, the list is already in the right order
467 continue
468 }
469 list := removeHostInfo(hm.unlockedGetHostList(addr), hostinfo)
470 list = append([]*HostInfo{hostinfo}, list...)
471 hm.unlockedSetHostsForAddr(addr, list)
472 }
473 return true
474 }
475
476 // unlockedDeleteHostInfo removes hostinfo from every one of its address lists and from the index
477 // maps. It returns true if this was the last hostinfo for all of its addresses (we no longer have
478 // any tunnel to the peer), which the caller uses to decide whether to clear learned lighthouse
479 // state and disestablish relays.
480 func (hm *HostMap) unlockedDeleteHostInfo(hostinfo *HostInfo) bool {
481 // Remove this hostinfo from each of its address lists. The lists are independent, so a
482 // sibling is never promoted to an address it does not own and no other list is touched.
483 final := true
484 for _, addr := range hostinfo.vpnAddrs {
485 if list, ok := hm.moreHosts[addr]; ok {
486 list = removeHostInfo(list, hostinfo)
487 hm.unlockedSetHostsForAddr(addr, list)
488 if len(list) > 0 {
489 final = false
490 }
491 } else if existing, ok := hm.Hosts[addr]; ok {
492 if existing == hostinfo {
493 // Common case, the only hostinfo for this address. moreHosts has no entry to clean up.
494 delete(hm.Hosts, addr)
495 } else {
496 // We don't hold this address but another hostinfo does, we still have a tunnel to the peer
497 final = false
498 }
499 }
500 }
501
502 // Go maps never shrink their buckets, replace fully drained maps so a node that churned
503 // through a large peer count gives the memory back. Same idiom as the index maps below.
504 if len(hm.Hosts) == 0 {
505 hm.Hosts = map[netip.Addr]*HostInfo{}
506 }
507 if len(hm.moreHosts) == 0 {
508 hm.moreHosts = map[netip.Addr][]*HostInfo{}
509 }
510
511 // The remote index uses index ids outside our control so lets make sure we are only removing
512 // the remote index pointer here if it points to the hostinfo we are deleting
513 hostinfo2, ok := hm.RemoteIndexes[hostinfo.remoteIndexId]
514 if ok && hostinfo2 == hostinfo {
515 delete(hm.RemoteIndexes, hostinfo.remoteIndexId)
516 if len(hm.RemoteIndexes) == 0 {
517 hm.RemoteIndexes = map[uint32]*HostInfo{}
518 }
519 }
520
521 delete(hm.Indexes, hostinfo.localIndexId)
522 if len(hm.Indexes) == 0 {
523 hm.Indexes = map[uint32]*HostInfo{}
524 }
525
526 if hm.l.Enabled(context.Background(), slog.LevelDebug) {
527 hm.l.Debug("Hostmap hostInfo deleted",
528 "hostMap", m{"mapTotalSize": len(hm.Hosts),
529 "vpnAddrs": hostinfo.vpnAddrs, "indexNumber": hostinfo.localIndexId, "remoteIndexNumber": hostinfo.remoteIndexId},
530 )
531 }
532
533 if final {
534 // I have lost connectivity to my peers. My relay tunnel is likely broken. Mark the next
535 // hops as 'Requested' so that new relay tunnels are created in the future.
536 hm.unlockedDisestablishVpnAddrRelayFor(hostinfo)
537 }
538 // Clean up any local relay indexes for which I am acting as a relay hop
539 for _, localRelayIdx := range hostinfo.relayState.CopyRelayForIdxs() {
540 delete(hm.Relays, localRelayIdx)
541 }
542
543 return final
544 }
545
546 func (hm *HostMap) QueryIndex(index uint32) *HostInfo {
547 hm.RLock()
548 if h, ok := hm.Indexes[index]; ok {
549 hm.RUnlock()
550 return h
551 } else {
552 hm.RUnlock()
553 return nil
554 }
555 }
556
557 func (hm *HostMap) QueryRelayIndex(index uint32) *HostInfo {
558 hm.RLock()
559 if h, ok := hm.Relays[index]; ok {
560 hm.RUnlock()
561 return h
562 } else {
563 hm.RUnlock()
564 return nil
565 }
566 }
567
568 func (hm *HostMap) QueryReverseIndex(index uint32) *HostInfo {
569 hm.RLock()
570 if h, ok := hm.RemoteIndexes[index]; ok {
571 hm.RUnlock()
572 return h
573 } else {
574 hm.RUnlock()
575 return nil
576 }
577 }
578
579 func (hm *HostMap) QueryVpnAddr(vpnIp netip.Addr) *HostInfo {
580 return hm.queryVpnAddr(vpnIp, nil)
581 }
582
583 func (hm *HostMap) QueryVpnAddrsRelayFor(targetIps []netip.Addr, relayHostIp netip.Addr) (*HostInfo, *Relay, error) {
584 hm.RLock()
585 defer hm.RUnlock()
586
587 // This runs per relayed packet, so check the primary with a single map probe and only consult
588 // moreHosts when the primary can't relay for us.
589 h, ok := hm.Hosts[relayHostIp]
590 if !ok {
591 return nil, nil, errors.New("unable to find host")
592 }
593
594 for _, targetIp := range targetIps {
595 r, ok := h.relayState.QueryRelayForByIp(targetIp)
596 if ok && r.State == Established {
597 return h, r, nil
598 }
599 }
600
601 if list, ok := hm.moreHosts[relayHostIp]; ok {
602 // list[0] is the primary we already checked
603 for _, h := range list[1:] {
604 for _, targetIp := range targetIps {
605 r, ok := h.relayState.QueryRelayForByIp(targetIp)
606 if ok && r.State == Established {
607 return h, r, nil
608 }
609 }
610 }
611 }
612
613 return nil, nil, errors.New("unable to find host with relay")
614 }
615
616 func (hm *HostMap) unlockedDisestablishVpnAddrRelayFor(hi *HostInfo) {
617 for _, relayHostIp := range hi.relayState.CopyRelayIps() {
618 for _, h := range hm.unlockedGetHostList(relayHostIp) {
619 h.relayState.UpdateRelayForByIpState(hi.vpnAddrs[0], Disestablished)
620 }
621 }
622 for _, rs := range hi.relayState.CopyAllRelayFor() {
623 if rs.Type == ForwardingType {
624 for _, h := range hm.unlockedGetHostList(rs.PeerAddr) {
625 h.relayState.UpdateRelayForByIpState(hi.vpnAddrs[0], Disestablished)
626 }
627 }
628 }
629 }
630
631 func (hm *HostMap) queryVpnAddr(vpnIp netip.Addr, promoteIfce *Interface) *HostInfo {
632 hm.RLock()
633 if h, ok := hm.Hosts[vpnIp]; ok {
634 hm.RUnlock()
635 // Do not attempt promotion if you are a lighthouse
636 if promoteIfce != nil && !promoteIfce.lightHouse.amLighthouse {
637 h.TryPromoteBest(hm.GetPreferredRanges(), promoteIfce)
638 }
639 return h
640
641 }
642
643 hm.RUnlock()
644 return nil
645 }
646
647 // unlockedAddHostInfo assumes you have a write-lock and will add a hostinfo object to the hostmap Indexes and RemoteIndexes maps.
648 // If an entry exists for the Hosts table (vpnIp -> hostinfo) then the provided hostinfo will be made primary
649 func (hm *HostMap) unlockedAddHostInfo(hostinfo *HostInfo, f *Interface) {
650 if f.dnsServer != nil {
651 remoteCert := hostinfo.ConnectionState.peerCert
652 f.dnsServer.Add(remoteCert.Certificate.Name()+".", hostinfo.vpnAddrs)
653 }
654 for _, addr := range hostinfo.vpnAddrs {
655 hm.unlockedInnerAddHostInfo(addr, hostinfo, f)
656 }
657
658 hm.Indexes[hostinfo.localIndexId] = hostinfo
659 hm.RemoteIndexes[hostinfo.remoteIndexId] = hostinfo
660
661 hostinfo.out.Store(true)
662 if f.connectionManager != nil { // f.connectionManager is only nil in some unit tests
663 f.connectionManager.trafficTimer.Add(hostinfo.localIndexId, f.connectionManager.checkInterval)
664 }
665
666 if hm.l.Enabled(context.Background(), slog.LevelDebug) {
667 hm.l.Debug("Hostmap vpnIp added",
668 "hostMap", m{"vpnAddrs": hostinfo.vpnAddrs, "mapTotalSize": len(hm.Hosts),
669 "hostinfo": m{"existing": true, "localIndexId": hostinfo.localIndexId, "vpnAddrs": hostinfo.vpnAddrs}},
670 )
671 }
672 }
673
674 func (hm *HostMap) unlockedInnerAddHostInfo(vpnAddr netip.Addr, hostinfo *HostInfo, f *Interface) {
675 existing, ok := hm.Hosts[vpnAddr]
676 if !ok {
677 // Common case, the first hostinfo for this address. moreHosts stays empty.
678 hm.Hosts[vpnAddr] = hostinfo
679 return
680 }
681
682 // The new hostinfo becomes the primary for this address. Remove any stale copy of it first so
683 // we never hold a duplicate, then prepend.
684 list, ok := hm.moreHosts[vpnAddr]
685 if !ok {
686 list = []*HostInfo{existing}
687 }
688 list = removeHostInfo(list, hostinfo)
689 list = append([]*HostInfo{hostinfo}, list...)
690 hm.unlockedSetHostsForAddr(vpnAddr, list)
691
692 // Enforce the per-address cap by fully retiring the oldest hostinfo once we exceed it.
693 // Deleting it removes it from all of its addresses and the index maps, matching prior behavior.
694 if len(list) > MaxHostInfosPerVpnIp {
695 hm.unlockedDeleteHostInfo(list[len(list)-1])
696 }
697 }
698
699 func (hm *HostMap) GetPreferredRanges() []netip.Prefix {
700 //NOTE: if preferredRanges is ever not stored before a load this will fail to dereference a nil pointer
701 return *hm.preferredRanges.Load()
702 }
703
704 func (hm *HostMap) ForEachVpnAddr(f controlEach) {
705 hm.RLock()
706 defer hm.RUnlock()
707
708 for _, v := range hm.Hosts {
709 f(v)
710 }
711 }
712
713 func (hm *HostMap) ForEachIndex(f controlEach) {
714 hm.RLock()
715 defer hm.RUnlock()
716
717 for _, v := range hm.Indexes {
718 f(v)
719 }
720 }
721
722 // TryPromoteBest handles re-querying lighthouses and probing for better paths
723 // NOTE: It is an error to call this if you are a lighthouse since they should not roam clients!
724 func (i *HostInfo) TryPromoteBest(preferredRanges []netip.Prefix, ifce *Interface) {
725 c := i.promoteCounter.Add(1)
726 if c%ifce.tryPromoteEvery.Load() == 0 {
727 remote := i.GetRemote()
728
729 // return early if we are already on a preferred remote
730 if remote.IsValid() {
731 rIP := remote.Addr()
732 for _, l := range preferredRanges {
733 if l.Contains(rIP) {
734 return
735 }
736 }
737 }
738
739 i.remotes.ForEach(preferredRanges, func(addr netip.AddrPort, preferred bool) {
740 if remote.IsValid() && (!addr.IsValid() || !preferred) {
741 return
742 }
743
744 // Try to send a test packet to that host, this should
745 // cause it to detect a roaming event and switch remotes
746 ifce.sendTo(header.Test, header.TestRequest, i.ConnectionState, i, addr, []byte(""), make([]byte, 12, 12), make([]byte, mtu))
747 })
748 }
749
750 // Re query our lighthouses for new remotes occasionally
751 if c%ifce.reQueryEvery.Load() == 0 && ifce.lightHouse != nil {
752 now := time.Now().UnixNano()
753 if now < i.nextLHQuery.Load() {
754 return
755 }
756
757 i.nextLHQuery.Store(now + ifce.reQueryWait.Load())
758 ifce.lightHouse.QueryServer(i.vpnAddrs[0])
759 }
760 }
761
762 func (i *HostInfo) GetCert() *cert.CachedCertificate {
763 if i.ConnectionState != nil {
764 return i.ConnectionState.peerCert
765 }
766 return nil
767 }
768
769 func (i *HostInfo) GetRemote() netip.AddrPort {
770 if p := i.remote.Load(); p != nil {
771 return *p
772 }
773 return netip.AddrPort{}
774 }
775
776 // TODO: Maybe use ViaSender here?
777 func (i *HostInfo) SetRemote(remote netip.AddrPort) {
778 // We copy here because we likely got this remote from a source that reuses the object
779 if i.GetRemote() != remote {
780 i.remote.Store(&remote)
781 i.remotes.LearnRemote(i.vpnAddrs[0], remote)
782 }
783 }
784
785 // SetRemoteIfPreferred returns true if the remote was changed. The lastRoam
786 // time on the HostInfo will also be updated.
787 func (i *HostInfo) SetRemoteIfPreferred(hm *HostMap, via ViaSender) bool {
788 if via.IsRelayed {
789 return false
790 }
791
792 currentRemote := i.GetRemote()
793 if !currentRemote.IsValid() {
794 i.SetRemote(via.UdpAddr)
795 return true
796 }
797
798 // NOTE: We do this loop here instead of calling `isPreferred` in
799 // remote_list.go so that we only have to loop over preferredRanges once.
800 newIsPreferred := false
801 for _, l := range hm.GetPreferredRanges() {
802 // return early if we are already on a preferred remote
803 if l.Contains(currentRemote.Addr()) {
804 return false
805 }
806
807 if l.Contains(via.UdpAddr.Addr()) {
808 newIsPreferred = true
809 }
810 }
811
812 if newIsPreferred {
813 // Consider this a roaming event
814 i.lastRoam = time.Now()
815 i.lastRoamRemote = currentRemote
816
817 i.SetRemote(via.UdpAddr)
818
819 return true
820 }
821
822 return false
823 }
824
825 // buildNetworks fills in the networks field of HostInfo. It accepts a cert.Certificate so you never ever mix the network types up.
826 func (i *HostInfo) buildNetworks(myVpnNetworksTable *bart.Lite, c cert.Certificate) {
827 if len(c.Networks()) == 1 && len(c.UnsafeNetworks()) == 0 {
828 if myVpnNetworksTable.Contains(c.Networks()[0].Addr()) {
829 return // Simple case, no BART needed
830 }
831 }
832
833 i.networks = new(bart.Table[NetworkType])
834 for _, network := range c.Networks() {
835 nprefix := netip.PrefixFrom(network.Addr(), network.Addr().BitLen())
836 if myVpnNetworksTable.Contains(network.Addr()) {
837 i.networks.Insert(nprefix, NetworkTypeVPN)
838 } else {
839 i.networks.Insert(nprefix, NetworkTypeVPNPeer)
840 }
841 }
842
843 for _, network := range c.UnsafeNetworks() {
844 i.networks.Insert(network, NetworkTypeUnsafe)
845 }
846 }
847
848 // logger returns a derived slog.Logger with per-hostinfo fields pre-bound.
849 func (i *HostInfo) logger(l *slog.Logger) *slog.Logger {
850 if i == nil {
851 return l
852 }
853
854 li := l.With(
855 "vpnAddrs", i.vpnAddrs,
856 "localIndex", i.localIndexId,
857 "remoteIndex", i.remoteIndexId,
858 )
859
860 if connState := i.ConnectionState; connState != nil {
861 if peerCert := connState.peerCert; peerCert != nil {
862 li = li.With("certName", peerCert.Certificate.Name())
863 }
864 }
865
866 return li
867 }
868
869 // Utility functions
870
871 func localAddrs(l *slog.Logger, allowList *LocalAllowList) []netip.Addr {
872 //FIXME: This function is pretty garbage
873 var finalAddrs []netip.Addr
874 ifaces, _ := net.Interfaces()
875 for _, i := range ifaces {
876 allow := allowList.AllowName(i.Name)
877 if l.Enabled(context.Background(), logging.LevelTrace) {
878 l.Log(context.Background(), logging.LevelTrace, "localAllowList.AllowName",
879 "interfaceName", i.Name,
880 "allow", allow,
881 )
882 }
883
884 if !allow {
885 continue
886 }
887 addrs, _ := i.Addrs()
888 for _, rawAddr := range addrs {
889 var addr netip.Addr
890 switch v := rawAddr.(type) {
891 case *net.IPNet:
892 //continue
893 addr, _ = netip.AddrFromSlice(v.IP)
894 case *net.IPAddr:
895 addr, _ = netip.AddrFromSlice(v.IP)
896 }
897
898 if !addr.IsValid() {
899 if l.Enabled(context.Background(), slog.LevelDebug) {
900 l.Debug("addr was invalid", "localAddr", rawAddr)
901 }
902 continue
903 }
904 addr = addr.Unmap()
905
906 if addr.IsLoopback() == false && addr.IsLinkLocalUnicast() == false {
907 isAllowed := allowList.Allow(addr)
908 if l.Enabled(context.Background(), logging.LevelTrace) {
909 l.Log(context.Background(), logging.LevelTrace, "localAllowList.Allow",
910 "localAddr", addr,
911 "allowed", isAllowed,
912 )
913 }
914 if !isAllowed {
915 continue
916 }
917
918 finalAddrs = append(finalAddrs, addr)
919 }
920 }
921 }
922 return finalAddrs
923 }