-
Notifications
You must be signed in to change notification settings - Fork 44
/
main.go
341 lines (277 loc) · 7.84 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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
//go:build darwin
package main
import (
"context"
"fmt"
"io"
"net"
"os"
"os/signal"
"strconv"
"syscall"
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/client"
"github.com/docker/docker/pkg/stdcopy"
"golang.zx2c4.com/wireguard/conn"
"golang.zx2c4.com/wireguard/device"
"golang.zx2c4.com/wireguard/ipc"
"golang.zx2c4.com/wireguard/tun"
"golang.zx2c4.com/wireguard/wgctrl"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
"github.com/chipmk/docker-mac-net-connect/networkmanager"
"github.com/chipmk/docker-mac-net-connect/version"
)
const (
ExitSetupSuccess = 0
ExitSetupFailed = 1
)
const (
ENV_WG_TUN_FD = "WG_TUN_FD"
ENV_WG_UAPI_FD = "WG_UAPI_FD"
ENV_WG_PROCESS_FOREGROUND = "WG_PROCESS_FOREGROUND"
)
func main() {
logLevel := func() int {
switch os.Getenv("LOG_LEVEL") {
case "verbose", "debug":
return device.LogLevelVerbose
case "error":
return device.LogLevelError
case "silent":
return device.LogLevelSilent
}
return device.LogLevelVerbose
}()
fmt.Printf("docker-mac-net-connect version '%s'\n", version.Version)
tun, err := tun.CreateTUN("utun", device.DefaultMTU)
if err != nil {
fmt.Errorf("Failed to create TUN device: %v", err)
os.Exit(ExitSetupFailed)
}
interfaceName, err := tun.Name()
if err != nil {
fmt.Errorf("Failed to get TUN device name: %v", err)
os.Exit(ExitSetupFailed)
}
logger := device.NewLogger(
logLevel,
fmt.Sprintf("(%s) ", interfaceName),
)
fileUAPI, err := ipc.UAPIOpen(interfaceName)
if err != nil {
logger.Errorf("UAPI listen error: %v", err)
os.Exit(ExitSetupFailed)
}
device := device.NewDevice(tun, conn.NewDefaultBind(), logger)
logger.Verbosef("Device started")
errs := make(chan error)
term := make(chan os.Signal, 1)
uapi, err := ipc.UAPIListen(interfaceName, fileUAPI)
if err != nil {
logger.Errorf("Failed to listen on UAPI socket: %v", err)
os.Exit(ExitSetupFailed)
}
go func() {
for {
conn, err := uapi.Accept()
if err != nil {
errs <- err
return
}
go device.IpcHandle(conn)
}
}()
logger.Verbosef("UAPI listener started")
// Wireguard configuration
hostPeerIp := "10.33.33.1"
vmPeerIp := "10.33.33.2"
c, err := wgctrl.New()
if err != nil {
logger.Errorf("Failed to create new wgctrl client: %v", err)
os.Exit(ExitSetupFailed)
}
defer c.Close()
hostPrivateKey, err := wgtypes.GeneratePrivateKey()
if err != nil {
logger.Errorf("Failed to generate host private key: %v", err)
os.Exit(ExitSetupFailed)
}
vmPrivateKey, err := wgtypes.GeneratePrivateKey()
if err != nil {
logger.Errorf("Failed to generate VM private key: %v", err)
os.Exit(ExitSetupFailed)
}
_, wildcardIpNet, err := net.ParseCIDR("0.0.0.0/0")
if err != nil {
logger.Errorf("Failed to parse wildcard CIDR: %v", err)
os.Exit(ExitSetupFailed)
}
_, vmIpNet, err := net.ParseCIDR(vmPeerIp + "/32")
if err != nil {
logger.Errorf("Failed to parse VM peer CIDR: %v", err)
os.Exit(ExitSetupFailed)
}
peer := wgtypes.PeerConfig{
PublicKey: vmPrivateKey.PublicKey(),
AllowedIPs: []net.IPNet{
*wildcardIpNet,
*vmIpNet,
},
}
port := 3333
err = c.ConfigureDevice(interfaceName, wgtypes.Config{
ListenPort: &port,
PrivateKey: &hostPrivateKey,
Peers: []wgtypes.PeerConfig{peer},
})
if err != nil {
logger.Errorf("Failed to configure Wireguard device: %v\n", err)
os.Exit(ExitSetupFailed)
}
networkManager := networkmanager.New()
_, stderr, err := networkManager.SetInterfaceAddress(hostPeerIp, vmPeerIp, interfaceName)
if err != nil {
logger.Errorf("Failed to set interface address with ifconfig: %v. %v", err, stderr)
os.Exit(ExitSetupFailed)
}
logger.Verbosef("Interface %s created\n", interfaceName)
cli, err := client.NewClientWithOpts(client.FromEnv)
if err != nil {
logger.Errorf("Failed to create Docker client: %v", err)
os.Exit(ExitSetupFailed)
}
logger.Verbosef("Wireguard server listening\n")
ctx := context.Background()
go func() {
for {
logger.Verbosef("Setting up Wireguard on Docker Desktop VM\n")
err = setupVm(ctx, cli, port, hostPeerIp, vmPeerIp, hostPrivateKey, vmPrivateKey)
if err != nil {
logger.Errorf("Failed to setup VM: %v", err)
time.Sleep(5 * time.Second)
continue
}
networks, err := cli.NetworkList(ctx, types.NetworkListOptions{})
if err != nil {
logger.Errorf("Failed to list Docker networks: %v", err)
time.Sleep(5 * time.Second)
continue
}
for _, network := range networks {
networkManager.ProcessDockerNetworkCreate(network, interfaceName)
}
logger.Verbosef("Watching Docker events\n")
msgs, errsChan := cli.Events(ctx, types.EventsOptions{
Filters: filters.NewArgs(
filters.Arg("type", "network"),
filters.Arg("event", "create"),
filters.Arg("event", "destroy"),
),
})
for loop := true; loop; {
select {
case err := <-errsChan:
logger.Errorf("Error: %v\n", err)
loop = false
case msg := <-msgs:
// Add routes when new Docker networks are created
if msg.Type == "network" && msg.Action == "create" {
network, err := cli.NetworkInspect(ctx, msg.Actor.ID, types.NetworkInspectOptions{})
if err != nil {
logger.Errorf("Failed to inspect new Docker network: %v", err)
continue
}
networkManager.ProcessDockerNetworkCreate(network, interfaceName)
continue
}
// Delete routes when Docker networks are destroyed
if msg.Type == "network" && msg.Action == "destroy" {
network, exists := networkManager.DockerNetworks[msg.Actor.ID]
if !exists {
logger.Errorf("Unknown Docker network with ID %s. No routes will be removed.")
continue
}
networkManager.ProcessDockerNetworkDestroy(network)
continue
}
}
}
time.Sleep(5 * time.Second)
}
}()
// Wait for program to terminate
signal.Notify(term, syscall.SIGTERM)
signal.Notify(term, os.Interrupt)
select {
case <-term:
case <-errs:
case <-device.Wait():
}
// Clean up
uapi.Close()
device.Close()
logger.Verbosef("Shutting down\n")
}
func setupVm(
ctx context.Context,
dockerCli *client.Client,
serverPort int,
hostPeerIp string,
vmPeerIp string,
hostPrivateKey wgtypes.Key,
vmPrivateKey wgtypes.Key,
) error {
imageName := fmt.Sprintf("%s:%s", version.SetupImage, version.Version)
_, _, err := dockerCli.ImageInspectWithRaw(ctx, imageName)
if err != nil {
fmt.Printf("Image doesn't exist locally. Pulling...\n")
pullStream, err := dockerCli.ImagePull(ctx, imageName, types.ImagePullOptions{})
if err != nil {
return fmt.Errorf("failed to pull setup image: %w", err)
}
io.Copy(os.Stdout, pullStream)
}
resp, err := dockerCli.ContainerCreate(ctx, &container.Config{
Image: imageName,
Env: []string{
"SERVER_PORT=" + strconv.Itoa(serverPort),
"HOST_PEER_IP=" + hostPeerIp,
"VM_PEER_IP=" + vmPeerIp,
"HOST_PUBLIC_KEY=" + hostPrivateKey.PublicKey().String(),
"VM_PRIVATE_KEY=" + vmPrivateKey.String(),
},
}, &container.HostConfig{
AutoRemove: true,
NetworkMode: "host",
CapAdd: []string{"NET_ADMIN"},
}, nil, nil, "wireguard-setup")
if err != nil {
return fmt.Errorf("failed to create container: %w", err)
}
// Run container to completion
err = dockerCli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{})
if err != nil {
return fmt.Errorf("failed to start container: %w", err)
}
func() error {
reader, err := dockerCli.ContainerLogs(ctx, resp.ID, types.ContainerLogsOptions{
ShowStdout: true,
ShowStderr: true,
Follow: true,
})
if err != nil {
return fmt.Errorf("failed to get logs for container %s: %w", resp.ID, err)
}
defer reader.Close()
_, err = stdcopy.StdCopy(os.Stdout, os.Stderr, reader)
if err != nil {
return err
}
return nil
}()
fmt.Println("Setup container complete")
return nil
}