73 lines
1.4 KiB
Go
73 lines
1.4 KiB
Go
package ripv2
|
|
|
|
import (
|
|
"crypto/sha256"
|
|
"fmt"
|
|
"net"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
type Routes struct {
|
|
Routes map[string]Route
|
|
sync.Mutex
|
|
}
|
|
|
|
type Route struct {
|
|
Addr net.IP
|
|
FIB bool
|
|
Subnet net.IPMask
|
|
Nexthop net.IP
|
|
Metric uint32
|
|
TTL time.Time
|
|
}
|
|
|
|
func Init() *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 *[]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)
|
|
}
|
|
}
|