-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathvmnet.go
424 lines (364 loc) · 10.5 KB
/
vmnet.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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
package vmnet
import (
"context"
"fmt"
"log/slog"
"net"
"os"
"strconv"
"gvisor.dev/gvisor/pkg/tcpip"
"gvisor.dev/gvisor/pkg/tcpip/adapters/gonet"
"gvisor.dev/gvisor/pkg/tcpip/header"
"gvisor.dev/gvisor/pkg/tcpip/network/ipv4"
"gvisor.dev/gvisor/pkg/tcpip/stack"
"gvisor.dev/gvisor/pkg/tcpip/transport/tcp"
)
type networkOpts struct {
MTU uint32
PcapFile *os.File
MACAddress net.HardwareAddr
DNSConfig *DNSConfig
TCPMaxInFlight int
TCPReceiveBufferSize int
Logger *slog.Logger
}
// NetworkOpts is functional options.
type NetworkOpts func(*networkOpts)
// WithMTU is an option to set MTU (maximum transmission unit) between the gateway
// and some link devices.
//
// Default is 1500.
func WithMTU(mtu uint32) NetworkOpts {
return func(n *networkOpts) {
n.MTU = mtu
}
}
// WithPcapFile is an option to create a pcap file based on the given file
// for writing packet data.
//
// Default is nil.
func WithPcapFile(pcapFile *os.File) NetworkOpts {
return func(n *networkOpts) {
n.PcapFile = pcapFile
}
}
// WithGatewayMACAddress is an option to specify the gateway MAC address.
//
// Default is "7a:5b:10:21:90:e3"
func WithGatewayMACAddress(hwAddr net.HardwareAddr) NetworkOpts {
return func(n *networkOpts) {
n.MACAddress = hwAddr
}
}
// WithDNSConfig is an option to configure DNS.
//
// Default value will be created from your /etc/resolv.conf file.
func WithDNSConfig(dnsConfig *DNSConfig) NetworkOpts {
return func(n *networkOpts) {
n.DNSConfig = dnsConfig
}
}
// WithTCPMaxInFlight is an option initializes a new TCP forwarder with the given
// maximum number of in-flight connection attempts. Once the maximum is reached
// new incoming connection requests will be ignored.
//
// Default is 512.
func WithTCPMaxInFlight(maxInFlight int) NetworkOpts {
return func(n *networkOpts) {
n.TCPMaxInFlight = maxInFlight
}
}
// WithTCPReceiveBufferSize is an option when use initialize a new TCP forwarder with
// the given buffer size of TCP Recieve window.
//
// Default is 1048576.
func WithTCPReceiveBufferSize(rcvWnd int) NetworkOpts {
return func(n *networkOpts) {
n.TCPReceiveBufferSize = rcvWnd
}
}
// WithLogger is an option for debug logging which is using the given logger.
//
// Default is nil.
func WithLogger(logger *slog.Logger) NetworkOpts {
return func(n *networkOpts) {
n.Logger = logger
}
}
// Network is network for any virtual machines.
type Network struct {
stack *stack.Stack
pool *bytePool
tcpMaxInFlight int
tcpReceiveBufferSize int
gateway *Gateway
logger *slog.Logger
subnet tcpip.Subnet
shutdown func()
}
// New initializes new network stack with a network gateway.
// The first IP in the specified cidr range is treated as the gateway IP address.
//
// For example, assume the value specified for cidr is "192.168.127.0/24". The
// first IP address in this range is "192.168.127.0" and last is "192.168.127.255.
// These IP addresses are not used for assignment. Because In general the first address
// is the network identification and the last one is the broadcast. Thus, the first IP
// address used for assignment here is "192.168.127.1". This is for the Gateway. Subsequent
// IP addresses will be assigned to the Link Device.
func New(cidr string, opts ...NetworkOpts) (*Network, error) {
opt := &networkOpts{
MTU: 1500,
// "7a:5b:10:21:90:e3"
// generated by https://go.dev/play/p/9XRn_wtY2go
MACAddress: net.HardwareAddr{
0x7a, 0x5b, 0x10, 0x21, 0x90, 0xe3,
},
TCPMaxInFlight: 512,
TCPReceiveBufferSize: tcp.DefaultReceiveBufferSize,
Logger: slog.New(&nopHandler{}), // no output
}
for _, optFunc := range opts {
optFunc(opt)
}
db, err := newLeaseDB(cidr)
if err != nil {
return nil, err
}
pool := newBytePool(int(opt.MTU))
_, subnet, err := net.ParseCIDR(cidr)
if err != nil {
return nil, err
}
gw, err := newGateway(opt.MACAddress, &gatewayOption{
MTU: opt.MTU,
PcapFile: opt.PcapFile,
Pool: pool,
Logger: opt.Logger,
Leases: db,
DNSConfig: opt.DNSConfig,
Subnet: subnet,
})
if err != nil {
return nil, err
}
s, err := createNetworkStack(gw.endpoint)
if err != nil {
return nil, err
}
gatewayIPv4 := tcpip.AddrFromSlice(gw.ipv4)
addAddress(s, gatewayIPv4)
ctx, cancel := context.WithCancel(context.Background())
nt := &Network{
stack: s,
pool: pool,
tcpMaxInFlight: opt.TCPMaxInFlight,
tcpReceiveBufferSize: opt.TCPReceiveBufferSize,
logger: opt.Logger,
gateway: gw,
subnet: gw.endpoint.subnet,
shutdown: cancel,
}
err = gw.serveDNS4Server(ctx, s, &tcpip.FullAddress{
NIC: nicID,
Addr: gatewayIPv4,
Port: 53,
})
if err != nil {
return nil, err
}
nt.setUDPForwarder(ctx)
nt.setTCPForwarder(ctx)
return nt, nil
}
func (nt *Network) Shutdown() {
nt.stack.Destroy()
nt.shutdown()
}
// Gateway returns default gateway in this network stack.
func (nt *Network) Gateway() *Gateway { return nt.gateway }
func (nt *Network) tcpIncomingForward(guestIPv4 net.IP, guestPort, hostPort int) (func() error, error) {
ln, err := net.Listen("tcp", ":"+strconv.Itoa(hostPort))
if err != nil {
return nil, err
}
proxy := fmt.Sprintf(
"127.0.0.1:%d <-> %s:%d",
hostPort,
guestIPv4.String(), guestPort,
)
nt.logger.Info(
"start relay incoming TCP forward",
slog.String("forward", proxy),
)
go func() {
defer ln.Close()
for {
conn, err := ln.Accept()
if err != nil {
nt.logger.Error(
"failed to accept connection in incoming TCP forward", err,
slog.String("forward", proxy),
)
return
}
go func() {
defer conn.Close()
conn1, err := gonet.DialTCP(nt.stack, tcpip.FullAddress{
NIC: nicID,
Addr: tcpip.AddrFromSlice(guestIPv4),
Port: uint16(guestPort),
}, ipv4.ProtocolNumber)
if err != nil {
nt.logger.Error(
"failed to dial connection to upstream in incoming TCP forward", err,
slog.String("forward", proxy),
)
return
}
defer conn1.Close()
if err := nt.pool.tcpRelay(conn.(*net.TCPConn), conn1); err != nil {
nt.logger.Error(
"failed to relay the connection in incoming TCP forward", err,
slog.String("forward", proxy),
)
}
}()
}
}()
return ln.Close, nil
}
func createNetworkStack(ep stack.LinkEndpoint) (*stack.Stack, error) {
s, err := createBaseNetStack()
if err != nil {
return nil, err
}
if err := s.CreateNIC(nicID, ep); err != nil {
return nil, fmt.Errorf("could not create netstack NIC: %v", err)
}
s.SetRouteTable([]tcpip.Route{
{
Destination: header.IPv4EmptySubnet,
// Gateway: gatewayIPv4,
NIC: nicID,
},
})
// Enable to forward transport layer data.
s.SetPromiscuousMode(nicID, true)
// Enable to allow endpoints to bind to any address in the NIC.
s.SetSpoofing(nicID, true)
return s, nil
}
// LinkDevice is a link device with vmnet network.
type LinkDevice struct {
dev *os.File
ipv4 net.IP
hwAddress net.HardwareAddr
closeFunc func() error
pool *bytePool
}
type linkDeviceOpts struct {
SendBufferSize int
TCPIncomingForward map[int]int
}
// LinkDeviceOpts is a optional type for NewLinkDevice.
type LinkDeviceOpts func(*linkDeviceOpts)
// WithSendBufferSize is an option sets SO_SNDBUF size between
// ethernet device and guest system. And sets SO_RCVBUF size
// four times of SO_SNDBUF. the default SO_SNDBUF is 131072.
func WithSendBufferSize(bufSize int) LinkDeviceOpts {
return func(edo *linkDeviceOpts) {
edo.SendBufferSize = bufSize
}
}
// WithTCPIncomingForward is an option to set TCP forward from host machine to guest machine.
// For example, if you want to connect from the host machine to the guest machine via ssh,
// configure as follows:
//
// `WithTCPIncomingForward(8888, 22)` then you can ssh to the guest OS via 127.0.0.1:8888
//
// This option can be applied multiple times.
func WithTCPIncomingForward(hostPort, guestPort int) LinkDeviceOpts {
return func(edo *linkDeviceOpts) {
if edo.TCPIncomingForward == nil {
edo.TCPIncomingForward = make(map[int]int)
}
edo.TCPIncomingForward[hostPort] = guestPort
}
}
// NewLinkDevice creates a new link device which is connected with vmnet network.
func (nt *Network) NewLinkDevice(hwAddr net.HardwareAddr, opts ...LinkDeviceOpts) (*LinkDevice, error) {
o := linkDeviceOpts{
// net.inet.tcp.sendspace: 131072 (sysctl net.inet.tcp.sendspace)
SendBufferSize: 128 * 1024,
}
for _, optFunc := range opts {
optFunc(&o)
}
deviceIPv4, err := nt.gateway.leaseDB.LeaseIP(hwAddr)
if err != nil {
return nil, err
}
dev, network, err := socketPair(o.SendBufferSize, o.SendBufferSize)
if err != nil {
return nil, fmt.Errorf("failed to create socket pair: %w", err)
}
closer := &wrappedConn{closers: []func() error{
dev.Close,
network.Close,
}}
ethConn, err := net.FileConn(network)
if err != nil {
closer.Close()
return nil, fmt.Errorf("failed to make a connection: %w", err)
}
closer.Conn = ethConn
closer.closers = append(closer.closers, ethConn.Close)
deviceIPv4Addr := tcpip.AddrFromSlice(deviceIPv4.To4())
nt.gateway.endpoint.RegisterConn(
deviceIPv4Addr,
tcpip.LinkAddress(hwAddr),
// we pass the closer with associated ethConn, because then if the endpoint
// is destroyed, everything is closed along with it
closer,
)
for hostPort, guestPort := range o.TCPIncomingForward {
close, err := nt.tcpIncomingForward(deviceIPv4, guestPort, hostPort)
if err != nil {
return nil, fmt.Errorf(
"failed to listen tcp forward proxy 127.0.0.1:%d <-> %s:%d: %w",
hostPort,
deviceIPv4.String(), guestPort,
err,
)
}
closer.closers = append(closer.closers, close)
}
return &LinkDevice{
dev: dev,
ipv4: deviceIPv4,
closeFunc: closer.Close,
pool: nt.pool,
hwAddress: hwAddr,
}, nil
}
// File returns *os.File for this device.
func (l *LinkDevice) File() *os.File { return l.dev }
// IPv4 returns ipv4 address that you can use in the guest OS.
func (l *LinkDevice) IPv4() net.IP { return l.ipv4 }
// MACAddress returns MAC address.
func (l *LinkDevice) MACAddress() net.HardwareAddr { return l.hwAddress }
// Close closes this device and LinkDevice connection.
func (l *LinkDevice) Close() error { return l.closeFunc() }
type wrappedConn struct {
net.Conn
closers []func() error
}
func (mt *wrappedConn) Close() error {
var err error
for _, c := range mt.closers {
if cerr := c(); cerr != nil && err == nil {
err = cerr
}
}
return err
}