-
Notifications
You must be signed in to change notification settings - Fork 6
/
devicemanager_linux.go
88 lines (80 loc) · 2.12 KB
/
devicemanager_linux.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// +build linux
package main
import (
"os"
"regexp"
"github.com/vishvananda/netlink"
)
// updateDeviceConfig takes the old WirestewardPeerConfig (optionally) and the
// desired, new config and performs the necessary operations to setup the IP
// address and routing table routes. If an "old" config is provided, it will
// attempt to clean up any system configuration before applying the new one.
func (dm *DeviceManager) updateDeviceConfig(oldConfig, config *WirestewardPeerConfig) error {
h := netlink.Handle{}
defer h.Delete()
link, err := h.LinkByName(dm.Name())
if err != nil {
return err
}
if oldConfig != nil {
for _, r := range oldConfig.AllowedIPs {
if h.RouteDel(&netlink.Route{LinkIndex: link.Attrs().Index, Dst: &r}); err != nil {
logger.Errorf(
"Could not remove old route (%s): %s",
r,
err,
)
}
}
if err := h.AddrDel(link, &netlink.Addr{IPNet: oldConfig.LocalAddress}); err != nil {
logger.Errorf(
"Could not remove old address (%s): %s",
oldConfig.LocalAddress,
err,
)
}
}
if err := h.AddrAdd(link, &netlink.Addr{IPNet: config.LocalAddress}); err != nil {
return err
}
for _, r := range config.AllowedIPs {
if err := h.RouteReplace(&netlink.Route{LinkIndex: link.Attrs().Index, Dst: &r, Gw: config.LocalAddress.IP}); err != nil {
logger.Errorf(
"Could not add new route (%s): %s", r, err)
}
}
return nil
}
// TODO: confirm that this is still needed for linux after the switch to tun.
func (dm *DeviceManager) ensureLinkUp() error {
h := netlink.Handle{}
defer h.Delete()
link, err := h.LinkByName(dm.Name())
if err != nil {
return err
}
return h.LinkSetUp(link)
}
func (dm *DeviceManager) flushAddresses() error {
h := netlink.Handle{}
defer h.Delete()
link, err := h.LinkByName(dm.Name())
if err != nil {
return err
}
ips, err := h.AddrList(link, 2)
for _, ip := range ips {
if err := h.AddrDel(link, &ip); err != nil {
return err
}
}
return nil
}
func wgDevTypeSupported() bool {
wgModule := regexp.MustCompile(`(^|\n)wireguard .+`)
m, err := os.ReadFile("/proc/modules")
if err != nil {
panic(err)
}
return wgModule.Match(m)
}