Update 'devices.go'

This commit is contained in:
Kekskurse 2021-05-16 14:41:17 +00:00
parent 7b4efbc697
commit b0ba5a7563

View file

@ -12,6 +12,7 @@ type Device struct {
PublicKey string PublicKey string
PrivateKey string PrivateKey string
ListenPort int ListenPort int
IP netlink.Addr
} }
func DevicesList() ([]Device, error) { func DevicesList() ([]Device, error) {
@ -40,10 +41,66 @@ func DevicesList() ([]Device, error) {
return devList, nil return devList, nil
} }
func DevicesCreate(device Device) (error) { func DevicesCreate(name string, ip netlink.Addr, privateKey string, listenPort int) (error) {
// Create IP Device // Create IP Device
la := netlink.NewLinkAttrs() la := netlink.NewLinkAttrs()
la.Name = device.Name la.Name = name
wgDev := &netlink.GenericLink{
LinkAttrs: la,
LinkType: "wireguard",
}
err := netlink.LinkAdd(wgDev)
if err != nil {
return fmt.Errorf("Cant create Link to Device: %w", err)
}
err = netlink.AddrAdd(wgDev, &ip)
if err != nil {
return fmt.Errorf("Cant add ip to device: %w", err)
}
privkey, err := wgtypes.ParseKey(privateKey)
if err != nil {
return fmt.Errorf("Cant parse private key: %w", err)
}
config := wgtypes.Config{
PrivateKey: &privkey,
ListenPort: &listenPort,
FirewallMark: nil,
ReplacePeers: false,
Peers: nil,
}
client, err := wgctrl.New()
if err != nil {
return fmt.Errorf("Cant create wireguard client: %w", err)
}
client.ConfigureDevice(name, config)
err = netlink.LinkSetUp(wgDev)
if err != nil {
return fmt.Errorf("Cant start device: %w", err)
}
return nil
}
func DeviceDelete(name string) (error) {
la := netlink.NewLinkAttrs()
la.Name = name
dev := &netlink.GenericLink{
LinkAttrs: la,
LinkType: "wireguard",
}
err := netlink.LinkDel(dev)
if err != nil {
return fmt.Errorf("Cant delete Device: %w", err)
}
return nil return nil
} }