Simple direct peer-to-peer communication

This commit is contained in:
Tim Beatham 2023-09-20 19:05:29 +01:00
parent cfdf377567
commit 91212e60cf
4 changed files with 38 additions and 19 deletions

View File

@ -7,6 +7,7 @@ import (
"net"
"strconv"
"github.com/tim-beatham/wgmesh/pkg/lib"
"golang.zx2c4.com/wireguard/wgctrl"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
)
@ -32,6 +33,20 @@ func (server *MeshCtrlServer) IsInMesh(meshId string) bool {
return inMesh
}
func (server *MeshCtrlServer) addSelfToMesh(meshId string) error {
ipAddr := lib.GetOutboundIP()
node := MeshNode{
HostEndpoint: ipAddr.String() + ":8080",
PublicKey: server.GetDevice().PrivateKey.String(),
WgEndpoint: ipAddr.String() + ":51820",
WgHost: "10.0.0.1/32",
}
server.Meshes[meshId].Nodes[node.HostEndpoint] = node
return nil
}
func (server *MeshCtrlServer) CreateMesh() (*Mesh, error) {
key, err := wgtypes.GenerateKey()
@ -45,6 +60,7 @@ func (server *MeshCtrlServer) CreateMesh() (*Mesh, error) {
}
server.Meshes[key.String()] = mesh
server.addSelfToMesh(mesh.SharedKey.String())
return &mesh, nil
}

View File

@ -27,19 +27,6 @@ type Mesh struct {
Server *ctrlserver.MeshCtrlServer
}
// Get preferred outbound ip of this machine
func GetOutboundIP() (*net.UDPAddr, error) {
conn, err := net.Dial("udp", "8.8.8.8:80")
if err != nil {
return nil, err
}
defer conn.Close()
localAddr := conn.LocalAddr().(*net.UDPAddr)
return localAddr, nil
}
/*
* Create a new WireGuard mesh network
*/
@ -108,13 +95,11 @@ func updateMesh(n *Mesh, meshId string, endPoint string) error {
ctrlserver.AddWgPeer(n.Server.IfName, n.Server.Client, meshNode)
}
cfg := wgtypes.Config{}
n.Server.Client.ConfigureDevice(n.Server.IfName)
return nil
}
func (n Mesh) JoinOtherMesh
func (n Mesh) JoinMesh(args *ipctypes.JoinMeshArgs, reply *string) error {
conn, err := grpc.Dial(args.IpAdress+":8080", grpc.WithTransportCredentials(insecure.NewCredentials()))

View File

@ -66,10 +66,10 @@ func (m *meshCtrlServer) JoinMesh(ctx context.Context, request *JoinMeshRequest)
}
addHostArgs := ctrlserver.AddHostArgs{
HostEndpoint: "[" + hostIp + "]" + ":" + strconv.Itoa(int(request.HostPort)),
HostEndpoint: hostIp + ":" + strconv.Itoa(int(request.HostPort)),
PublicKey: request.PublicKey,
MeshId: request.MeshId,
WgEndpoint: "[" + hostIp + "]" + ":" + strconv.Itoa(int(request.WgPort)),
WgEndpoint: hostIp + ":" + strconv.Itoa(int(request.WgPort)),
}
err = m.server.AddHost(addHostArgs)

18
pkg/lib/ip.go Normal file
View File

@ -0,0 +1,18 @@
package lib
import (
"log"
"net"
)
func GetOutboundIP() net.IP {
conn, err := net.Dial("udp", "8.8.8.8:80")
if err != nil {
log.Fatal(err)
}
defer conn.Close()
localAddr := conn.LocalAddr().(*net.UDPAddr)
return localAddr.IP
}