2020-04-12 08:55:13 -04:00
|
|
|
package routing
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"fmt"
|
2020-10-20 02:45:28 +00:00
|
|
|
"net"
|
2020-10-22 18:55:28 -04:00
|
|
|
|
|
|
|
|
"github.com/vishvananda/netlink"
|
2020-04-12 08:55:13 -04:00
|
|
|
)
|
|
|
|
|
|
2020-10-22 18:55:28 -04:00
|
|
|
func (r *routing) AddRouteVia(destination net.IPNet, gateway net.IP, iface string) error {
|
|
|
|
|
destinationStr := destination.String()
|
|
|
|
|
r.logger.Info("adding route for %s", destinationStr)
|
2020-07-13 02:14:56 +00:00
|
|
|
if r.debug {
|
2020-10-22 18:55:28 -04:00
|
|
|
fmt.Printf("ip route add %s via %s dev %s\n", destinationStr, gateway, iface)
|
2020-07-13 02:14:56 +00:00
|
|
|
}
|
2020-10-22 18:55:28 -04:00
|
|
|
|
|
|
|
|
link, err := netlink.LinkByName(iface)
|
2020-07-11 21:03:55 +00:00
|
|
|
if err != nil {
|
2020-10-22 18:55:28 -04:00
|
|
|
return fmt.Errorf("cannot add route for %s: %w", destinationStr, err)
|
|
|
|
|
}
|
|
|
|
|
route := netlink.Route{
|
|
|
|
|
Dst: &destination,
|
|
|
|
|
Gw: gateway,
|
|
|
|
|
LinkIndex: link.Attrs().Index,
|
|
|
|
|
}
|
|
|
|
|
if err := netlink.RouteReplace(&route); err != nil {
|
|
|
|
|
return fmt.Errorf("cannot add route for %s: %w", destinationStr, err)
|
2020-04-12 08:55:13 -04:00
|
|
|
}
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
2020-10-22 18:55:28 -04:00
|
|
|
func (r *routing) DeleteRouteVia(destination net.IPNet) (err error) {
|
|
|
|
|
destinationStr := destination.String()
|
|
|
|
|
r.logger.Info("deleting route for %s", destinationStr)
|
2020-07-13 02:14:56 +00:00
|
|
|
if r.debug {
|
2020-10-22 18:55:28 -04:00
|
|
|
fmt.Printf("ip route del %s\n", destinationStr)
|
2020-07-13 02:14:56 +00:00
|
|
|
}
|
2020-10-22 18:55:28 -04:00
|
|
|
route := netlink.Route{
|
|
|
|
|
Dst: &destination,
|
|
|
|
|
}
|
|
|
|
|
if err := netlink.RouteDel(&route); err != nil {
|
|
|
|
|
return fmt.Errorf("cannot delete route for %s: %w", destinationStr, err)
|
2020-04-12 08:55:13 -04:00
|
|
|
}
|
|
|
|
|
return nil
|
|
|
|
|
}
|