-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
main.go
214 lines (187 loc) · 4.87 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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
/*
Copyright 2023 Avi Zimmerman <avi.zimmerman@gmail.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"bufio"
"context"
"errors"
"flag"
"fmt"
"net"
"os"
"os/signal"
"syscall"
"github.com/webmeshproj/webmesh/pkg/config"
"github.com/webmeshproj/webmesh/pkg/embed"
"github.com/webmeshproj/webmesh/pkg/meshnet/endpoints"
)
func main() {
joinServer := flag.String("join", "", "Address of node to join")
loglevel := flag.String("loglevel", "", "Log level (default: silent)")
flag.Parse()
mode := "server"
if *joinServer != "" {
mode = "client"
}
switch mode {
case "server":
if err := runServer(*loglevel); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
case "client":
if err := runClient(*loglevel, *joinServer); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
default:
flag.Usage()
os.Exit(1)
}
}
// We explicitly set unique ports in case we are being run on the
// same machine.
func runServer(loglevel string) error {
ctx := context.Background()
eps, err := endpoints.Detect(ctx, endpoints.DetectOpts{
DetectIPv6: true,
DetectPrivate: true,
SkipInterfaces: []string{},
})
if err != nil {
return err
}
if len(eps) == 0 {
return errors.New("no endpoints detected")
}
fmt.Printf("Bootstrapping network with primary endpoint %s...\n", eps[0].Addr().String())
conf := config.NewDefaultConfig("server-node")
conf.Global.LogLevel = loglevel
conf.Services.API.ListenAddress = "[::]:8443"
conf.Services.API.Insecure = true
conf.Storage.Raft.ListenAddress = "[::]:9000"
conf.Storage.InMemory = true
conf.WireGuard.ListenPort = 61820
conf.WireGuard.InterfaceName = "meshserver0"
conf.Bootstrap.Enabled = true
conf.TLS.Insecure = true
conf.Mesh.PrimaryEndpoint = eps[0].Addr().String()
conn, err := embed.NewNode(context.Background(), embed.Options{Config: conf})
if err != nil {
return err
}
err = conn.Start(ctx)
if err != nil {
return err
}
defer conn.Stop(ctx)
// Start a chat server on the wireguard interface.
addr := conn.AddressV6().Addr()
fmt.Printf("Chat server listening on %s:8080\n", addr)
l, err := net.Listen("tcp", net.JoinHostPort(addr.String(), "8080"))
if err != nil {
return err
}
defer l.Close()
go func() {
for {
conn, err := l.Accept()
if err != nil {
if errors.Is(err, net.ErrClosed) {
return
}
fmt.Printf("Error accepting connection: %v\n", err)
continue
}
fmt.Print("New connection from ", conn.RemoteAddr(), "\n")
go handleChat(conn)
}
}()
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt, syscall.SIGTERM)
<-sig
return nil
}
func runClient(loglevel string, join string) error {
fmt.Println("Joining", join)
ctx := context.Background()
conf := config.NewDefaultConfig("client-node")
conf.Global.LogLevel = loglevel
conf.Services.API.ListenAddress = "[::]:8444"
conf.Services.API.Insecure = true
conf.WireGuard.ListenPort = 61821
conf.WireGuard.InterfaceName = "meshclient0"
conf.Mesh.JoinAddress = join
conf.TLS.Insecure = true
conn, err := embed.NewNode(context.Background(), embed.Options{Config: conf})
if err != nil {
return err
}
err = conn.Start(ctx)
if err != nil {
return err
}
defer conn.Stop(ctx)
// Dial the chat server on the wireguard interface.
c, err := conn.Dial(ctx, "tcp", "server-node:8080")
if err != nil {
return err
}
go handleChat(c)
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt, syscall.SIGTERM)
<-sig
return nil
}
func handleChat(conn net.Conn) {
defer conn.Close()
rw := bufio.NewReadWriter(bufio.NewReader(conn), bufio.NewWriter(conn))
go writeData(rw)
readData(rw)
}
func readData(rw *bufio.ReadWriter) {
for {
str, err := rw.ReadString('\n')
if err != nil {
fmt.Println("Error reading from buffer", "error", err.Error())
return
}
if str == "" {
return
}
if str != "\n" {
fmt.Printf("\x1b[32m%s\x1b[0m> ", str)
}
}
}
func writeData(rw *bufio.ReadWriter) {
stdReader := bufio.NewReader(os.Stdin)
for {
fmt.Print("> ")
sendData, err := stdReader.ReadString('\n')
if err != nil {
fmt.Println("Error reading from stdin", "error", err.Error())
return
}
_, err = rw.WriteString(fmt.Sprintf("%s\n", sendData))
if err != nil {
fmt.Println("Error writing to buffer", "error", err.Error())
return
}
err = rw.Flush()
if err != nil {
fmt.Println("Error flushing buffer", "error", err.Error())
return
}
}
}