-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
166 lines (151 loc) · 5.63 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
package main
import (
"flag"
"fmt"
"github.com/segator/wireguard-dynamic/mesh"
"log"
"net"
"os"
"os/signal"
"strings"
"syscall"
"time"
)
type cmdLineOpts struct {
init bool
join bool
kvType string
kvUser string
kvPassword string
kvToken string
kvAddrs string
mesh mesh.Mesh
meshPeer mesh.MeshLocalPeer
}
var (
opts cmdLineOpts
initCmd = flag.NewFlagSet("init", flag.ExitOnError)
joinCmd = flag.NewFlagSet("join", flag.ExitOnError)
)
func main() {
chanOSSignal := make(chan os.Signal)
signal.Notify(chanOSSignal, os.Interrupt, syscall.SIGTERM)
subnets := ""
privateIps := ""
flag.Parse()
switch os.Args[1] {
case "init":
commonParameters(initCmd)
initCmd.Parse(os.Args[2:])
opts.init=true
case "join":
opts.join=true
joinCmd.StringVar(&opts.mesh.MeshID, "token", "", "join mesh token")
joinCmd.IntVar(&opts.meshPeer.ListenPort, "listen-port", 31111, "Listen Port for VPN Service")
joinCmd.IntVar(&opts.meshPeer.ApiListenPort, "api-listen-port", 23103, "Listen Port for REST API Service")
joinCmd.IntVar(&opts.meshPeer.PublicPort, "public-port", 31111, "Public listen Port for the VPN Service, if connection through NAT can be diferent than listen port")
joinCmd.StringVar(&opts.meshPeer.PublicIP, "public-ip", "auto", "Public IP used by other nodes to connect to this node, by default is auto calculated")
joinCmd.StringVar(&privateIps, "private-ip", "auto", "Private IP used by other nodes on the same LAN to connect to this node directly without tunneling through wireguard, you can also define ranges so we will search for privateIps that match this range(Example: 192.168.0.0/16), by default will use all Ip's on internal net device,if you don't want this node be reached by internal network set 'none'")
joinCmd.StringVar(&opts.meshPeer.VPNIP, "vpn-ip", "auto", "IP of the internal VPN this node will have, only /32 allowed")
joinCmd.StringVar(&subnets, "accept-networks", "", "network list splited with ,(coma) so other Nodes will know how to achieve those subnets through this node")
//joinCmd.StringVar(&subnets, "accept-networks-routing", "NONE", "how other nodes will route to accepted networks of this node(MASQUERADE, NONE, FORWARD)")
joinCmd.IntVar(&opts.meshPeer.KeepAlive, "keep-alive", 15, "Keep Alive in seconds")
joinCmd.StringVar(&opts.meshPeer.DeviceName, "device-name", "wg0", "Device name, by default wg0")
commonParameters(joinCmd)
joinCmd.Parse(os.Args[2:])
default:
fmt.Fprintf(os.Stderr, "wireguard-dynamic init #this create new mesh token\nwireguard-dynamic join #this join this node to a existing mesh")
os.Exit(1)
}
//Get Repo Type
storeRepository :=mesh.NewKVDBRepository()
if opts.kvType != "kvdb.io" {
KVAddrsArray :=strings.Split(opts.kvAddrs,",")
valkeyrieConfig := &mesh.ValkeyrieConfig{
Token:opts.kvToken,
ConnectionTimeout:time.Duration(5 * time.Second),
}
storeRepository = mesh.NewKValkeyrieRepository(mesh.ValkeyrieKVType(opts.kvType),KVAddrsArray,valkeyrieConfig)
}
//Get VPN Type( Chaining Wireguard type + host Gateway)
networkService := mesh.NewHostGatewayNetworkService(mesh.NewWireGuardNetworkService())
//Mesh Type
me :=mesh.NewSimpleMeshService(storeRepository,networkService)
//Api Service
restApiService := mesh.NewRestAPIService(opts.meshPeer.ApiListenPort,me)
if opts.init {
mesh :=me.CreateMesh()
fmt.Print(mesh.MeshID)
}else if opts.join{
opts.meshPeer.Version=0
if opts.meshPeer.PublicIP == "auto" {
opts.meshPeer.IsCalculatedPublicIP=true
opts.meshPeer.PublicIP = ""
}
if privateIps == "auto" {
opts.meshPeer.PrivateIPs = findAllPrivateIps()
}else if privateIps == "none" {
opts.meshPeer.PrivateIPs = []string{"none"}
}else{
allPrivateIPs:=findAllPrivateIps()
opts.meshPeer.PrivateIPs = []string{}
privateIpsArray :=strings.Split(privateIps,",")
for _, privateIP := range privateIpsArray {
_, subnet,err :=net.ParseCIDR(privateIP)
if err != nil {
opts.meshPeer.PrivateIPs = append(opts.meshPeer.PrivateIPs,privateIP)
}else{
for _, privateLocalIP := range allPrivateIPs {
if subnet.Contains(net.ParseIP(privateLocalIP)) {
addIP:=true
for _, alreadyAddedIP := range opts.meshPeer.PrivateIPs {
if alreadyAddedIP == privateLocalIP {
addIP=false
break
}
}
if addIP{
opts.meshPeer.PrivateIPs = append(opts.meshPeer.PrivateIPs,privateLocalIP)
}
}
}
}
}
}
if opts.meshPeer.VPNIP == "auto" {
opts.meshPeer.AutoVPNIP=true
opts.meshPeer.VPNIP = ""
}
if subnets != "" {
opts.meshPeer.AllowedIPs = strings.Split(subnets,",")
}
go restApiService.Listen()
me.JoinMesh(opts.mesh,opts.meshPeer)
<-chanOSSignal
log.Println("Signal detected, closing network")
me.Stop()
}
os.Exit(0)
}
func commonParameters(flagSet *flag.FlagSet) {
flagSet.StringVar(&opts.kvType,"kv-type","kvdb.io","Select a key-value service to use as a configuration provider")
flagSet.StringVar(&opts.kvUser,"kv-username","","authentication username for selected KeyValue Type")
flagSet.StringVar(&opts.kvPassword,"kv-password","","authentication password for selected KeyValue Type")
flagSet.StringVar(&opts.kvToken,"kv-token","","KV Auth Token")
flagSet.StringVar(&opts.kvAddrs,"kv-addr","localhost","KV Server Address separated with coma, example 15.1.1.1,16.3.2.1,41.1.4.11")
}
func findAllPrivateIps() []string {
foundIPS := []string{}
addrs, err := net.InterfaceAddrs()
if err != nil {
log.Panic("Oops:"+err.Error())
}
for _, a := range addrs {
if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
foundIPS = append(foundIPS,ipnet.IP.String())
}
}
}
return foundIPS
}