crip/ripv2/routes.go

73 lines
1.4 KiB
Go
Raw Normal View History

2024-04-16 12:55:08 +01:00
package ripv2
2024-04-10 16:33:33 +01:00
import (
2024-04-10 20:42:12 +01:00
"crypto/sha256"
"fmt"
2024-04-10 16:33:33 +01:00
"net"
2024-04-11 21:15:36 +01:00
"sync"
2024-04-10 16:33:33 +01:00
"time"
)
2024-04-11 21:15:36 +01:00
type Routes struct {
Routes map[string]Route
sync.Mutex
}
2024-04-10 16:33:33 +01:00
type Route struct {
Addr net.IP
2024-04-15 11:26:37 +01:00
FIB bool
2024-04-10 16:33:33 +01:00
Subnet net.IPMask
Nexthop net.IP
Metric uint32
TTL time.Time
}
2024-04-16 12:55:08 +01:00
func Init() *Routes {
2024-04-11 21:15:36 +01:00
var routes Routes
routes.Routes = make(map[string]Route, 25)
return &routes
2024-04-10 16:33:33 +01:00
}
func (r *Routes) append(route Route) {
2024-04-10 20:42:12 +01:00
key := route.Addr.String() + route.Subnet.String() + route.Nexthop.String() + fmt.Sprintf("%d", route.Metric)
h := sha256.New()
h.Write([]byte(key))
bs := h.Sum(nil)
2024-04-11 21:15:36 +01:00
r.Lock()
defer r.Unlock()
k, ok := r.Routes[string(bs)]
2024-04-10 20:42:12 +01:00
if !ok {
2024-04-11 21:15:36 +01:00
r.Routes[string(bs)] = route
2024-04-10 20:42:12 +01:00
return
}
k.TTL = time.Now()
2024-04-11 21:15:36 +01:00
r.Routes[string(bs)] = k
2024-04-10 16:33:33 +01:00
}
2024-04-16 12:55:08 +01:00
func (r *Routes) ParseRoutes(addr net.UDPAddr, rip *[]RIP) {
2024-04-10 16:33:33 +01:00
var route Route
for _, rip := range *rip {
/* if not af_inet */
if rip.AFI != 2 {
continue
}
if rip.Addr == 0 || rip.Subnet == 0 {
continue
}
route = Route{}
route.Addr = net.IPv4(byte(rip.Addr>>24), byte(rip.Addr>>16), byte(rip.Addr>>8), byte(rip.Addr))
route.Subnet = net.IPv4Mask(byte(rip.Subnet>>24), byte(rip.Subnet>>16), byte(rip.Subnet>>8), byte(rip.Subnet))
if rip.Nexthop == 0 {
route.Nexthop = addr.IP
} else {
route.Nexthop = net.IPv4(byte(rip.Nexthop>>24), byte(rip.Nexthop>>16), byte(rip.Nexthop>>8), byte(rip.Nexthop))
}
route.Metric = rip.Metric
route.TTL = time.Now()
r.append(route)
}
}