forked from adamlaska/machine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnetwork.go
More file actions
400 lines (336 loc) · 10.7 KB
/
network.go
File metadata and controls
400 lines (336 loc) · 10.7 KB
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
package virtualbox
import (
"errors"
"fmt"
"net"
"regexp"
"strings"
"time"
"runtime"
"github.com/docker/machine/libmachine/log"
)
const (
buggyNetmask = "0f000000"
dhcpPrefix = "HostInterfaceNetworking-"
)
var (
reHostOnlyAdapterCreated = regexp.MustCompile(`Interface '(.+)' was successfully created`)
errNewHostOnlyAdapterNotVisible = errors.New("The host-only adapter we just created is not visible. This is a well known VirtualBox bug. You might want to uninstall it and reinstall at least version 5.0.12 that is is supposed to fix this issue")
)
// Host-only network.
type hostOnlyNetwork struct {
Name string
GUID string
DHCP bool
IPv4 net.IPNet
HwAddr net.HardwareAddr
Medium string
Status string
NetworkName string // referenced in DHCP.NetworkName
}
// HostInterfaces returns host network interface info. By default delegates to net.Interfaces()
type HostInterfaces interface {
Interfaces() ([]net.Interface, error)
Addrs(iface *net.Interface) ([]net.Addr, error)
}
func NewHostInterfaces() HostInterfaces {
return &defaultHostInterfaces{}
}
type defaultHostInterfaces struct {
}
func (ni *defaultHostInterfaces) Interfaces() ([]net.Interface, error) {
return net.Interfaces()
}
func (ni *defaultHostInterfaces) Addrs(iface *net.Interface) ([]net.Addr, error) {
return iface.Addrs()
}
// Save changes the configuration of the host-only network.
func (n *hostOnlyNetwork) Save(vbox VBoxManager) error {
if err := n.SaveIPv4(vbox); err != nil {
return err
}
if n.DHCP {
vbox.vbm("hostonlyif", "ipconfig", n.Name, "--dhcp") // not implemented as of VirtualBox 4.3
}
return nil
}
// SaveIPv4 changes the ipv4 configuration of the host-only network.
func (n *hostOnlyNetwork) SaveIPv4(vbox VBoxManager) error {
if n.IPv4.IP != nil && n.IPv4.Mask != nil {
if runtime.GOOS == "windows" {
log.Warn("Windows might ask for the permission to configure a network adapter. Sometimes, such confirmation window is minimized in the taskbar.")
}
if err := vbox.vbm("hostonlyif", "ipconfig", n.Name, "--ip", n.IPv4.IP.String(), "--netmask", net.IP(n.IPv4.Mask).String()); err != nil {
return err
}
}
return nil
}
// createHostonlyAdapter creates a new host-only network.
func createHostonlyAdapter(vbox VBoxManager) (*hostOnlyNetwork, error) {
if runtime.GOOS == "windows" {
log.Warn("Windows might ask for the permission to create a network adapter. Sometimes, such confirmation window is minimized in the taskbar.")
}
out, err := vbox.vbmOut("hostonlyif", "create")
if err != nil {
return nil, err
}
res := reHostOnlyAdapterCreated.FindStringSubmatch(string(out))
if res == nil {
return nil, errors.New("Failed to create host-only adapter")
}
return &hostOnlyNetwork{Name: res[1]}, nil
}
// listHostOnlyAdapters gets all host-only adapters in a map keyed by NetworkName.
func listHostOnlyAdapters(vbox VBoxManager) (map[string]*hostOnlyNetwork, error) {
out, err := vbox.vbmOut("list", "hostonlyifs")
if err != nil {
return nil, err
}
byName := map[string]*hostOnlyNetwork{}
byIP := map[string]*hostOnlyNetwork{}
n := &hostOnlyNetwork{}
err = parseKeyValues(out, reColonLine, func(key, val string) error {
switch key {
case "Name":
n.Name = val
case "GUID":
n.GUID = val
case "DHCP":
n.DHCP = (val != "Disabled")
case "IPAddress":
n.IPv4.IP = net.ParseIP(val)
case "NetworkMask":
n.IPv4.Mask = parseIPv4Mask(val)
case "HardwareAddress":
mac, err := net.ParseMAC(val)
if err != nil {
return err
}
n.HwAddr = mac
case "MediumType":
n.Medium = val
case "Status":
n.Status = val
case "VBoxNetworkName":
n.NetworkName = val
if _, present := byName[n.NetworkName]; present {
return fmt.Errorf("VirtualBox is configured with multiple host-only adapters with the same name %q. Please remove one.", n.NetworkName)
}
byName[n.NetworkName] = n
if len(n.IPv4.IP) != 0 {
if _, present := byIP[n.IPv4.IP.String()]; present {
return fmt.Errorf("VirtualBox is configured with multiple host-only adapters with the same IP %q. Please remove one.", n.IPv4.IP)
}
byIP[n.IPv4.IP.String()] = n
}
n = &hostOnlyNetwork{}
}
return nil
})
if err != nil {
return nil, err
}
return byName, nil
}
func getHostOnlyAdapter(nets map[string]*hostOnlyNetwork, hostIP net.IP, netmask net.IPMask) *hostOnlyNetwork {
for _, n := range nets {
// Second part of this conditional handles a race where
// VirtualBox returns us the incorrect netmask value for the
// newly created adapter.
if hostIP.Equal(n.IPv4.IP) &&
(netmask.String() == n.IPv4.Mask.String() || n.IPv4.Mask.String() == buggyNetmask) {
log.Debugf("Found: %s", n.Name)
return n
}
}
log.Debug("Not found")
return nil
}
func getOrCreateHostOnlyNetwork(hostIP net.IP, netmask net.IPMask, nets map[string]*hostOnlyNetwork, vbox VBoxManager) (*hostOnlyNetwork, error) {
// Search for an existing host-only adapter.
hostOnlyAdapter := getHostOnlyAdapter(nets, hostIP, netmask)
if hostOnlyAdapter != nil {
return hostOnlyAdapter, nil
}
// No existing host-only adapter found. Create a new one.
_, err := createHostonlyAdapter(vbox)
if err != nil {
// Sometimes the host-only adapter fails to create. See https://www.virtualbox.org/ticket/14040
// BUT, it is created in fact! So let's wait until it appears last in the list
log.Warnf("Creating a new host-only adapter produced an error: %s", err)
log.Warn("This is a known VirtualBox bug. Let's try to recover anyway...")
}
// It can take some time for an adapter to appear. Let's poll.
hostOnlyAdapter, err = waitForNewHostOnlyNetwork(nets, vbox)
if err != nil {
// Sometimes, Vbox says it created it but then it cannot be found...
return nil, errNewHostOnlyAdapterNotVisible
}
log.Warnf("Found a new host-only adapter: %q", hostOnlyAdapter.Name)
hostOnlyAdapter.IPv4.IP = hostIP
hostOnlyAdapter.IPv4.Mask = netmask
if err := hostOnlyAdapter.Save(vbox); err != nil {
return nil, err
}
return hostOnlyAdapter, nil
}
func waitForNewHostOnlyNetwork(oldNets map[string]*hostOnlyNetwork, vbox VBoxManager) (*hostOnlyNetwork, error) {
for i := 0; i < 10; i++ {
time.Sleep(1 * time.Second)
newNets, err := listHostOnlyAdapters(vbox)
if err != nil {
return nil, err
}
for name, latestNet := range newNets {
if _, present := oldNets[name]; !present {
return latestNet, nil
}
}
}
return nil, errors.New("Failed to find a new host-only adapter")
}
// DHCP server info.
type dhcpServer struct {
NetworkName string
IPv4 net.IPNet
LowerIP net.IP
UpperIP net.IP
Enabled bool
}
// removeOrphanDHCPServers removed the DHCP servers linked to no host-only adapter
func removeOrphanDHCPServers(vbox VBoxManager) error {
dhcps, err := listDHCPServers(vbox)
if err != nil {
return err
}
if len(dhcps) == 0 {
return nil
}
log.Debug("Removing orphan DHCP servers...")
nets, err := listHostOnlyAdapters(vbox)
if err != nil {
return err
}
for name := range dhcps {
if strings.HasPrefix(name, dhcpPrefix) {
if _, present := nets[name]; !present {
if err := vbox.vbm("dhcpserver", "remove", "--netname", name); err != nil {
log.Warnf("Unable to remove orphan dhcp server %q: %s", name, err)
}
}
}
}
return nil
}
// addHostOnlyDHCPServer adds a DHCP server to a host-only network.
func addHostOnlyDHCPServer(ifname string, d dhcpServer, vbox VBoxManager) error {
name := dhcpPrefix + ifname
dhcps, err := listDHCPServers(vbox)
if err != nil {
return err
}
// On some platforms (OSX), creating a host-only adapter adds a default dhcpserver,
// while on others (Windows?) it does not.
command := "add"
if dhcp, ok := dhcps[name]; ok {
command = "modify"
if (dhcp.IPv4.IP.Equal(d.IPv4.IP)) && (dhcp.IPv4.Mask.String() == d.IPv4.Mask.String()) && (dhcp.LowerIP.Equal(d.LowerIP)) && (dhcp.UpperIP.Equal(d.UpperIP)) && dhcp.Enabled {
// dhcp is up to date
return nil
}
}
args := []string{"dhcpserver", command,
"--netname", name,
"--ip", d.IPv4.IP.String(),
"--netmask", net.IP(d.IPv4.Mask).String(),
"--lowerip", d.LowerIP.String(),
"--upperip", d.UpperIP.String(),
}
if d.Enabled {
args = append(args, "--enable")
} else {
args = append(args, "--disable")
}
if runtime.GOOS == "windows" {
log.Warn("Windows might ask for the permission to configure a dhcp server. Sometimes, such confirmation window is minimized in the taskbar.")
}
return vbox.vbm(args...)
}
// listDHCPServers lists all DHCP server settings in a map keyed by DHCP.NetworkName.
func listDHCPServers(vbox VBoxManager) (map[string]*dhcpServer, error) {
out, err := vbox.vbmOut("list", "dhcpservers")
if err != nil {
return nil, err
}
m := map[string]*dhcpServer{}
dhcp := &dhcpServer{}
err = parseKeyValues(out, reColonLine, func(key, val string) error {
switch key {
case "NetworkName":
dhcp = &dhcpServer{}
m[val] = dhcp
dhcp.NetworkName = val
case "IP":
dhcp.IPv4.IP = net.ParseIP(val)
case "upperIPAddress":
dhcp.UpperIP = net.ParseIP(val)
case "lowerIPAddress":
dhcp.LowerIP = net.ParseIP(val)
case "NetworkMask":
dhcp.IPv4.Mask = parseIPv4Mask(val)
case "Enabled":
dhcp.Enabled = (val == "Yes")
}
return nil
})
if err != nil {
return nil, err
}
return m, nil
}
// listHostInterfaces returns a map of net.IPNet addresses of host interfaces that are "UP" and not loopback adapters
// and not virtualbox host-only networks (given by excludeNets), keyed by CIDR string.
func listHostInterfaces(hif HostInterfaces, excludeNets map[string]*hostOnlyNetwork) (map[string]*net.IPNet, error) {
ifaces, err := hif.Interfaces()
if err != nil {
return nil, err
}
m := map[string]*net.IPNet{}
for _, iface := range ifaces {
addrs, err := hif.Addrs(&iface)
if err != nil {
return nil, err
}
for _, a := range addrs {
switch ipnet := a.(type) {
case *net.IPNet:
_, hostOnly := excludeNets[ipnet.String()]
if !hostOnly && iface.Flags&net.FlagUp != 0 && iface.Flags&net.FlagLoopback == 0 {
m[ipnet.String()] = ipnet
}
default:
}
}
}
return m, nil
}
// checkIPNetCollision returns true if any host interfaces conflict with the host-only network mask passed as a parameter.
// This works with IPv4 or IPv6 ip addresses.
func checkIPNetCollision(hostonly *net.IPNet, hostIfaces map[string]*net.IPNet) (bool, error) {
for _, ifaceNet := range hostIfaces {
if hostonly.IP.Equal(ifaceNet.IP.Mask(ifaceNet.Mask)) {
return true, nil
}
}
return false, nil
}
// parseIPv4Mask parses IPv4 netmask written in IP form (e.g. 255.255.255.0).
// This function should really belong to the net package.
func parseIPv4Mask(s string) net.IPMask {
mask := net.ParseIP(s)
if mask == nil {
return nil
}
return net.IPv4Mask(mask[12], mask[13], mask[14], mask[15])
}