netmaker/netclient/local/routes_linux.go

75 lines
2.2 KiB
Go
Raw Normal View History

2022-02-03 09:46:25 +08:00
package local
import (
//"github.com/davecgh/go-spew/spew"
2022-02-03 11:00:59 +08:00
"fmt"
2022-02-03 09:46:25 +08:00
"net"
2022-02-06 03:26:19 +08:00
"strings"
2022-02-03 09:46:25 +08:00
2022-05-27 05:39:18 +08:00
"github.com/c-robinson/iplib"
2022-04-20 04:18:03 +08:00
"github.com/gravitl/netmaker/logger"
2022-02-03 09:46:25 +08:00
"github.com/gravitl/netmaker/netclient/ncutils"
)
2022-08-23 04:44:04 +08:00
// GetDefaultRoute - Gets the default route (ip and interface) on a linux machine
func GetDefaultRoute() (string, string, error) {
var ipaddr string
var iface string
var err error
output, err := ncutils.RunCmd("ip route show default", false)
if err != nil {
return ipaddr, iface, err
}
outputSlice := strings.Split(output, " ")
if !strings.Contains(outputSlice[0], "default") {
return ipaddr, iface, fmt.Errorf("could not find default gateway")
}
for i, outString := range outputSlice {
if outString == "via" {
ipaddr = outputSlice[i+1]
}
if outString == "dev" {
iface = outputSlice[i+1]
}
}
return ipaddr, iface, err
}
2022-02-04 08:55:12 +08:00
func setRoute(iface string, addr *net.IPNet, address string) error {
2022-02-06 03:26:19 +08:00
out, err := ncutils.RunCmd(fmt.Sprintf("ip route get %s", addr.IP.String()), false)
if err != nil || !strings.Contains(out, iface) {
2022-02-06 04:38:50 +08:00
_, err = ncutils.RunCmd(fmt.Sprintf("ip route add %s dev %s", addr.String(), iface), false)
2022-02-06 03:26:19 +08:00
}
2022-02-03 09:46:25 +08:00
return err
}
2022-08-24 03:58:02 +08:00
// SetExplicitRoute - sets route via explicit ip address
func SetExplicitRoute(iface string, destination *net.IPNet, gateway string) error {
_, err := ncutils.RunCmd(fmt.Sprintf("ip route add %s via %s dev %s", destination.String(), gateway, iface), false)
return err
}
2022-02-04 08:55:12 +08:00
func deleteRoute(iface string, addr *net.IPNet, address string) error {
2022-02-03 09:46:25 +08:00
var err error
2022-02-06 03:26:19 +08:00
out, _ := ncutils.RunCmd(fmt.Sprintf("ip route get %s", addr.IP.String()), false)
if strings.Contains(out, iface) {
_, err = ncutils.RunCmd(fmt.Sprintf("ip route del %s dev %s", addr.String(), iface), false)
}
2022-02-03 09:46:25 +08:00
return err
}
func setCidr(iface, address string, addr *net.IPNet) {
2022-05-27 05:39:18 +08:00
if iplib.Version(addr.IP) == 4 {
2022-04-20 04:18:03 +08:00
ncutils.RunCmd("ip -4 route add "+addr.String()+" dev "+iface, false)
2022-05-27 05:39:18 +08:00
} else if iplib.Version(addr.IP) == 6 {
2022-04-20 04:18:03 +08:00
ncutils.RunCmd("ip -6 route add "+addr.String()+" dev "+iface, false)
} else {
logger.Log(1, "could not parse address: "+addr.String())
}
}
2022-02-06 04:00:26 +08:00
func removeCidr(iface string, addr *net.IPNet, address string) {
ncutils.RunCmd("ip route delete "+addr.String()+" dev "+iface, false)
}