hvpn-node3/link.go
HeshamTB 1a611616bd
init:
- Working basic wg controls
    - Working ip_pool allocation
    - Working basic HTTP API

Signed-off-by: HeshamTB <hishaminv@gmail.com>
2024-03-11 17:34:06 +03:00

78 lines
1.5 KiB
Go

package hvpnnode3
import (
"errors"
"github.com/vishvananda/netlink"
"golang.zx2c4.com/wireguard/wgctrl"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
)
type WGLink struct {
*netlink.LinkAttrs
*wgctrl.Client
}
// Retruns an existing or create a WGLink
func InitWGLink(ifName string, privateKey *wgtypes.Key, port int) (*WGLink, error){
attrs := netlink.NewLinkAttrs()
attrs.Name = ifName
wg := WGLink{LinkAttrs: &attrs}
link, err := netlink.LinkByName(ifName)
if err != nil {
switch err.(type) {
case netlink.LinkNotFoundError:
if err := netlink.LinkAdd(&wg); err != nil {
return nil, err
}
default:
return nil, err
}
} else {
wg.LinkAttrs = link.Attrs()
}
err = wg.initClient()
if err != nil {
return nil, err
}
err = wg.ConfigureDevice(
ifName,
wgtypes.Config{
PrivateKey: privateKey,
ListenPort: &port,
},
)
if err != nil {
return nil, err
}
return &wg, netlink.LinkSetUp(&wg)
}
func (WGLink) Type() string {
return "wireguard"
}
func (wg *WGLink) Attrs() *netlink.LinkAttrs {
return wg.LinkAttrs
}
func (wg *WGLink) Close() error {
return netlink.LinkDel(wg)
}
func (wg *WGLink) initClient() error {
client, err := wgctrl.New()
if client == nil {
return errors.New("Could not initialize new Wireguard Client")
}
wg.Client = client
return err
}