| 1 |
//go:build e2e_testing |
| 2 |
// +build e2e_testing |
| 3 |
|
| 4 |
package router |
| 5 |
|
| 6 |
import ( |
| 7 |
"context" |
| 8 |
"fmt" |
| 9 |
"net/netip" |
| 10 |
"os" |
| 11 |
"path/filepath" |
| 12 |
"reflect" |
| 13 |
"regexp" |
| 14 |
"sort" |
| 15 |
"sync" |
| 16 |
"sync/atomic" |
| 17 |
"testing" |
| 18 |
"time" |
| 19 |
|
| 20 |
"github.com/google/gopacket" |
| 21 |
"github.com/google/gopacket/layers" |
| 22 |
"github.com/slackhq/nebula" |
| 23 |
"github.com/slackhq/nebula/header" |
| 24 |
"github.com/slackhq/nebula/udp" |
| 25 |
"golang.org/x/exp/maps" |
| 26 |
) |
| 27 |
|
| 28 |
// outNatKey is the (from, to) pair used by outNat. Comparable struct, so it works as a map key without the |
| 29 |
// allocation cost of a string-concat key. |
| 30 |
type outNatKey struct { |
| 31 |
from, to netip.AddrPort |
| 32 |
} |
| 33 |
|
| 34 |
// fannedPacket pairs a UDP TX packet with its source control so the router can route it after popping from |
| 35 |
// the fan-in channel. |
| 36 |
type fannedPacket struct { |
| 37 |
from *nebula.Control |
| 38 |
pkt *udp.Packet |
| 39 |
} |
| 40 |
|
| 41 |
type R struct { |
| 42 |
// Simple map of the ip:port registered on a control to the control |
| 43 |
// Basically a router, right? |
| 44 |
controls map[netip.AddrPort]*nebula.Control |
| 45 |
|
| 46 |
// A map for inbound packets for a control that doesn't know about this address |
| 47 |
inNat map[netip.AddrPort]*nebula.Control |
| 48 |
|
| 49 |
// A last used map, if an inbound packet hit the inNat map then |
| 50 |
// all return packets should use the same last used inbound address for the outbound sender |
| 51 |
outNat map[outNatKey]netip.AddrPort |
| 52 |
|
| 53 |
// A map of vpn ip to the nebula control it belongs to |
| 54 |
vpnControls map[netip.Addr]*nebula.Control |
| 55 |
|
| 56 |
// Cached select infrastructure for RouteForAllUntilTxTun. |
| 57 |
// The controls map is immutable after NewR so the cases are good for the test lifetime. |
| 58 |
// We only rebuild if a different receiver is asked. |
| 59 |
selRecvCtl *nebula.Control |
| 60 |
selCases []reflect.SelectCase |
| 61 |
selCtls []*nebula.Control |
| 62 |
|
| 63 |
// Optional fan-in mode for hot-path benchmarks: one forwarder goroutine per control drains UDP TX into udpFanIn, |
| 64 |
// so RouteForAllUntilTxTun can do a fixed 2-way native select instead of paying reflect.Select per call. |
| 65 |
// Off by default (would otherwise interleave with tests that use GetFromUDP directly on the same control). |
| 66 |
// Enabled by EnableFanIn. |
| 67 |
udpFanIn chan fannedPacket |
| 68 |
stopFanIn chan struct{} |
| 69 |
fanInWG sync.WaitGroup |
| 70 |
fanInMu sync.Mutex |
| 71 |
fanInOn atomic.Bool |
| 72 |
|
| 73 |
ignoreFlows []ignoreFlow |
| 74 |
flow []flowEntry |
| 75 |
|
| 76 |
// A set of additional mermaid graphs to draw in the flow log markdown file |
| 77 |
// Currently consisting only of hostmap renders |
| 78 |
additionalGraphs []mermaidGraph |
| 79 |
|
| 80 |
// All interactions are locked to help serialize behavior |
| 81 |
sync.Mutex |
| 82 |
|
| 83 |
fn string |
| 84 |
cancelRender context.CancelFunc |
| 85 |
t testing.TB |
| 86 |
} |
| 87 |
|
| 88 |
type ignoreFlow struct { |
| 89 |
tun NullBool |
| 90 |
messageType header.MessageType |
| 91 |
subType header.MessageSubType |
| 92 |
//from |
| 93 |
//to |
| 94 |
} |
| 95 |
|
| 96 |
type mermaidGraph struct { |
| 97 |
title string |
| 98 |
content string |
| 99 |
} |
| 100 |
|
| 101 |
type NullBool struct { |
| 102 |
HasValue bool |
| 103 |
IsTrue bool |
| 104 |
} |
| 105 |
|
| 106 |
type flowEntry struct { |
| 107 |
note string |
| 108 |
packet *packet |
| 109 |
} |
| 110 |
|
| 111 |
type packet struct { |
| 112 |
from *nebula.Control |
| 113 |
to *nebula.Control |
| 114 |
packet *udp.Packet |
| 115 |
tun bool // a packet pulled off a tun device |
| 116 |
rx bool // the packet was received by a udp device |
| 117 |
|
| 118 |
// h is the nebula header, parsed once when the packet is recorded. parseErr says why there isn't one, which |
| 119 |
// the flow log reports rather than hiding. Punchy sends a single byte, so an unparseable packet is normal. |
| 120 |
h header.H |
| 121 |
parseErr error |
| 122 |
} |
| 123 |
|
| 124 |
// fromAddr and toAddr are the addresses this packet actually travelled between. Reading them off the control |
| 125 |
// instead would misreport the whole history once a test moves a node. Tun packets are synthesized without |
| 126 |
// addresses, so they fall back to the control. |
| 127 |
func (p *packet) fromAddr() netip.AddrPort { |
| 128 |
if p.tun || !p.packet.From.IsValid() { |
| 129 |
return p.from.GetUDPAddr() |
| 130 |
} |
| 131 |
return p.packet.From |
| 132 |
} |
| 133 |
|
| 134 |
func (p *packet) toAddr() netip.AddrPort { |
| 135 |
if p.tun || !p.packet.To.IsValid() { |
| 136 |
return p.to.GetUDPAddr() |
| 137 |
} |
| 138 |
return p.packet.To |
| 139 |
} |
| 140 |
|
| 141 |
func (p *packet) WasReceived() { |
| 142 |
if p != nil { |
| 143 |
p.rx = true |
| 144 |
} |
| 145 |
} |
| 146 |
|
| 147 |
type ExitType int |
| 148 |
|
| 149 |
const ( |
| 150 |
// KeepRouting the function will get called again on the next packet |
| 151 |
KeepRouting ExitType = 0 |
| 152 |
// ExitNow does not route this packet and exits immediately |
| 153 |
ExitNow ExitType = 1 |
| 154 |
// RouteAndExit routes this packet and exits immediately afterwards |
| 155 |
RouteAndExit ExitType = 2 |
| 156 |
) |
| 157 |
|
| 158 |
type ExitFunc func(packet *udp.Packet, receiver *nebula.Control) ExitType |
| 159 |
|
| 160 |
// NewR creates a new router to pass packets in a controlled fashion between the provided controllers. |
| 161 |
// The packet flow will be recorded in a file within the mermaid directory under the same name as the test. |
| 162 |
// Renders will occur automatically, roughly every 100ms, until a call to RenderFlow() is made |
| 163 |
func NewR(t testing.TB, controls ...*nebula.Control) *R { |
| 164 |
ctx, cancel := context.WithCancel(context.Background()) |
| 165 |
|
| 166 |
if err := os.MkdirAll("mermaid", 0755); err != nil { |
| 167 |
panic(err) |
| 168 |
} |
| 169 |
|
| 170 |
r := &R{ |
| 171 |
controls: make(map[netip.AddrPort]*nebula.Control), |
| 172 |
vpnControls: make(map[netip.Addr]*nebula.Control), |
| 173 |
inNat: make(map[netip.AddrPort]*nebula.Control), |
| 174 |
outNat: make(map[outNatKey]netip.AddrPort), |
| 175 |
flow: []flowEntry{}, |
| 176 |
ignoreFlows: []ignoreFlow{}, |
| 177 |
fn: filepath.Join("mermaid", fmt.Sprintf("%s.md", t.Name())), |
| 178 |
t: t, |
| 179 |
cancelRender: cancel, |
| 180 |
} |
| 181 |
|
| 182 |
// Try to remove our render file |
| 183 |
os.Remove(r.fn) |
| 184 |
|
| 185 |
for _, c := range controls { |
| 186 |
addr := c.GetUDPAddr() |
| 187 |
if _, ok := r.controls[addr]; ok { |
| 188 |
panic("Duplicate listen address: " + addr.String()) |
| 189 |
} |
| 190 |
|
| 191 |
for _, vpnAddr := range c.GetVpnAddrs() { |
| 192 |
r.vpnControls[vpnAddr] = c |
| 193 |
} |
| 194 |
|
| 195 |
r.controls[addr] = c |
| 196 |
} |
| 197 |
|
| 198 |
// Spin the renderer in case we go nuts and the test never completes |
| 199 |
go func() { |
| 200 |
clockSource := time.NewTicker(time.Millisecond * 100) |
| 201 |
defer clockSource.Stop() |
| 202 |
|
| 203 |
for { |
| 204 |
select { |
| 205 |
case <-ctx.Done(): |
| 206 |
return |
| 207 |
case <-clockSource.C: |
| 208 |
r.Lock() |
| 209 |
r.renderHostmaps("clock tick") |
| 210 |
r.renderFlow() |
| 211 |
r.Unlock() |
| 212 |
} |
| 213 |
} |
| 214 |
}() |
| 215 |
|
| 216 |
return r |
| 217 |
} |
| 218 |
|
| 219 |
// AddRoute will place the nebula controller at the ip and port specified. |
| 220 |
// It does not look at the addr attached to the instance. |
| 221 |
// If a route is used, this will behave like a NAT for the return path. |
| 222 |
// Rewriting the source ip:port to what was last sent to from the origin |
| 223 |
func (r *R) AddRoute(ip netip.Addr, port uint16, c *nebula.Control) { |
| 224 |
r.Lock() |
| 225 |
defer r.Unlock() |
| 226 |
|
| 227 |
inAddr := netip.AddrPortFrom(ip, port) |
| 228 |
if _, ok := r.inNat[inAddr]; ok { |
| 229 |
panic("Duplicate listen address inNat: " + inAddr.String()) |
| 230 |
} |
| 231 |
r.inNat[inAddr] = c |
| 232 |
} |
| 233 |
|
| 234 |
// RenderFlow renders the packet flow seen up until now and stops further automatic renders from happening. |
| 235 |
func (r *R) RenderFlow() { |
| 236 |
r.cancelRender() |
| 237 |
r.Lock() |
| 238 |
defer r.Unlock() |
| 239 |
r.renderFlow() |
| 240 |
} |
| 241 |
|
| 242 |
// CancelFlowLogs stops flow logs from being tracked and destroys any logs already collected |
| 243 |
func (r *R) CancelFlowLogs() { |
| 244 |
r.cancelRender() |
| 245 |
r.Lock() |
| 246 |
r.flow = nil |
| 247 |
r.Unlock() |
| 248 |
} |
| 249 |
|
| 250 |
// renderFlow writes the flow log to disk. Caller must hold r.Lock. renderFlow reads r.flow / r.additionalGraphs and |
| 251 |
// the *packet pointers stashed inside, all of which are mutated under the same lock by routing paths. |
| 252 |
func (r *R) renderFlow() { |
| 253 |
if r.flow == nil { |
| 254 |
return |
| 255 |
} |
| 256 |
|
| 257 |
f, err := os.OpenFile(r.fn, os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0644) |
| 258 |
if err != nil { |
| 259 |
panic(err) |
| 260 |
} |
| 261 |
|
| 262 |
var participants = map[netip.AddrPort]struct{}{} |
| 263 |
var participantsVals []string |
| 264 |
|
| 265 |
fmt.Fprintln(f, "```mermaid") |
| 266 |
fmt.Fprintln(f, "sequenceDiagram") |
| 267 |
|
| 268 |
// Assemble participants |
| 269 |
for _, e := range r.flow { |
| 270 |
if e.packet == nil { |
| 271 |
continue |
| 272 |
} |
| 273 |
|
| 274 |
addr := e.packet.fromAddr() |
| 275 |
if _, ok := participants[addr]; ok { |
| 276 |
continue |
| 277 |
} |
| 278 |
participants[addr] = struct{}{} |
| 279 |
sanAddr := normalizeName(addr.String()) |
| 280 |
participantsVals = append(participantsVals, sanAddr) |
| 281 |
fmt.Fprintf( |
| 282 |
f, " participant %s as Nebula: %s<br/>UDP: %s\n", |
| 283 |
sanAddr, e.packet.from.GetVpnAddrs(), sanAddr, |
| 284 |
) |
| 285 |
} |
| 286 |
|
| 287 |
if len(participantsVals) > 2 { |
| 288 |
// Get the first and last participantVals for notes |
| 289 |
participantsVals = []string{participantsVals[0], participantsVals[len(participantsVals)-1]} |
| 290 |
} |
| 291 |
|
| 292 |
// Print packets |
| 293 |
for _, e := range r.flow { |
| 294 |
if e.packet == nil { |
| 295 |
//fmt.Fprintf(f, " note over %s: %s\n", strings.Join(participantsVals, ", "), e.note) |
| 296 |
continue |
| 297 |
} |
| 298 |
|
| 299 |
p := e.packet |
| 300 |
if p.tun { |
| 301 |
fmt.Fprintln(f, r.formatUdpPacket(p)) |
| 302 |
|
| 303 |
} else { |
| 304 |
line := "--x" |
| 305 |
if p.rx { |
| 306 |
line = "->>" |
| 307 |
} |
| 308 |
|
| 309 |
detail := fmt.Sprintf("%s(%s), index %v, counter: %v", |
| 310 |
p.h.TypeName(), p.h.SubTypeName(), p.h.RemoteIndex, p.h.MessageCounter) |
| 311 |
if p.parseErr != nil { |
| 312 |
detail = fmt.Sprintf("unparsed, %v (%d bytes)", p.parseErr, len(p.packet.Data)) |
| 313 |
} |
| 314 |
|
| 315 |
fmt.Fprintf(f, " %s%s%s: %s\n", |
| 316 |
normalizeName(p.fromAddr().String()), |
| 317 |
line, |
| 318 |
normalizeName(p.toAddr().String()), |
| 319 |
detail, |
| 320 |
) |
| 321 |
} |
| 322 |
} |
| 323 |
fmt.Fprintln(f, "```") |
| 324 |
|
| 325 |
for _, g := range r.additionalGraphs { |
| 326 |
fmt.Fprintf(f, "## %s\n", g.title) |
| 327 |
fmt.Fprintln(f, "```mermaid") |
| 328 |
fmt.Fprintln(f, g.content) |
| 329 |
fmt.Fprintln(f, "```") |
| 330 |
} |
| 331 |
} |
| 332 |
|
| 333 |
func normalizeName(s string) string { |
| 334 |
rx := regexp.MustCompile("[\\[\\]\\:]") |
| 335 |
return rx.ReplaceAllLiteralString(s, "_") |
| 336 |
} |
| 337 |
|
| 338 |
// IgnoreFlow tells the router to stop recording future flows that matches the provided criteria. |
| 339 |
// messageType and subType will target nebula underlay packets while tun will target nebula overlay packets |
| 340 |
// NOTE: This is a very broad system, if you set tun to true then no more tun traffic will be rendered |
| 341 |
func (r *R) IgnoreFlow(messageType header.MessageType, subType header.MessageSubType, tun NullBool) { |
| 342 |
r.Lock() |
| 343 |
defer r.Unlock() |
| 344 |
r.ignoreFlows = append(r.ignoreFlows, ignoreFlow{ |
| 345 |
tun, |
| 346 |
messageType, |
| 347 |
subType, |
| 348 |
}) |
| 349 |
} |
| 350 |
|
| 351 |
func (r *R) RenderHostmaps(title string, controls ...*nebula.Control) { |
| 352 |
r.Lock() |
| 353 |
defer r.Unlock() |
| 354 |
|
| 355 |
s := renderHostmaps(controls...) |
| 356 |
if len(r.additionalGraphs) > 0 { |
| 357 |
lastGraph := r.additionalGraphs[len(r.additionalGraphs)-1] |
| 358 |
if lastGraph.content == s && lastGraph.title == title { |
| 359 |
// Ignore this rendering if it matches the last rendering added |
| 360 |
// This is useful if you want to track rendering changes |
| 361 |
return |
| 362 |
} |
| 363 |
} |
| 364 |
|
| 365 |
r.additionalGraphs = append(r.additionalGraphs, mermaidGraph{ |
| 366 |
title: title, |
| 367 |
content: s, |
| 368 |
}) |
| 369 |
} |
| 370 |
|
| 371 |
func (r *R) renderHostmaps(title string) { |
| 372 |
c := maps.Values(r.controls) |
| 373 |
sort.SliceStable(c, func(i, j int) bool { |
| 374 |
return c[i].GetVpnAddrs()[0].Compare(c[j].GetVpnAddrs()[0]) > 0 |
| 375 |
}) |
| 376 |
|
| 377 |
s := renderHostmaps(c...) |
| 378 |
if len(r.additionalGraphs) > 0 { |
| 379 |
lastGraph := r.additionalGraphs[len(r.additionalGraphs)-1] |
| 380 |
if lastGraph.content == s { |
| 381 |
// Ignore this rendering if it matches the last rendering added |
| 382 |
// This is useful if you want to track rendering changes |
| 383 |
return |
| 384 |
} |
| 385 |
} |
| 386 |
|
| 387 |
r.additionalGraphs = append(r.additionalGraphs, mermaidGraph{ |
| 388 |
title: title, |
| 389 |
content: s, |
| 390 |
}) |
| 391 |
} |
| 392 |
|
| 393 |
// InjectFlow can be used to record packet flow if the test is handling the routing on its own. |
| 394 |
// The packet is assumed to have been received |
| 395 |
func (r *R) InjectFlow(from, to *nebula.Control, p *udp.Packet) { |
| 396 |
r.Lock() |
| 397 |
defer r.Unlock() |
| 398 |
r.unlockedInjectFlow(from, to, p, false) |
| 399 |
} |
| 400 |
|
| 401 |
func (r *R) Log(arg ...any) { |
| 402 |
if r.flow == nil { |
| 403 |
return |
| 404 |
} |
| 405 |
|
| 406 |
r.Lock() |
| 407 |
r.flow = append(r.flow, flowEntry{note: fmt.Sprint(arg...)}) |
| 408 |
r.t.Log(arg...) |
| 409 |
r.Unlock() |
| 410 |
} |
| 411 |
|
| 412 |
func (r *R) Logf(format string, arg ...any) { |
| 413 |
if r.flow == nil { |
| 414 |
return |
| 415 |
} |
| 416 |
|
| 417 |
r.Lock() |
| 418 |
r.flow = append(r.flow, flowEntry{note: fmt.Sprintf(format, arg...)}) |
| 419 |
r.t.Logf(format, arg...) |
| 420 |
r.Unlock() |
| 421 |
} |
| 422 |
|
| 423 |
// unlockedInjectFlow is used by the router to record a packet has been transmitted, the packet is returned and |
| 424 |
// should be marked as received AFTER it has been placed on the receivers channel. |
| 425 |
// If flow logs have been disabled this function will return nil |
| 426 |
func (r *R) unlockedInjectFlow(from, to *nebula.Control, p *udp.Packet, tun bool) *packet { |
| 427 |
if r.flow == nil { |
| 428 |
return nil |
| 429 |
} |
| 430 |
|
| 431 |
r.renderHostmaps(fmt.Sprintf("Packet %v", len(r.flow))) |
| 432 |
|
| 433 |
var h header.H |
| 434 |
var parseErr error |
| 435 |
if !tun { |
| 436 |
parseErr = h.Parse(p.Data) |
| 437 |
} |
| 438 |
|
| 439 |
// Decide before copying, the copy comes from a freelist and an ignored packet would never be released |
| 440 |
for _, i := range r.ignoreFlows { |
| 441 |
if tun { |
| 442 |
if i.tun.HasValue && i.tun.IsTrue { |
| 443 |
return nil |
| 444 |
} |
| 445 |
continue |
| 446 |
} |
| 447 |
|
| 448 |
// A packet we could not parse has no type to match against, so no rule can ignore it |
| 449 |
if parseErr == nil && i.messageType == h.Type && i.subType == h.Subtype { |
| 450 |
return nil |
| 451 |
} |
| 452 |
} |
| 453 |
|
| 454 |
fp := &packet{ |
| 455 |
from: from, |
| 456 |
to: to, |
| 457 |
packet: p.Copy(), |
| 458 |
tun: tun, |
| 459 |
h: h, |
| 460 |
parseErr: parseErr, |
| 461 |
} |
| 462 |
|
| 463 |
r.flow = append(r.flow, flowEntry{packet: fp}) |
| 464 |
return fp |
| 465 |
} |
| 466 |
|
| 467 |
// OnceFrom will route a single packet from sender then return |
| 468 |
// If the router doesn't have the nebula controller for that address, we panic |
| 469 |
func (r *R) OnceFrom(sender *nebula.Control) { |
| 470 |
r.RouteExitFunc(sender, func(*udp.Packet, *nebula.Control) ExitType { |
| 471 |
return RouteAndExit |
| 472 |
}) |
| 473 |
} |
| 474 |
|
| 475 |
// RouteUntilTxTun will route for sender and return when a packet is seen on receivers tun |
| 476 |
// If the router doesn't have the nebula controller for that address, we panic |
| 477 |
func (r *R) RouteUntilTxTun(sender *nebula.Control, receiver *nebula.Control) []byte { |
| 478 |
tunTx := receiver.GetTunTxChan() |
| 479 |
udpTx := sender.GetUDPTxChan() |
| 480 |
|
| 481 |
for { |
| 482 |
select { |
| 483 |
// Maybe we already have something on the tun for us |
| 484 |
case b := <-tunTx: |
| 485 |
r.Lock() |
| 486 |
np := udp.Packet{Data: make([]byte, len(b))} |
| 487 |
copy(np.Data, b) |
| 488 |
r.unlockedInjectFlow(receiver, receiver, &np, true) |
| 489 |
r.Unlock() |
| 490 |
return b |
| 491 |
|
| 492 |
// Nope, lets push the sender along |
| 493 |
case p := <-udpTx: |
| 494 |
r.Lock() |
| 495 |
a := sender.GetUDPAddr() |
| 496 |
c := r.getControl(a, p.To, p) |
| 497 |
if c == nil { |
| 498 |
r.Unlock() |
| 499 |
panic("No control for udp tx " + a.String()) |
| 500 |
} |
| 501 |
fp := r.unlockedInjectFlow(sender, c, p, false) |
| 502 |
c.InjectUDPPacket(p) // copies internally; original is ours to release |
| 503 |
fp.WasReceived() |
| 504 |
r.Unlock() |
| 505 |
p.Release() |
| 506 |
} |
| 507 |
} |
| 508 |
} |
| 509 |
|
| 510 |
// RouteForAllUntilTxTun will route for everyone and return when a packet is seen on the receiver's tun. |
| 511 |
// If a control's UDP TX address can't be matched to a registered control, we panic. |
| 512 |
// |
| 513 |
// For allocation-sensitive callers (hot-path benchmarks, in particular relay |
| 514 |
// benches with 3+ controls), call EnableFanIn() first. |
| 515 |
func (r *R) RouteForAllUntilTxTun(receiver *nebula.Control) []byte { |
| 516 |
if r.fanInOn.Load() { |
| 517 |
return r.routeFanIn(receiver) |
| 518 |
} |
| 519 |
return r.routeReflect(receiver) |
| 520 |
} |
| 521 |
|
| 522 |
// routeFanIn is the alloc-free path used when EnableFanIn is in effect. |
| 523 |
func (r *R) routeFanIn(receiver *nebula.Control) []byte { |
| 524 |
tunTx := receiver.GetTunTxChan() |
| 525 |
for { |
| 526 |
select { |
| 527 |
case p := <-tunTx: |
| 528 |
r.Lock() |
| 529 |
if r.flow != nil { |
| 530 |
np := udp.Packet{Data: make([]byte, len(p))} |
| 531 |
copy(np.Data, p) |
| 532 |
r.unlockedInjectFlow(receiver, receiver, &np, true) |
| 533 |
} |
| 534 |
r.Unlock() |
| 535 |
return p |
| 536 |
case fp := <-r.udpFanIn: |
| 537 |
r.routeUDP(fp.from, fp.pkt) |
| 538 |
} |
| 539 |
} |
| 540 |
} |
| 541 |
|
| 542 |
// routeReflect is the default reflect.Select-based path. Pays the boxing allocation per call but doesn't interfere |
| 543 |
// with tests that pull packets directly from controls' UDP TX channels via GetFromUDP. |
| 544 |
func (r *R) routeReflect(receiver *nebula.Control) []byte { |
| 545 |
sc, cm := r.selectCasesFor(receiver) |
| 546 |
for { |
| 547 |
x, rx, _ := reflect.Select(sc) |
| 548 |
if x == 0 { |
| 549 |
p := rx.Interface().([]byte) |
| 550 |
r.Lock() |
| 551 |
if r.flow != nil { |
| 552 |
np := udp.Packet{Data: make([]byte, len(p))} |
| 553 |
copy(np.Data, p) |
| 554 |
r.unlockedInjectFlow(cm[x], cm[x], &np, true) |
| 555 |
} |
| 556 |
r.Unlock() |
| 557 |
return p |
| 558 |
} |
| 559 |
r.routeUDP(cm[x], rx.Interface().(*udp.Packet)) |
| 560 |
} |
| 561 |
} |
| 562 |
|
| 563 |
// EnableFanIn switches RouteForAllUntilTxTun to the alloc-free fan-in path. |
| 564 |
// One forwarder goroutine per registered control drains UDP TX into a shared channel that RouteForAllUntilTxTun selects |
| 565 |
// on alongside the receiver's TUN TX channel. |
| 566 |
func (r *R) EnableFanIn() { |
| 567 |
r.fanInMu.Lock() |
| 568 |
defer r.fanInMu.Unlock() |
| 569 |
if r.fanInOn.Load() { |
| 570 |
return |
| 571 |
} |
| 572 |
r.udpFanIn = make(chan fannedPacket, 32) |
| 573 |
r.stopFanIn = make(chan struct{}) |
| 574 |
for _, c := range r.controls { |
| 575 |
r.startFanInWorker(c) |
| 576 |
} |
| 577 |
r.fanInOn.Store(true) |
| 578 |
r.t.Cleanup(r.stopFanInWorkers) |
| 579 |
} |
| 580 |
|
| 581 |
// startFanInWorker spawns a goroutine that drains c's UDP TX into r.udpFanIn. |
| 582 |
func (r *R) startFanInWorker(c *nebula.Control) { |
| 583 |
r.fanInWG.Add(1) |
| 584 |
udpTx := c.GetUDPTxChan() |
| 585 |
go func() { |
| 586 |
defer r.fanInWG.Done() |
| 587 |
for { |
| 588 |
select { |
| 589 |
case <-r.stopFanIn: |
| 590 |
return |
| 591 |
case p := <-udpTx: |
| 592 |
select { |
| 593 |
case <-r.stopFanIn: |
| 594 |
p.Release() |
| 595 |
return |
| 596 |
case r.udpFanIn <- fannedPacket{from: c, pkt: p}: |
| 597 |
} |
| 598 |
} |
| 599 |
} |
| 600 |
}() |
| 601 |
} |
| 602 |
|
| 603 |
// stopFanInWorkers signals the fan-in goroutines to exit and waits for them. |
| 604 |
func (r *R) stopFanInWorkers() { |
| 605 |
r.fanInMu.Lock() |
| 606 |
wasOn := r.fanInOn.Swap(false) |
| 607 |
r.fanInMu.Unlock() |
| 608 |
if !wasOn { |
| 609 |
return |
| 610 |
} |
| 611 |
close(r.stopFanIn) |
| 612 |
r.fanInWG.Wait() |
| 613 |
} |
| 614 |
|
| 615 |
// routeUDP forwards a UDP TX packet from the named source control to the destination control derived from p.To, |
| 616 |
// releasing the source packet after InjectUDPPacket has copied its bytes into a fresh pool slot. |
| 617 |
func (r *R) routeUDP(from *nebula.Control, p *udp.Packet) { |
| 618 |
r.Lock() |
| 619 |
defer r.Unlock() |
| 620 |
a := from.GetUDPAddr() |
| 621 |
c := r.getControl(a, p.To, p) |
| 622 |
if c == nil { |
| 623 |
panic(fmt.Sprintf("No control for udp tx %s", p.To)) |
| 624 |
} |
| 625 |
fp := r.unlockedInjectFlow(from, c, p, false) |
| 626 |
c.InjectUDPPacket(p) // copies internally; original is ours to release |
| 627 |
fp.WasReceived() |
| 628 |
p.Release() |
| 629 |
} |
| 630 |
|
| 631 |
// selectCasesFor returns the SelectCase array used by routeReflect: one slot for the receiver's TUN TX channel followed |
| 632 |
// by one per control's UDP TX channel. Cached for the test lifetime, only rebuilt if the receiver changes. |
| 633 |
func (r *R) selectCasesFor(receiver *nebula.Control) ([]reflect.SelectCase, []*nebula.Control) { |
| 634 |
r.Lock() |
| 635 |
defer r.Unlock() |
| 636 |
if r.selRecvCtl == receiver && r.selCases != nil { |
| 637 |
return r.selCases, r.selCtls |
| 638 |
} |
| 639 |
sc := make([]reflect.SelectCase, len(r.controls)+1) |
| 640 |
cm := make([]*nebula.Control, len(r.controls)+1) |
| 641 |
sc[0] = reflect.SelectCase{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(receiver.GetTunTxChan())} |
| 642 |
cm[0] = receiver |
| 643 |
i := 1 |
| 644 |
for _, c := range r.controls { |
| 645 |
sc[i] = reflect.SelectCase{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(c.GetUDPTxChan())} |
| 646 |
cm[i] = c |
| 647 |
i++ |
| 648 |
} |
| 649 |
r.selRecvCtl = receiver |
| 650 |
r.selCases = sc |
| 651 |
r.selCtls = cm |
| 652 |
return sc, cm |
| 653 |
} |
| 654 |
|
| 655 |
// RouteExitFunc will call the whatDo func with each udp packet from sender. |
| 656 |
// whatDo can return: |
| 657 |
// - exitNow: the packet will not be routed and this call will return immediately |
| 658 |
// - routeAndExit: this call will return immediately after routing the last packet from sender |
| 659 |
// - keepRouting: the packet will be routed and whatDo will be called again on the next packet from sender |
| 660 |
func (r *R) RouteExitFunc(sender *nebula.Control, whatDo ExitFunc) { |
| 661 |
h := &header.H{} |
| 662 |
for { |
| 663 |
p := sender.GetFromUDP(true) |
| 664 |
r.Lock() |
| 665 |
if err := h.Parse(p.Data); err != nil { |
| 666 |
panic(err) |
| 667 |
} |
| 668 |
|
| 669 |
receiver := r.getControl(sender.GetUDPAddr(), p.To, p) |
| 670 |
if receiver == nil { |
| 671 |
r.Unlock() |
| 672 |
panic("Can't RouteExitFunc for host: " + p.To.String()) |
| 673 |
} |
| 674 |
|
| 675 |
e := whatDo(p, receiver) |
| 676 |
switch e { |
| 677 |
case ExitNow: |
| 678 |
r.Unlock() |
| 679 |
p.Release() |
| 680 |
return |
| 681 |
|
| 682 |
case RouteAndExit: |
| 683 |
fp := r.unlockedInjectFlow(sender, receiver, p, false) |
| 684 |
receiver.InjectUDPPacket(p) |
| 685 |
fp.WasReceived() |
| 686 |
r.Unlock() |
| 687 |
p.Release() |
| 688 |
return |
| 689 |
|
| 690 |
case KeepRouting: |
| 691 |
fp := r.unlockedInjectFlow(sender, receiver, p, false) |
| 692 |
receiver.InjectUDPPacket(p) |
| 693 |
fp.WasReceived() |
| 694 |
|
| 695 |
default: |
| 696 |
panic(fmt.Sprintf("Unknown exitFunc return: %v", e)) |
| 697 |
} |
| 698 |
|
| 699 |
r.Unlock() |
| 700 |
p.Release() |
| 701 |
} |
| 702 |
} |
| 703 |
|
| 704 |
// RouteUntilAfterMsgType will route for sender until a message type is seen and sent from sender |
| 705 |
// If the router doesn't have the nebula controller for that address, we panic |
| 706 |
func (r *R) RouteUntilAfterMsgType(sender *nebula.Control, msgType header.MessageType, subType header.MessageSubType) { |
| 707 |
h := &header.H{} |
| 708 |
r.RouteExitFunc(sender, func(p *udp.Packet, r *nebula.Control) ExitType { |
| 709 |
if err := h.Parse(p.Data); err != nil { |
| 710 |
panic(err) |
| 711 |
} |
| 712 |
if h.Type == msgType && h.Subtype == subType { |
| 713 |
return RouteAndExit |
| 714 |
} |
| 715 |
|
| 716 |
return KeepRouting |
| 717 |
}) |
| 718 |
} |
| 719 |
|
| 720 |
// RouteFor routes everything that shows up for the given duration and then returns. Use it to let a test settle |
| 721 |
// deterministically rather than sleeping and hoping: a single FlushAll races a completing handshake, which queues |
| 722 |
// more packets right behind it. |
| 723 |
func (r *R) RouteFor(d time.Duration) { |
| 724 |
r.RouteForAllExitFuncOrTimeout(d, func(*udp.Packet, *nebula.Control) ExitType { |
| 725 |
return KeepRouting |
| 726 |
}) |
| 727 |
} |
| 728 |
|
| 729 |
// RouteForAllExitFuncOrTimeout is RouteForAllExitFunc with a deadline, reporting whether whatDo asked to exit |
| 730 |
// before time ran out. The unbounded version blocks forever on a quiet network, so this is what a test needs to |
| 731 |
// assert that something does NOT happen, or to route for a fixed settling period. |
| 732 |
func (r *R) RouteForAllExitFuncOrTimeout(timeout time.Duration, whatDo ExitFunc) bool { |
| 733 |
sc := make([]reflect.SelectCase, 0, len(r.controls)+1) |
| 734 |
cm := make([]*nebula.Control, 0, len(r.controls)) |
| 735 |
|
| 736 |
for _, c := range r.controls { |
| 737 |
sc = append(sc, reflect.SelectCase{ |
| 738 |
Dir: reflect.SelectRecv, |
| 739 |
Chan: reflect.ValueOf(c.GetUDPTxChan()), |
| 740 |
Send: reflect.Value{}, |
| 741 |
}) |
| 742 |
cm = append(cm, c) |
| 743 |
} |
| 744 |
|
| 745 |
timer := time.NewTimer(timeout) |
| 746 |
defer timer.Stop() |
| 747 |
sc = append(sc, reflect.SelectCase{ |
| 748 |
Dir: reflect.SelectRecv, |
| 749 |
Chan: reflect.ValueOf(timer.C), |
| 750 |
Send: reflect.Value{}, |
| 751 |
}) |
| 752 |
|
| 753 |
for { |
| 754 |
x, rx, _ := reflect.Select(sc) |
| 755 |
if x == len(cm) { |
| 756 |
return false |
| 757 |
} |
| 758 |
|
| 759 |
r.Lock() |
| 760 |
p := rx.Interface().(*udp.Packet) |
| 761 |
receiver := r.getControl(cm[x].GetUDPAddr(), p.To, p) |
| 762 |
if receiver == nil { |
| 763 |
r.Unlock() |
| 764 |
panic("Can't RouteForAllExitFuncOrTimeout for host: " + p.To.String()) |
| 765 |
} |
| 766 |
|
| 767 |
e := whatDo(p, receiver) |
| 768 |
switch e { |
| 769 |
case ExitNow: |
| 770 |
r.Unlock() |
| 771 |
p.Release() |
| 772 |
return true |
| 773 |
|
| 774 |
case RouteAndExit: |
| 775 |
fp := r.unlockedInjectFlow(cm[x], receiver, p, false) |
| 776 |
receiver.InjectUDPPacket(p) |
| 777 |
fp.WasReceived() |
| 778 |
r.Unlock() |
| 779 |
p.Release() |
| 780 |
return true |
| 781 |
|
| 782 |
case KeepRouting: |
| 783 |
fp := r.unlockedInjectFlow(cm[x], receiver, p, false) |
| 784 |
receiver.InjectUDPPacket(p) |
| 785 |
fp.WasReceived() |
| 786 |
|
| 787 |
default: |
| 788 |
panic(fmt.Sprintf("Unknown exitFunc return: %v", e)) |
| 789 |
} |
| 790 |
r.Unlock() |
| 791 |
p.Release() |
| 792 |
} |
| 793 |
} |
| 794 |
|
| 795 |
func (r *R) RouteForAllUntilAfterMsgTypeTo(receiver *nebula.Control, msgType header.MessageType, subType header.MessageSubType) { |
| 796 |
h := &header.H{} |
| 797 |
r.RouteForAllExitFunc(func(p *udp.Packet, r *nebula.Control) ExitType { |
| 798 |
if r != receiver { |
| 799 |
return KeepRouting |
| 800 |
} |
| 801 |
|
| 802 |
if err := h.Parse(p.Data); err != nil { |
| 803 |
panic(err) |
| 804 |
} |
| 805 |
|
| 806 |
if h.Type == msgType && h.Subtype == subType { |
| 807 |
return RouteAndExit |
| 808 |
} |
| 809 |
|
| 810 |
return KeepRouting |
| 811 |
}) |
| 812 |
} |
| 813 |
|
| 814 |
func (r *R) InjectUDPPacket(sender, receiver *nebula.Control, packet *udp.Packet) { |
| 815 |
r.Lock() |
| 816 |
defer r.Unlock() |
| 817 |
|
| 818 |
fp := r.unlockedInjectFlow(sender, receiver, packet, false) |
| 819 |
receiver.InjectUDPPacket(packet) |
| 820 |
fp.WasReceived() |
| 821 |
} |
| 822 |
|
| 823 |
// RouteForUntilAfterToAddr will route for sender and return only after it sees and sends a packet destined for toAddr |
| 824 |
// finish can be any of the exitType values except `keepRouting`, the default value is `routeAndExit` |
| 825 |
// If the router doesn't have the nebula controller for that address, we panic |
| 826 |
func (r *R) RouteForUntilAfterToAddr(sender *nebula.Control, toAddr netip.AddrPort, finish ExitType) { |
| 827 |
if finish == KeepRouting { |
| 828 |
finish = RouteAndExit |
| 829 |
} |
| 830 |
|
| 831 |
r.RouteExitFunc(sender, func(p *udp.Packet, r *nebula.Control) ExitType { |
| 832 |
if p.To == toAddr { |
| 833 |
return finish |
| 834 |
} |
| 835 |
|
| 836 |
return KeepRouting |
| 837 |
}) |
| 838 |
} |
| 839 |
|
| 840 |
// RouteForAllExitFunc will route for every registered controller and calls the whatDo func with each udp packet from |
| 841 |
// whatDo can return: |
| 842 |
// - exitNow: the packet will not be routed and this call will return immediately |
| 843 |
// - routeAndExit: this call will return immediately after routing the last packet from sender |
| 844 |
// - keepRouting: the packet will be routed and whatDo will be called again on the next packet from sender |
| 845 |
func (r *R) RouteForAllExitFunc(whatDo ExitFunc) { |
| 846 |
sc := make([]reflect.SelectCase, len(r.controls)) |
| 847 |
cm := make([]*nebula.Control, len(r.controls)) |
| 848 |
|
| 849 |
i := 0 |
| 850 |
for _, c := range r.controls { |
| 851 |
sc[i] = reflect.SelectCase{ |
| 852 |
Dir: reflect.SelectRecv, |
| 853 |
Chan: reflect.ValueOf(c.GetUDPTxChan()), |
| 854 |
Send: reflect.Value{}, |
| 855 |
} |
| 856 |
|
| 857 |
cm[i] = c |
| 858 |
i++ |
| 859 |
} |
| 860 |
|
| 861 |
for { |
| 862 |
x, rx, _ := reflect.Select(sc) |
| 863 |
r.Lock() |
| 864 |
|
| 865 |
p := rx.Interface().(*udp.Packet) |
| 866 |
receiver := r.getControl(cm[x].GetUDPAddr(), p.To, p) |
| 867 |
if receiver == nil { |
| 868 |
r.Unlock() |
| 869 |
panic("Can't RouteForAllExitFunc for host: " + p.To.String()) |
| 870 |
} |
| 871 |
|
| 872 |
e := whatDo(p, receiver) |
| 873 |
switch e { |
| 874 |
case ExitNow: |
| 875 |
r.Unlock() |
| 876 |
p.Release() |
| 877 |
return |
| 878 |
|
| 879 |
case RouteAndExit: |
| 880 |
fp := r.unlockedInjectFlow(cm[x], receiver, p, false) |
| 881 |
receiver.InjectUDPPacket(p) |
| 882 |
fp.WasReceived() |
| 883 |
r.Unlock() |
| 884 |
p.Release() |
| 885 |
return |
| 886 |
|
| 887 |
case KeepRouting: |
| 888 |
fp := r.unlockedInjectFlow(cm[x], receiver, p, false) |
| 889 |
receiver.InjectUDPPacket(p) |
| 890 |
fp.WasReceived() |
| 891 |
|
| 892 |
default: |
| 893 |
panic(fmt.Sprintf("Unknown exitFunc return: %v", e)) |
| 894 |
} |
| 895 |
r.Unlock() |
| 896 |
p.Release() |
| 897 |
} |
| 898 |
} |
| 899 |
|
| 900 |
// FlushAll will route for every registered controller, exiting once there are no packets left to route |
| 901 |
func (r *R) FlushAll() { |
| 902 |
sc := make([]reflect.SelectCase, len(r.controls)) |
| 903 |
cm := make([]*nebula.Control, len(r.controls)) |
| 904 |
|
| 905 |
i := 0 |
| 906 |
for _, c := range r.controls { |
| 907 |
sc[i] = reflect.SelectCase{ |
| 908 |
Dir: reflect.SelectRecv, |
| 909 |
Chan: reflect.ValueOf(c.GetUDPTxChan()), |
| 910 |
Send: reflect.Value{}, |
| 911 |
} |
| 912 |
|
| 913 |
cm[i] = c |
| 914 |
i++ |
| 915 |
} |
| 916 |
|
| 917 |
// Add a default case to exit when nothing is left to send |
| 918 |
sc = append(sc, reflect.SelectCase{ |
| 919 |
Dir: reflect.SelectDefault, |
| 920 |
Chan: reflect.Value{}, |
| 921 |
Send: reflect.Value{}, |
| 922 |
}) |
| 923 |
|
| 924 |
for { |
| 925 |
x, rx, ok := reflect.Select(sc) |
| 926 |
if !ok { |
| 927 |
return |
| 928 |
} |
| 929 |
r.Lock() |
| 930 |
|
| 931 |
p := rx.Interface().(*udp.Packet) |
| 932 |
|
| 933 |
receiver := r.getControl(cm[x].GetUDPAddr(), p.To, p) |
| 934 |
if receiver == nil { |
| 935 |
r.Unlock() |
| 936 |
panic("Can't FlushAll for host: " + p.To.String()) |
| 937 |
} |
| 938 |
receiver.InjectUDPPacket(p) |
| 939 |
r.Unlock() |
| 940 |
p.Release() |
| 941 |
} |
| 942 |
} |
| 943 |
|
| 944 |
// getControl performs or seeds NAT translation and returns the control for toAddr, p from fields may change |
| 945 |
// This is an internal router function, the caller must hold the lock |
| 946 |
func (r *R) getControl(fromAddr, toAddr netip.AddrPort, p *udp.Packet) *nebula.Control { |
| 947 |
if newAddr, ok := r.outNat[outNatKey{from: fromAddr, to: toAddr}]; ok { |
| 948 |
p.From = newAddr |
| 949 |
} |
| 950 |
|
| 951 |
c, ok := r.inNat[toAddr] |
| 952 |
if ok { |
| 953 |
r.outNat[outNatKey{from: c.GetUDPAddr(), to: fromAddr}] = toAddr |
| 954 |
return c |
| 955 |
} |
| 956 |
|
| 957 |
return r.controls[toAddr] |
| 958 |
} |
| 959 |
|
| 960 |
func (r *R) formatUdpPacket(p *packet) string { |
| 961 |
var packet gopacket.Packet |
| 962 |
var srcAddr netip.Addr |
| 963 |
|
| 964 |
packet = gopacket.NewPacket(p.packet.Data, layers.LayerTypeIPv6, gopacket.Lazy) |
| 965 |
if packet.ErrorLayer() == nil { |
| 966 |
v6 := packet.Layer(layers.LayerTypeIPv6).(*layers.IPv6) |
| 967 |
if v6 == nil { |
| 968 |
panic("not an ipv6 packet") |
| 969 |
} |
| 970 |
srcAddr, _ = netip.AddrFromSlice(v6.SrcIP) |
| 971 |
} else { |
| 972 |
packet = gopacket.NewPacket(p.packet.Data, layers.LayerTypeIPv4, gopacket.Lazy) |
| 973 |
v6 := packet.Layer(layers.LayerTypeIPv4).(*layers.IPv4) |
| 974 |
if v6 == nil { |
| 975 |
panic("not an ipv6 packet") |
| 976 |
} |
| 977 |
srcAddr, _ = netip.AddrFromSlice(v6.SrcIP) |
| 978 |
} |
| 979 |
|
| 980 |
from := "unknown" |
| 981 |
if c, ok := r.vpnControls[srcAddr]; ok { |
| 982 |
from = c.GetUDPAddr().String() |
| 983 |
} |
| 984 |
|
| 985 |
udpLayer := packet.Layer(layers.LayerTypeUDP).(*layers.UDP) |
| 986 |
if udpLayer == nil { |
| 987 |
panic("not a udp packet") |
| 988 |
} |
| 989 |
|
| 990 |
data := packet.ApplicationLayer() |
| 991 |
return fmt.Sprintf( |
| 992 |
" %s-->>%s: src port: %v<br/>dest port: %v<br/>data: \"%v\"\n", |
| 993 |
normalizeName(from), |
| 994 |
normalizeName(p.to.GetUDPAddr().String()), |
| 995 |
udpLayer.SrcPort, |
| 996 |
udpLayer.DstPort, |
| 997 |
string(data.Payload()), |
| 998 |
) |
| 999 |
} |