crip/ripv2/routes/routes.go
Jim Colderwood 9d18b81f81 Route timer
2024-04-11 21:15:36 +01:00

74 lines
1.4 KiB
Go

package routes
import (
"crypto/sha256"
"fmt"
"net"
"sync"
"time"
"github.com/crip/ripv2"
)
type Routes struct {
Routes map[string]Route
sync.Mutex
}
type Route struct {
Addr net.IP
Subnet net.IPMask
Nexthop net.IP
Metric uint32
TTL time.Time
}
func New() *Routes {
var routes Routes
routes.Routes = make(map[string]Route, 25)
return &routes
}
func (r *Routes) append(route Route) {
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)
r.Lock()
defer r.Unlock()
k, ok := r.Routes[string(bs)]
if !ok {
r.Routes[string(bs)] = route
return
}
k.TTL = time.Now()
r.Routes[string(bs)] = k
}
func (r *Routes) ParseRoutes(addr net.UDPAddr, rip *[25]ripv2.RIP) {
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)
}
}