1
0
forked from extern/smegmesh
smegmesh/pkg/ctrlserver/ctrlserver.go

148 lines
2.7 KiB
Go
Raw Normal View History

package ctrlserver
import (
2023-09-20 00:50:44 +02:00
"errors"
"fmt"
"math/rand"
"net"
"strconv"
2023-09-19 14:45:49 +02:00
"golang.zx2c4.com/wireguard/wgctrl"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
)
/*
* Create a new control server instance running
* on the provided port.
*/
2023-09-20 00:50:44 +02:00
func NewCtrlServer(wgClient *wgctrl.Client, ifName string) *MeshCtrlServer {
ctrlServer := new(MeshCtrlServer)
2023-09-19 14:45:49 +02:00
ctrlServer.Meshes = make(map[string]Mesh)
ctrlServer.Client = wgClient
2023-09-20 00:50:44 +02:00
ctrlServer.IfName = ifName
return ctrlServer
}
/*
* Given the meshid returns true if the node is in the mesh
* false otherwise.
*/
func (server *MeshCtrlServer) IsInMesh(meshId string) bool {
_, inMesh := server.Meshes[meshId]
return inMesh
}
2023-09-19 14:45:49 +02:00
func (server *MeshCtrlServer) CreateMesh() (*Mesh, error) {
key, err := wgtypes.GenerateKey()
if err != nil {
return nil, err
}
var mesh Mesh = Mesh{
SharedKey: &key,
Nodes: make(map[string]MeshNode),
}
server.Meshes[key.String()] = mesh
return &mesh, nil
}
2023-09-20 00:50:44 +02:00
type AddHostArgs struct {
HostEndpoint string
PublicKey string
MeshId string
WgEndpoint string
}
func (server *MeshCtrlServer) AddHost(args AddHostArgs) error {
nodes, contains := server.Meshes[args.MeshId]
if !contains {
return errors.New("Node does not exist in the mesh")
}
_, contains = nodes.Nodes[args.HostEndpoint]
if contains {
return errors.New("The node already has an endpoint in the mesh network")
}
fmt.Println(args.WgEndpoint)
node := MeshNode{
HostEndpoint: args.HostEndpoint,
WgEndpoint: args.WgEndpoint,
PublicKey: args.PublicKey,
WgHost: "10.0.0." + strconv.Itoa(rand.Intn(253)+1) + "/32",
}
err := addWgPeer(server.IfName, server.Client, node)
if err == nil {
nodes.Nodes[args.MeshId] = node
} else {
fmt.Println(err.Error())
}
return err
}
func (server *MeshCtrlServer) GetDevice() *wgtypes.Device {
dev, err := server.Client.Device(server.IfName)
if err != nil {
return nil
}
return dev
}
func addWgPeer(ifName string, client *wgctrl.Client, node MeshNode) error {
peer := make([]wgtypes.PeerConfig, 1)
peerPublic, err := wgtypes.ParseKey(node.PublicKey)
if err != nil {
return err
}
peerEndpoint, err := net.ResolveUDPAddr("udp", node.WgEndpoint)
if err != nil {
fmt.Println("err")
return err
}
allowedIps := make([]net.IPNet, 1)
_, ipnet, err := net.ParseCIDR(node.WgHost)
if err != nil {
return err
}
allowedIps[0] = *ipnet
peer[0] = wgtypes.PeerConfig{
PublicKey: peerPublic,
Endpoint: peerEndpoint,
AllowedIPs: allowedIps,
}
cfg := wgtypes.Config{
Peers: peer,
}
err = client.ConfigureDevice(ifName, cfg)
dev, _ := client.Device(ifName)
fmt.Println(dev.Peers[0].Endpoint)
if err != nil {
return err
}
return nil
}