summaryrefslogtreecommitdiff
path: root/libpod/network/internal/util/bridge.go
blob: 47655705072e30122cc6e607a04050c64114137d (plain)
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
package util

import (
	"net"

	"github.com/containers/podman/v3/libpod/define"
	"github.com/containers/podman/v3/libpod/network/types"
	"github.com/containers/podman/v3/libpod/network/util"
	pkgutil "github.com/containers/podman/v3/pkg/util"
	"github.com/pkg/errors"
)

func CreateBridge(n NetUtil, network *types.Network, usedNetworks []*net.IPNet) error {
	if network.NetworkInterface != "" {
		bridges := GetBridgeInterfaceNames(n)
		if pkgutil.StringInSlice(network.NetworkInterface, bridges) {
			return errors.Errorf("bridge name %s already in use", network.NetworkInterface)
		}
		if !define.NameRegex.MatchString(network.NetworkInterface) {
			return errors.Wrapf(define.RegexError, "bridge name %s invalid", network.NetworkInterface)
		}
	} else {
		var err error
		network.NetworkInterface, err = GetFreeDeviceName(n)
		if err != nil {
			return err
		}
	}

	if network.IPAMOptions["driver"] != types.DHCPIPAMDriver {
		if len(network.Subnets) == 0 {
			freeSubnet, err := GetFreeIPv4NetworkSubnet(usedNetworks)
			if err != nil {
				return err
			}
			network.Subnets = append(network.Subnets, *freeSubnet)
		}
		// ipv6 enabled means dual stack, check if we already have
		// a ipv4 or ipv6 subnet and add one if not.
		if network.IPv6Enabled {
			ipv4 := false
			ipv6 := false
			for _, subnet := range network.Subnets {
				if util.IsIPv6(subnet.Subnet.IP) {
					ipv6 = true
				}
				if util.IsIPv4(subnet.Subnet.IP) {
					ipv4 = true
				}
			}
			if !ipv4 {
				freeSubnet, err := GetFreeIPv4NetworkSubnet(usedNetworks)
				if err != nil {
					return err
				}
				network.Subnets = append(network.Subnets, *freeSubnet)
			}
			if !ipv6 {
				freeSubnet, err := GetFreeIPv6NetworkSubnet(usedNetworks)
				if err != nil {
					return err
				}
				network.Subnets = append(network.Subnets, *freeSubnet)
			}
		}
		network.IPAMOptions["driver"] = types.HostLocalIPAMDriver
	}
	return nil
}