2023-09-18 16:52:28 +02:00
|
|
|
package ctrlserver
|
|
|
|
|
|
|
|
import (
|
|
|
|
"strconv"
|
|
|
|
|
|
|
|
"github.com/gin-gonic/gin"
|
2023-09-19 14:45:49 +02:00
|
|
|
"golang.zx2c4.com/wireguard/wgctrl"
|
|
|
|
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
|
2023-09-18 16:52:28 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
/*
|
|
|
|
* Create a new control server instance running
|
|
|
|
* on the provided port.
|
|
|
|
*/
|
2023-09-19 14:45:49 +02:00
|
|
|
func NewCtrlServer(host string, port int, wgClient *wgctrl.Client) *MeshCtrlServer {
|
2023-09-18 16:52:28 +02:00
|
|
|
ctrlServer := new(MeshCtrlServer)
|
|
|
|
ctrlServer.Port = port
|
2023-09-19 14:45:49 +02:00
|
|
|
ctrlServer.Meshes = make(map[string]Mesh)
|
2023-09-18 16:52:28 +02:00
|
|
|
ctrlServer.Host = host
|
2023-09-19 14:45:49 +02:00
|
|
|
ctrlServer.Client = wgClient
|
2023-09-18 16:52:28 +02:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
|
|
|
func (server *MeshCtrlServer) GetEndpoint() string {
|
|
|
|
return server.Host + ":" + strconv.Itoa(server.Port)
|
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
|
|
|
* Run the gin server instance
|
|
|
|
*/
|
|
|
|
func (server *MeshCtrlServer) Run() bool {
|
|
|
|
r := gin.Default()
|
|
|
|
r.Run(server.GetEndpoint())
|
|
|
|
return true
|
|
|
|
}
|
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
|
|
|
|
}
|