Debian Codegraph @

vnet/router.go

raw symbols SCIP
1 package vnet
2
3 import (
4 "errors"
5 "fmt"
6 "math/rand"
7 "net"
8 "strings"
9 "sync"
10 "sync/atomic"
11 "time"
12
13 "github.com/pion/logging"
14 "github.com/pion/transport/v2"
15 )
16
17 const (
18 defaultRouterQueueSize = 0 // unlimited
19 )
20
21 var (
22 errInvalidLocalIPinStaticIPs = errors.New("invalid local IP in StaticIPs")
23 errLocalIPBeyondStaticIPsSubset = errors.New("mapped in StaticIPs is beyond subnet")
24 errLocalIPNoStaticsIPsAssociated = errors.New("all StaticIPs must have associated local IPs")
25 errRouterAlreadyStarted = errors.New("router already started")
26 errRouterAlreadyStopped = errors.New("router already stopped")
27 errStaticIPisBeyondSubnet = errors.New("static IP is beyond subnet")
28 errAddressSpaceExhausted = errors.New("address space exhausted")
29 errNoIPAddrEth0 = errors.New("no IP address is assigned for eth0")
30 )
31
32 // Generate a unique router name
33 var assignRouterName = func() func() string { //nolint:gochecknoglobals
34 var routerIDCtr uint64
35
36 return func() string {
37 n := atomic.AddUint64(&routerIDCtr, 1)
38 return fmt.Sprintf("router%d", n)
39 }
40 }()
41
42 // RouterConfig ...
43 type RouterConfig struct {
44 // Name of router. If not specified, a unique name will be assigned.
45 Name string
46 // CIDR notation, like "192.0.2.0/24"
47 CIDR string
48 // StaticIPs is an array of static IP addresses to be assigned for this router.
49 // If no static IP address is given, the router will automatically assign
50 // an IP address.
51 // This will be ignored if this router is the root.
52 StaticIPs []string
53 // StaticIP is deprecated. Use StaticIPs.
54 StaticIP string
55 // Internal queue size
56 QueueSize int
57 // Effective only when this router has a parent router
58 NATType *NATType
59 // Minimum Delay
60 MinDelay time.Duration
61 // Max Jitter
62 MaxJitter time.Duration
63 // Logger factory
64 LoggerFactory logging.LoggerFactory
65 }
66
67 // NIC is a network interface controller that interfaces Router
68 type NIC interface {
69 getInterface(ifName string) (*transport.Interface, error)
70 onInboundChunk(c Chunk)
71 getStaticIPs() []net.IP
72 setRouter(r *Router) error
73 }
74
75 // ChunkFilter is a handler users can add to filter chunks.
76 // If the filter returns false, the packet will be dropped.
77 type ChunkFilter func(c Chunk) bool
78
79 // Router ...
80 type Router struct {
81 name string // read-only
82 interfaces []*transport.Interface // read-only
83 ipv4Net *net.IPNet // read-only
84 staticIPs []net.IP // read-only
85 staticLocalIPs map[string]net.IP // read-only,
86 lastID byte // requires mutex [x], used to assign the last digit of IPv4 address
87 queue *chunkQueue // read-only
88 parent *Router // read-only
89 children []*Router // read-only
90 natType *NATType // read-only
91 nat *networkAddressTranslator // read-only
92 nics map[string]NIC // read-only
93 stopFunc func() // requires mutex [x]
94 resolver *resolver // read-only
95 chunkFilters []ChunkFilter // requires mutex [x]
96 minDelay time.Duration // requires mutex [x]
97 maxJitter time.Duration // requires mutex [x]
98 mutex sync.RWMutex // thread-safe
99 pushCh chan struct{} // writer requires mutex
100 loggerFactory logging.LoggerFactory // read-only
101 log logging.LeveledLogger // read-only
102 }
103
104 // NewRouter ...
105 func NewRouter(config *RouterConfig) (*Router, error) {
106 loggerFactory := config.LoggerFactory
107 log := loggerFactory.NewLogger("vnet")
108
109 _, ipv4Net, err := net.ParseCIDR(config.CIDR)
110 if err != nil {
111 return nil, err
112 }
113
114 queueSize := defaultRouterQueueSize
115 if config.QueueSize > 0 {
116 queueSize = config.QueueSize
117 }
118
119 // set up network interface, lo0
120 lo0 := transport.NewInterface(net.Interface{
121 Index: 1,
122 MTU: 16384,
123 Name: lo0String,
124 HardwareAddr: nil,
125 Flags: net.FlagUp | net.FlagLoopback | net.FlagMulticast,
126 })
127 lo0.AddAddress(&net.IPAddr{IP: net.ParseIP("127.0.0.1"), Zone: ""})
128
129 // set up network interface, eth0
130 eth0 := transport.NewInterface(net.Interface{
131 Index: 2,
132 MTU: 1500,
133 Name: "eth0",
134 HardwareAddr: newMACAddress(),
135 Flags: net.FlagUp | net.FlagMulticast,
136 })
137
138 // local host name resolver
139 resolver := newResolver(&resolverConfig{
140 LoggerFactory: config.LoggerFactory,
141 })
142
143 name := config.Name
144 if len(name) == 0 {
145 name = assignRouterName()
146 }
147
148 var staticIPs []net.IP
149 staticLocalIPs := map[string]net.IP{}
150 for _, ipStr := range config.StaticIPs {
151 ipPair := strings.Split(ipStr, "/")
152 if ip := net.ParseIP(ipPair[0]); ip != nil {
153 if len(ipPair) > 1 {
154 locIP := net.ParseIP(ipPair[1])
155 if locIP == nil {
156 return nil, errInvalidLocalIPinStaticIPs
157 }
158 if !ipv4Net.Contains(locIP) {
159 return nil, fmt.Errorf("local IP %s %w", locIP.String(), errLocalIPBeyondStaticIPsSubset)
160 }
161 staticLocalIPs[ip.String()] = locIP
162 }
163 staticIPs = append(staticIPs, ip)
164 }
165 }
166 if len(config.StaticIP) > 0 {
167 log.Warn("StaticIP is deprecated. Use StaticIPs instead")
168 if ip := net.ParseIP(config.StaticIP); ip != nil {
169 staticIPs = append(staticIPs, ip)
170 }
171 }
172
173 if nStaticLocal := len(staticLocalIPs); nStaticLocal > 0 {
174 if nStaticLocal != len(staticIPs) {
175 return nil, errLocalIPNoStaticsIPsAssociated
176 }
177 }
178
179 return &Router{
180 name: name,
181 interfaces: []*transport.Interface{lo0, eth0},
182 ipv4Net: ipv4Net,
183 staticIPs: staticIPs,
184 staticLocalIPs: staticLocalIPs,
185 queue: newChunkQueue(queueSize, 0),
186 natType: config.NATType,
187 nics: map[string]NIC{},
188 resolver: resolver,
189 minDelay: config.MinDelay,
190 maxJitter: config.MaxJitter,
191 pushCh: make(chan struct{}, 1),
192 loggerFactory: loggerFactory,
193 log: log,
194 }, nil
195 }
196
197 // caller must hold the mutex
198 func (r *Router) getInterfaces() ([]*transport.Interface, error) {
199 if len(r.interfaces) == 0 {
200 return nil, fmt.Errorf("%w is available", errNoInterface)
201 }
202
203 return r.interfaces, nil
204 }
205
206 func (r *Router) getInterface(ifName string) (*transport.Interface, error) {
207 r.mutex.RLock()
208 defer r.mutex.RUnlock()
209
210 ifs, err := r.getInterfaces()
211 if err != nil {
212 return nil, err
213 }
214 for _, ifc := range ifs {
215 if ifc.Name == ifName {
216 return ifc, nil
217 }
218 }
219
220 return nil, fmt.Errorf("%w: %s", transport.ErrInterfaceNotFound, ifName)
221 }
222
223 // Start ...
224 func (r *Router) Start() error {
225 r.mutex.Lock()
226 defer r.mutex.Unlock()
227
228 if r.stopFunc != nil {
229 return errRouterAlreadyStarted
230 }
231
232 cancelCh := make(chan struct{})
233
234 go func() {
235 loop:
236 for {
237 d, err := r.processChunks()
238 if err != nil {
239 r.log.Errorf("[%s] %s", r.name, err.Error())
240 break
241 }
242
243 if d <= 0 {
244 select {
245 case <-r.pushCh:
246 case <-cancelCh:
247 break loop
248 }
249 } else {
250 t := time.NewTimer(d)
251 select {
252 case <-t.C:
253 case <-cancelCh:
254 break loop
255 }
256 }
257 }
258 }()
259
260 r.stopFunc = func() {
261 close(cancelCh)
262 }
263
264 for _, child := range r.children {
265 if err := child.Start(); err != nil {
266 return err
267 }
268 }
269
270 return nil
271 }
272
273 // Stop ...
274 func (r *Router) Stop() error {
275 r.mutex.Lock()
276 defer r.mutex.Unlock()
277
278 if r.stopFunc == nil {
279 return errRouterAlreadyStopped
280 }
281
282 for _, router := range r.children {
283 r.mutex.Unlock()
284 err := router.Stop()
285 r.mutex.Lock()
286
287 if err != nil {
288 return err
289 }
290 }
291
292 r.stopFunc()
293 r.stopFunc = nil
294 return nil
295 }
296
297 // caller must hold the mutex
298 func (r *Router) addNIC(nic NIC) error {
299 ifc, err := nic.getInterface("eth0")
300 if err != nil {
301 return err
302 }
303
304 var ips []net.IP
305
306 if ips = nic.getStaticIPs(); len(ips) == 0 {
307 // assign an IP address
308 ip, err2 := r.assignIPAddress()
309 if err2 != nil {
310 return err2
311 }
312 ips = append(ips, ip)
313 }
314
315 for _, ip := range ips {
316 if !r.ipv4Net.Contains(ip) {
317 return fmt.Errorf("%w: %s", errStaticIPisBeyondSubnet, r.ipv4Net.String())
318 }
319
320 ifc.AddAddress(&net.IPNet{
321 IP: ip,
322 Mask: r.ipv4Net.Mask,
323 })
324
325 r.nics[ip.String()] = nic
326 }
327
328 if err = nic.setRouter(r); err != nil {
329 return err
330 }
331
332 return nil
333 }
334
335 // AddRouter adds a child Router.
336 func (r *Router) AddRouter(router *Router) error {
337 r.mutex.Lock()
338 defer r.mutex.Unlock()
339
340 // Router is a NIC. Add it as a NIC so that packets are routed to this child
341 // router.
342 err := r.addNIC(router)
343 if err != nil {
344 return err
345 }
346
347 if err = router.setRouter(r); err != nil {
348 return err
349 }
350
351 r.children = append(r.children, router)
352 return nil
353 }
354
355 // AddChildRouter is like AddRouter, but does not add the child routers NIC to
356 // the parent. This has to be done manually by calling AddNet, which allows to
357 // use a wrapper around the subrouters NIC.
358 // AddNet MUST be called before AddChildRouter.
359 func (r *Router) AddChildRouter(router *Router) error {
360 r.mutex.Lock()
361 defer r.mutex.Unlock()
362 if err := router.setRouter(r); err != nil {
363 return err
364 }
365
366 r.children = append(r.children, router)
367 return nil
368 }
369
370 // AddNet ...
371 func (r *Router) AddNet(nic NIC) error {
372 r.mutex.Lock()
373 defer r.mutex.Unlock()
374
375 return r.addNIC(nic)
376 }
377
378 // AddHost adds a mapping of hostname and an IP address to the local resolver.
379 func (r *Router) AddHost(hostName string, ipAddr string) error {
380 return r.resolver.addHost(hostName, ipAddr)
381 }
382
383 // AddChunkFilter adds a filter for chunks traversing this router.
384 // You may add more than one filter. The filters are called in the order of this method call.
385 // If a chunk is dropped by a filter, subsequent filter will not receive the chunk.
386 func (r *Router) AddChunkFilter(filter ChunkFilter) {
387 r.mutex.Lock()
388 defer r.mutex.Unlock()
389
390 r.chunkFilters = append(r.chunkFilters, filter)
391 }
392
393 // caller should hold the mutex
394 func (r *Router) assignIPAddress() (net.IP, error) {
395 // See: https://stackoverflow.com/questions/14915188/ip-address-ending-with-zero
396
397 if r.lastID == 0xfe {
398 return nil, errAddressSpaceExhausted
399 }
400
401 ip := make(net.IP, 4)
402 copy(ip, r.ipv4Net.IP[:3])
403 r.lastID++
404 ip[3] = r.lastID
405 return ip, nil
406 }
407
408 func (r *Router) push(c Chunk) {
409 r.mutex.Lock()
410 defer r.mutex.Unlock()
411
412 r.log.Debugf("[%s] route %s", r.name, c.String())
413 if r.stopFunc != nil {
414 c.setTimestamp()
415 if r.queue.push(c) {
416 select {
417 case r.pushCh <- struct{}{}:
418 default:
419 }
420 } else {
421 r.log.Warnf("[%s] queue was full. dropped a chunk", r.name)
422 }
423 }
424 }
425
426 func (r *Router) processChunks() (time.Duration, error) {
427 r.mutex.Lock()
428 defer r.mutex.Unlock()
429
430 // Introduce jitter by delaying the processing of chunks.
431 if r.maxJitter > 0 {
432 jitter := time.Duration(rand.Int63n(int64(r.maxJitter))) //nolint:gosec
433 time.Sleep(jitter)
434 }
435
436 // cutOff
437 // v min delay
438 // |<--->|
439 // +------------:--
440 // |OOOOOOXXXXX : --> time
441 // +------------:--
442 // |<--->| now
443 // due
444
445 enteredAt := time.Now()
446 cutOff := enteredAt.Add(-r.minDelay)
447
448 var d time.Duration // the next sleep duration
449
450 for {
451 d = 0
452
453 c := r.queue.peek()
454 if c == nil {
455 break // no more chunk in the queue
456 }
457
458 // check timestamp to find if the chunk is due
459 if c.getTimestamp().After(cutOff) {
460 // There is one or more chunk in the queue but none of them are due.
461 // Calculate the next sleep duration here.
462 nextExpire := c.getTimestamp().Add(r.minDelay)
463 d = nextExpire.Sub(enteredAt)
464 break
465 }
466
467 var ok bool
468 if c, ok = r.queue.pop(); !ok {
469 break // no more chunk in the queue
470 }
471
472 blocked := false
473 for i := 0; i < len(r.chunkFilters); i++ {
474 filter := r.chunkFilters[i]
475 if !filter(c) {
476 blocked = true
477 break
478 }
479 }
480 if blocked {
481 continue // discard
482 }
483
484 dstIP := c.getDestinationIP()
485
486 // check if the destination is in our subnet
487 if r.ipv4Net.Contains(dstIP) {
488 // search for the destination NIC
489 var nic NIC
490 if nic, ok = r.nics[dstIP.String()]; !ok {
491 // NIC not found. drop it.
492 r.log.Debugf("[%s] %s unreachable", r.name, c.String())
493 continue
494 }
495
496 // found the NIC, forward the chunk to the NIC.
497 // call to NIC must unlock mutex
498 r.mutex.Unlock()
499 nic.onInboundChunk(c)
500 r.mutex.Lock()
501 continue
502 }
503
504 // the destination is outside of this subnet
505 // is this WAN?
506 if r.parent == nil {
507 // this WAN. No route for this chunk
508 r.log.Debugf("[%s] no route found for %s", r.name, c.String())
509 continue
510 }
511
512 // Pass it to the parent via NAT
513 toParent, err := r.nat.translateOutbound(c)
514 if err != nil {
515 return 0, err
516 }
517
518 if toParent == nil {
519 continue
520 }
521
522 //nolint:godox
523 /* FIXME: this implementation would introduce a duplicate packet!
524 if r.nat.natType.Hairpinning {
525 hairpinned, err := r.nat.translateInbound(toParent)
526 if err != nil {
527 r.log.Warnf("[%s] %s", r.name, err.Error())
528 } else {
529 go func() {
530 r.push(hairpinned)
531 }()
532 }
533 }
534 */
535
536 // call to parent router mutex unlock mutex
537 r.mutex.Unlock()
538 r.parent.push(toParent)
539 r.mutex.Lock()
540 }
541
542 return d, nil
543 }
544
545 // caller must hold the mutex
546 func (r *Router) setRouter(parent *Router) error {
547 r.parent = parent
548 r.resolver.setParent(parent.resolver)
549
550 // when this method is called, one or more IP address has already been assigned by
551 // the parent router.
552 ifc, err := r.getInterface("eth0")
553 if err != nil {
554 return err
555 }
556
557 addrs, _ := ifc.Addrs()
558 if len(addrs) == 0 {
559 return errNoIPAddrEth0
560 }
561
562 mappedIPs := []net.IP{}
563 localIPs := []net.IP{}
564
565 for _, ifcAddr := range addrs {
566 var ip net.IP
567 switch addr := ifcAddr.(type) {
568 case *net.IPNet:
569 ip = addr.IP
570 case *net.IPAddr: // Do we really need this case?
571 ip = addr.IP
572 default:
573 }
574
575 if ip == nil {
576 continue
577 }
578
579 mappedIPs = append(mappedIPs, ip)
580
581 if locIP := r.staticLocalIPs[ip.String()]; locIP != nil {
582 localIPs = append(localIPs, locIP)
583 }
584 }
585
586 // Set up NAT here
587 if r.natType == nil {
588 r.natType = &NATType{
589 MappingBehavior: EndpointIndependent,
590 FilteringBehavior: EndpointAddrPortDependent,
591 Hairpinning: false,
592 PortPreservation: false,
593 MappingLifeTime: 30 * time.Second,
594 }
595 }
596 r.nat, err = newNAT(&natConfig{
597 name: r.name,
598 natType: *r.natType,
599 mappedIPs: mappedIPs,
600 localIPs: localIPs,
601 loggerFactory: r.loggerFactory,
602 })
603 if err != nil {
604 return err
605 }
606
607 return nil
608 }
609
610 func (r *Router) onInboundChunk(c Chunk) {
611 fromParent, err := r.nat.translateInbound(c)
612 if err != nil {
613 r.log.Warnf("[%s] %s", r.name, err.Error())
614 return
615 }
616
617 r.push(fromParent)
618 }
619
620 func (r *Router) getStaticIPs() []net.IP {
621 return r.staticIPs
622 }