Exemplo n.º 1
0
func GetAvailableGwAddress(bridgeIP string) (gwaddr string, err error) {
	if len(bridgeIP) != 0 {
		_, _, err = net.ParseCIDR(bridgeIP)
		if err != nil {
			return
		}
		gwaddr = bridgeIP
	} else {
		for _, addr := range gatewayAddrs {
			_, dockerNetwork, err := net.ParseCIDR(addr)
			if err != nil {
				return "", err
			}
			if err = CheckRouteOverlaps(dockerNetwork); err != nil {
				continue
			}
			gwaddr = addr
			break
		}
	}
	if gwaddr == "" {
		return "", errors.New("No available gateway addresses")
	}
	return gwaddr, nil
}
Exemplo n.º 2
0
Arquivo: util.go Projeto: 40a/vega
func init() {
	// Add each private block
	privateBlocks = make([]*net.IPNet, 3)
	_, block, err := net.ParseCIDR("10.0.0.0/8")
	if err != nil {
		panic(fmt.Sprintf("Bad cidr. Got %v", err))
	}
	privateBlocks[0] = block

	_, block, err = net.ParseCIDR("172.16.0.0/12")
	if err != nil {
		panic(fmt.Sprintf("Bad cidr. Got %v", err))
	}
	privateBlocks[1] = block

	_, block, err = net.ParseCIDR("192.168.0.0/16")
	if err != nil {
		panic(fmt.Sprintf("Bad cidr. Got %v", err))
	}
	privateBlocks[2] = block

	var n int64
	binary.Read(crand.Reader, binary.BigEndian, &n)

	randSrc = rand.NewSource(n)

	randGen = rand.New(randSrc)
}
Exemplo n.º 3
0
// determine the IP address of the container
func getIp(usePublic bool) string {
	interfaces, _ := net.Interfaces()
	var ips []net.IP
	_, loopback, _ := net.ParseCIDR("127.0.0.0/8")
	for _, intf := range interfaces {
		ipAddrs, _ := intf.Addrs()
		// We're assuming each interface has one IP here because neither Docker
		// nor Triton sets up IP aliasing.
		ipAddr, _, _ := net.ParseCIDR(ipAddrs[0].String())
		if !loopback.Contains(ipAddr) {
			ips = append(ips, ipAddr)
		}
	}
	var ip string
	for _, ipAddr := range ips {
		isPublic := isPublicIp(ipAddr)
		if isPublic && usePublic {
			ip = ipAddr.String()
			break
		} else if !isPublic && !usePublic {
			ip = ipAddr.String()
			break
		}
	}
	return ip
}
Exemplo n.º 4
0
func ExamplePrefix_subnettingAndAggregation() {
	_, n, err := net.ParseCIDR("192.168.0.0/24")
	if err != nil {
		log.Fatal(err)
	}
	p := ipaddr.NewPrefix(n)
	fmt.Println(p.IP, p.Last(), p.Len(), p.Mask, p.Hostmask())
	ps := p.Subnets(2)
	for _, p := range ps {
		fmt.Println(p)
	}
	_, n, err = net.ParseCIDR("192.168.100.0/24")
	if err != nil {
		log.Fatal(err)
	}
	ps = append(ps, *ipaddr.NewPrefix(n))
	fmt.Println(ipaddr.Aggregate(ps[2:]))
	// Output:
	// 192.168.0.0 192.168.0.255 24 ffffff00 000000ff
	// 192.168.0.0/26
	// 192.168.0.64/26
	// 192.168.0.128/26
	// 192.168.0.192/26
	// [192.168.0.128/25 192.168.100.0/24]
}
Exemplo n.º 5
0
func parseIpv4RoutingLine(line string) (route Route, err error) {
	t := strings.Fields(line)

	if strings.HasPrefix(t[1], "link") {
		err = errors.New("Link-local route")
		return
	}

	raw_dest := t[0]
	if raw_dest == "default" {
		raw_dest = "0.0.0.0/0"
	}

	_, destination, err := net.ParseCIDR(raw_dest)
	if err != nil {
		return
	}

	raw_gateway := t[1]
	gateway, _, err := net.ParseCIDR(raw_gateway + "/32")
	if err != nil {
		return
	}

	route.Destination = *destination
	route.Gateway = gateway

	return
}
Exemplo n.º 6
0
func newTestServerWithDefaults() (*Server, *MockRingBuilderThings) {
	b := ring.NewBuilder(64)
	b.SetReplicaCount(3)
	b.AddNode(true, 1, []string{"server1", "zone1"}, []string{"1.2.3.4:56789"}, "server1|meta one", []byte("Conf Thing1"))
	b.AddNode(true, 1, []string{"dummy1", "zone42"}, []string{"1.42.42.42:56789"}, "dummy1|meta one", []byte("Dummy Conf"))
	ring := b.Ring()

	rbytes := []byte("imnotaring")
	bbytes := []byte("imnotbuilder")

	mock := &MockRingBuilderThings{
		builderPath:  "/tmp/test.builder",
		ringPath:     "/tmp/test.ring",
		ring:         ring,
		ringbytes:    &rbytes,
		builder:      b,
		builderbytes: &bbytes,
		managedNodes: make(map[uint64]ManagedNode, 0),
		slaves:       make([]*RingSlave, 0),
		changeChan:   make(chan *changeMsg, 1),
	}
	s := newTestServer(&Config{}, "test", mock)
	_, netblock, _ := net.ParseCIDR("10.0.0.0/24")
	s.netlimits = append(s.netlimits, netblock)
	_, netblock, _ = net.ParseCIDR("1.2.3.0/24")
	s.netlimits = append(s.netlimits, netblock)
	return s, mock
}
Exemplo n.º 7
0
func TestServer_ValidNodeIP(t *testing.T) {
	s, _ := newTestServerWithDefaults()

	_, netblock, _ := net.ParseCIDR("10.0.0.0/24")
	s.netlimits = append(s.netlimits, netblock)

	loopback := "127.0.0.1/32"
	multicast := "224.0.0.1/32"
	inlimit := "10.0.0.1/32"
	badips := []string{
		loopback,
		multicast,
		"2.2.2.2/32",
	}
	for _, v := range badips {
		i, _, _ := net.ParseCIDR(v)
		if s.validNodeIP(i) {
			t.Errorf("validNodeIP(%s) should have been false but was true", v)
		}
	}
	log.Println(inlimit)
	okip, _, err := net.ParseCIDR(inlimit)
	if err != nil {
		panic(err)
	}
	if !s.validNodeIP(okip) {
		t.Errorf("validNodeIP(%s) should have been true but was false", okip)
	}
}
Exemplo n.º 8
0
// Subset checks if the IPs belonging to a given CIDR block is a subset of IPs
// belonging to another CIDR block.
func Subset(cidr1, cidr2 string) (bool, error) {
	if cidr1 == "" {
		return false, fmt.Errorf("missing CIDR to be checked against")
	}

	if cidr2 == "" {
		return false, fmt.Errorf("missing CIDR that needs to be checked")
	}

	ip1, net1, err := net.ParseCIDR(cidr1)
	if err != nil {
		return false, fmt.Errorf("failed to parse the CIDR to be checked against: %q", err)
	}

	zeroAddr := false
	if ip := ip1.To4(); ip != nil && ip.Equal(net.IPv4zero) {
		zeroAddr = true
	}
	if ip := ip1.To16(); ip != nil && ip.Equal(net.IPv6zero) {
		zeroAddr = true
	}

	maskLen1, _ := net1.Mask.Size()
	if !zeroAddr && maskLen1 == 0 {
		return false, fmt.Errorf("CIDR to be checked against is not in its canonical form")
	}

	ip2, net2, err := net.ParseCIDR(cidr2)
	if err != nil {
		return false, fmt.Errorf("failed to parse the CIDR that needs to be checked: %q", err)
	}

	zeroAddr = false
	if ip := ip2.To4(); ip != nil && ip.Equal(net.IPv4zero) {
		zeroAddr = true
	}
	if ip := ip2.To16(); ip != nil && ip.Equal(net.IPv6zero) {
		zeroAddr = true
	}

	maskLen2, _ := net2.Mask.Size()
	if !zeroAddr && maskLen2 == 0 {
		return false, fmt.Errorf("CIDR that needs to be checked is not in its canonical form")
	}

	// If the mask length of the CIDR that needs to be checked is smaller
	// then the mask length of the CIDR to be checked against, then the
	// former will encompass more IPs than the latter, and hence can't be a
	// subset of the latter.
	if maskLen2 < maskLen1 {
		return false, nil
	}

	belongs, err := IPBelongsToCIDR(net2.IP.String(), cidr1)
	if err != nil {
		return false, err
	}

	return belongs, nil
}
Exemplo n.º 9
0
func TestCompareIPNet(t *testing.T) {
	if CompareIPNet(nil, nil) == false {
		t.Fatalf("Failed to detect two nil net.IPNets are equal")
	}

	_, net1, _ := net.ParseCIDR("192.168.30.22/24")
	if CompareIPNet(net1, net1) == false {
		t.Fatalf("Failed to detect same net.IPNet pointers equality")
	}

	_, net2, _ := net.ParseCIDR("192.168.30.22/24")
	if CompareIPNet(net1, net2) == false {
		t.Fatalf("Failed to detect same net.IPNet object equality")
	}

	_, net3, _ := net.ParseCIDR("192.168.30.33/24")
	if CompareIPNet(net1, net3) == false {
		t.Fatalf("Failed to detect semantically equivalent net.IPNets")
	}

	_, net3, _ = net.ParseCIDR("192.168.31.33/24")
	if CompareIPNet(net2, net3) == true {
		t.Fatalf("Failed to detect different net.IPNets")
	}
}
Exemplo n.º 10
0
// RunNodeController starts the node controller
// TODO: handle node CIDR and route allocation
func (c *MasterConfig) RunNodeController() {
	s := c.ControllerManager

	// this cidr has been validated already
	_, clusterCIDR, _ := net.ParseCIDR(s.ClusterCIDR)
	_, serviceCIDR, _ := net.ParseCIDR(s.ServiceCIDR)

	controller, err := nodecontroller.NewNodeController(
		c.CloudProvider,
		clientadapter.FromUnversionedClient(c.KubeClient),
		s.PodEvictionTimeout.Duration,

		flowcontrol.NewTokenBucketRateLimiter(s.DeletingPodsQps, int(s.DeletingPodsBurst)),
		flowcontrol.NewTokenBucketRateLimiter(s.DeletingPodsQps, int(s.DeletingPodsBurst)), // upstream uses the same ones too

		s.NodeMonitorGracePeriod.Duration,
		s.NodeStartupGracePeriod.Duration,
		s.NodeMonitorPeriod.Duration,

		clusterCIDR,

		serviceCIDR,
		int(s.NodeCIDRMaskSize),

		s.AllocateNodeCIDRs,
	)
	if err != nil {
		glog.Fatalf("Unable to start node controller: %v", err)
	}

	controller.Run(s.NodeSyncPeriod.Duration)
}
Exemplo n.º 11
0
func (oc *OvsController) validateClusterNetwork(networkCIDR string, subnetsInUse []string, hostIPNets []*net.IPNet) error {
	clusterIP, clusterIPNet, err := net.ParseCIDR(networkCIDR)
	if err != nil {
		return fmt.Errorf("Failed to parse network address: %s", networkCIDR)
	}

	errList := []error{}
	for _, ipNet := range hostIPNets {
		if ipNet.Contains(clusterIP) {
			errList = append(errList, fmt.Errorf("Error: Cluster IP: %s conflicts with host network: %s", clusterIP.String(), ipNet.String()))
		}
		if clusterIPNet.Contains(ipNet.IP) {
			errList = append(errList, fmt.Errorf("Error: Host network with IP: %s conflicts with cluster network: %s", ipNet.IP.String(), networkCIDR))
		}
	}

	for _, netStr := range subnetsInUse {
		subnetIP, _, err := net.ParseCIDR(netStr)
		if err != nil {
			errList = append(errList, fmt.Errorf("Failed to parse network address: %s", netStr))
			continue
		}
		if !clusterIPNet.Contains(subnetIP) {
			errList = append(errList, fmt.Errorf("Error: Existing node subnet: %s is not part of cluster network: %s", netStr, networkCIDR))
		}
	}
	return kerrors.NewAggregate(errList)
}
Exemplo n.º 12
0
func TestCheckRouteOverlaps(t *testing.T) {
	teardown := setUp(t)
	defer teardown()

	_, bad, _ := net.ParseCIDR("10.254.44.1/24")
	_, good, _ := net.ParseCIDR("1.1.1.1/24")

	var err error

	if err = SetInterfaceIp(testIface, "10.254.44.1/24"); err != nil {
		t.Fatal(err)
	}
	if err = InterfaceUp(testIface); err != nil {
		t.Fatal(err)
	}

	err = CheckRouteOverlaps(bad)
	if err != ErrNetworkOverlaps {
		t.Fatal("network should be overlapping")
	}

	err = CheckRouteOverlaps(good)
	if err != nil {
		t.Fatal("There should be no errors here")
	}
}
Exemplo n.º 13
0
func (i *ipam) RequestAddress(rq *ipamapi.RequestAddressRequest) (res *ipamapi.RequestAddressResponse, err error) {
	Log.Debugln("RequestAddress %v", rq)
	defer func() { Log.Debugln("RequestAddress returned res: %v, err: %v", res, err) }()
	options := rq.Options
	macAddr, err := net.ParseMAC(options[netlabel.MacAddress])
	if err != nil {
		err = fmt.Errorf("Mac address not understood %v", options[netlabel.MacAddress])
		return
	}
	parts := strings.Split(rq.PoolID, "-")
	if len(parts) != 3 || parts[0] != PoolName {
		err = fmt.Errorf("Unrecognized pool ID: %s", rq.PoolID)
		return
	}
	var subnet, iprange *net.IPNet
	if _, subnet, err = net.ParseCIDR(parts[1]); err != nil {
		return
	}
	if _, iprange, err = net.ParseCIDR(parts[2]); err != nil {
		return
	}
	Log.Debugf("We should query DHCP with: mac %v, subnet %v, iprange %v", macAddr, subnet, iprange)
	res = &ipamapi.RequestAddressResponse{
		Address: "172.13.0.84/24",
		Data: map[string]string{
			"ohay": "Good day to you too, sir!",
		},
	}
	return
}
Exemplo n.º 14
0
func AssertNoOverlap(CIDRx string, CIDRy string, t *testing.T) {
	_, netX, _ := net.ParseCIDR(CIDRx)
	_, netY, _ := net.ParseCIDR(CIDRy)
	if NetworkOverlaps(netX, netY) {
		t.Errorf("%v and %v should not overlap", netX, netY)
	}
}
Exemplo n.º 15
0
Arquivo: util.go Projeto: ffung/consul
func init() {
	// Add each private block
	privateBlocks = make([]*net.IPNet, 4)

	_, block, err := net.ParseCIDR("10.0.0.0/8")
	if err != nil {
		panic(fmt.Sprintf("Bad cidr. Got %v", err))
	}
	privateBlocks[0] = block

	_, block, err = net.ParseCIDR("172.16.0.0/12")
	if err != nil {
		panic(fmt.Sprintf("Bad cidr. Got %v", err))
	}
	privateBlocks[1] = block

	_, block, err = net.ParseCIDR("192.168.0.0/16")
	if err != nil {
		panic(fmt.Sprintf("Bad cidr. Got %v", err))
	}
	privateBlocks[2] = block

	_, block, err = net.ParseCIDR("100.64.0.0/10")
	if err != nil {
		panic(fmt.Sprintf("Bad cidr. Got %v", err))
	}
	privateBlocks[3] = block
}
Exemplo n.º 16
0
func TestCheckRouteOverlaps(t *testing.T) {
	orig := networkGetRoutesFct
	defer func() {
		networkGetRoutesFct = orig
	}()
	networkGetRoutesFct = func(netlink.Link, int) ([]netlink.Route, error) {
		routesData := []string{"10.0.2.0/32", "10.0.3.0/24", "10.0.42.0/24", "172.16.42.0/24", "192.168.142.0/24"}

		routes := []netlink.Route{}
		for _, addr := range routesData {
			_, netX, _ := net.ParseCIDR(addr)
			routes = append(routes, netlink.Route{Dst: netX})
		}
		return routes, nil
	}

	_, netX, _ := net.ParseCIDR("172.16.0.1/24")
	if err := CheckRouteOverlaps(netX); err != nil {
		t.Fatal(err)
	}

	_, netX, _ = net.ParseCIDR("10.0.2.0/24")
	if err := CheckRouteOverlaps(netX); err == nil {
		t.Fatalf("10.0.2.0/24 and 10.0.2.0 should overlap but it doesn't")
	}
}
Exemplo n.º 17
0
func NewSubnetAllocator(network string, capacity uint, inUse []string) (*SubnetAllocator, error) {
	_, netIP, err := net.ParseCIDR(network)
	if err != nil {
		return nil, fmt.Errorf("Failed to parse network address: %q", network)
	}

	netMaskSize, _ := netIP.Mask.Size()
	if capacity > (32 - uint(netMaskSize)) {
		return nil, fmt.Errorf("Subnet capacity cannot be larger than number of networks available.")
	}

	amap := make(map[string]bool)
	for _, netStr := range inUse {
		_, nIp, err := net.ParseCIDR(netStr)
		if err != nil {
			fmt.Println("Failed to parse network address: ", netStr)
			continue
		}
		if !netIP.Contains(nIp.IP) {
			fmt.Println("Provided subnet doesn't belong to network: ", nIp)
			continue
		}
		amap[nIp.String()] = true
	}
	return &SubnetAllocator{network: netIP, capacity: capacity, allocMap: amap}, nil
}
Exemplo n.º 18
0
// RunNodeController starts the node controller
// TODO: handle node CIDR and route allocation
func (c *MasterConfig) RunNodeController() {
	s := c.ControllerManager

	// this cidr has been validated already
	_, clusterCIDR, _ := net.ParseCIDR(s.ClusterCIDR)
	_, serviceCIDR, _ := net.ParseCIDR(s.ServiceCIDR)

	controller, err := nodecontroller.NewNodeController(
		c.Informers.Pods().Informer(),
		c.CloudProvider,
		clientadapter.FromUnversionedClient(c.KubeClient),
		s.PodEvictionTimeout.Duration,

		s.NodeEvictionRate,
		s.SecondaryNodeEvictionRate,
		s.LargeClusterSizeThreshold,
		s.UnhealthyZoneThreshold,

		s.NodeMonitorGracePeriod.Duration,
		s.NodeStartupGracePeriod.Duration,
		s.NodeMonitorPeriod.Duration,

		clusterCIDR,
		serviceCIDR,

		int(s.NodeCIDRMaskSize),
		s.AllocateNodeCIDRs,
	)
	if err != nil {
		glog.Fatalf("Unable to start node controller: %v", err)
	}

	controller.Run()
}
Exemplo n.º 19
0
func getCurrentDeviceAddrFromIPAddr(cmdReturn []byte) (ipnets []DeviceAddr, err error) {
	//可能性1 本地回路     inet 127.0.0.1/8 scope host lo
	//可能性2 物理网卡     inet 10.169.224.99/21 brd 10.169.231.255 scope global eth0
	//可能性3 pptp虚拟网卡 inet 172.20.0.1 peer 172.20.0.2/32 scope global ppp0
	reg := regexp.MustCompile(`inet ([^ ]+).* ([^\s]+)`)
	out := reg.FindAllSubmatch(cmdReturn, -1)
	ipnets = make([]DeviceAddr, len(out))
	for i := range out {
		ip, ipnet, err := net.ParseCIDR(string(out[i][1]))
		if err != nil {
			_, ok := err.(*net.ParseError)
			if !ok {
				return nil, err
			}
			ip, ipnet, err = net.ParseCIDR(string(out[i][1]) + "/32")
			if err != nil {
				return nil, fmt.Errorf("[getCurrentDeviceAddrFromIPAddr] can not parse CIDR or IP [%s]", out[i][0])
			}
		}
		ipnets[i] = DeviceAddr{
			IP:        ip,
			IPNet:     ipnet,
			DevString: string(out[i][2]),
		}
	}
	return
}
Exemplo n.º 20
0
func init() {
	// Seed the random number generator
	rand.Seed(time.Now().UnixNano())

	// Add each private block
	privateBlocks = make([]*net.IPNet, 3)
	_, block, err := net.ParseCIDR("10.0.0.0/8")
	if err != nil {
		panic(fmt.Sprintf("Bad cidr. Got %v", err))
	}
	privateBlocks[0] = block

	_, block, err = net.ParseCIDR("172.16.0.0/12")
	if err != nil {
		panic(fmt.Sprintf("Bad cidr. Got %v", err))
	}
	privateBlocks[1] = block

	_, block, err = net.ParseCIDR("192.168.0.0/16")
	if err != nil {
		panic(fmt.Sprintf("Bad cidr. Got %v", err))
	}
	privateBlocks[2] = block

	_, block, err = net.ParseCIDR("127.0.0.0/8")
	if err != nil {
		panic(fmt.Sprintf("Bad cidr. Got %v", err))
	}
	loopbackBlock = block
}
Exemplo n.º 21
0
func (i *ipam) RequestAddress(poolID string, address net.IP, options map[string]string) (ip *net.IPNet, _ map[string]string, err error) {
	Log.Debugln("RequestAddress", poolID, address, options)
	defer func() { Log.Debugln("allocateIP returned", ip, err) }()
	// If we pass magic string "_" to weave IPAM it stores the address under its own string
	if poolID == "weavepool" { // old-style
		ip, err = i.weave.AllocateIP("_")
		return
	}
	parts := strings.Split(poolID, "-")
	if len(parts) != 3 || parts[0] != "weave" {
		err = fmt.Errorf("Unrecognized pool ID: %s", poolID)
		return
	}
	var subnet, iprange *net.IPNet
	if _, subnet, err = net.ParseCIDR(parts[1]); err != nil {
		return
	}
	if _, iprange, err = net.ParseCIDR(parts[2]); err != nil {
		return
	}
	// We are lying slightly to IPAM here: the range is not a subnet
	if ip, err = i.weave.AllocateIPInSubnet("_", iprange); err != nil {
		return
	}
	ip.Mask = subnet.Mask // fix up the subnet we lied about
	return
}
Exemplo n.º 22
0
func validateIPAMConfiguration(ipamConf *api.IPAMConfig) error {
	if ipamConf == nil {
		return grpc.Errorf(codes.InvalidArgument, "ipam configuration: cannot be empty")
	}

	_, subnet, err := net.ParseCIDR(ipamConf.Subnet)
	if err != nil {
		return grpc.Errorf(codes.InvalidArgument, "ipam configuration: invalid subnet %s", ipamConf.Subnet)
	}

	if ipamConf.Range != "" {
		ip, _, err := net.ParseCIDR(ipamConf.Range)
		if err != nil {
			return grpc.Errorf(codes.InvalidArgument, "ipam configuration: invalid range %s", ipamConf.Range)
		}

		if !subnet.Contains(ip) {
			return grpc.Errorf(codes.InvalidArgument, "ipam configuration: subnet %s does not contain range %s", ipamConf.Subnet, ipamConf.Range)
		}
	}

	if ipamConf.Gateway != "" {
		ip := net.ParseIP(ipamConf.Gateway)
		if ip == nil {
			return grpc.Errorf(codes.InvalidArgument, "ipam configuration: invalid gateway %s", ipamConf.Gateway)
		}

		if !subnet.Contains(ip) {
			return grpc.Errorf(codes.InvalidArgument, "ipam configuration: subnet %s does not contain gateway %s", ipamConf.Subnet, ipamConf.Gateway)
		}
	}

	return nil
}
Exemplo n.º 23
0
// try to get the public IP. This never accesses the network, and will not work
// if the host is behind a NAT.
func getPublicIP() (net.IP, error) {
	_, prv24, _ := net.ParseCIDR("10.0.0.0/8")
	_, prv20, _ := net.ParseCIDR("172.16.0.0/12")
	_, prv16, _ := net.ParseCIDR("192.168.0.0/16")

	ifaces, err := net.InterfaceAddrs()
	if err != nil {
		return nil, err
	}
	for _, iface := range ifaces {
		ip := iface.(*net.IPNet).IP
		if ip.IsGlobalUnicast() && !prv24.Contains(ip) && !prv20.Contains(ip) && !prv16.Contains(ip) {
			return ip, nil
		}
	}

	// we are behind a NAT
	// TODO do something better here. This is really dumb.
	resp, err := http.Get("http://myexternalip.com/raw")
	if err != nil {
		panic(err.Error())
	}
	defer resp.Body.Close()
	haha := new(bytes.Buffer)
	io.Copy(haha, resp.Body)
	fmt.Println(string(haha.Bytes()))
	toret, err := net.ResolveIPAddr("ip", strings.Trim(string(haha.Bytes()), " \n"))
	if err != nil {
		panic(err.Error())
	}

	return toret.IP, nil
}
Exemplo n.º 24
0
//IsInPrivateRange check if the requested CIDR is in the private IP range
func IsInPrivateRange(cidr string) bool {
	ip, _, err := net.ParseCIDR(cidr)
	if err != nil {
		log.Println(err)
	}

	_, ipNet2, err := net.ParseCIDR("10.0.0.0/8")
	if err != nil {
		log.Println(err)
	}

	_, ipNet3, err := net.ParseCIDR("172.16.0.0/12")
	if err != nil {
		log.Println(err)
	}

	_, ipNet4, err := net.ParseCIDR("192.168.0.0/16")
	if err != nil {
		log.Println(err)
	}

	if ipNet2.Contains(ip) || ipNet3.Contains(ip) || ipNet4.Contains(ip) {
		return true
	}

	return false
}
func TestMarshalNet(t *testing.T) {
	tv := map[string]*BasicNet{
		"test-a": NewBasicNet(),
		"test-b": NewBasicNet(),
	}

	_, n, err := net.ParseCIDR("192.168.3.0/24")
	if err != nil {
		t.Fatalf("%v", err)
	}
	tv["test-a"].Add(n)

	_, n, err = net.ParseCIDR("192.168.7.0/24")
	if err != nil {
		t.Fatalf("%v", err)
	}
	tv["test-a"].Add(n)

	out, err := json.Marshal(tv)
	if err != nil {
		t.Fatalf("%v", err)
	}

	var tvPrime map[string]*BasicNet
	err = json.Unmarshal(out, &tvPrime)
	if err != nil {
		t.Fatalf("%v", err)
	}
}
Exemplo n.º 26
0
// ValidateClusterNetwork tests if required fields in the ClusterNetwork are set.
func ValidateClusterNetwork(clusterNet *sdnapi.ClusterNetwork) field.ErrorList {
	allErrs := validation.ValidateObjectMeta(&clusterNet.ObjectMeta, false, oapi.MinimalNameRequirements, field.NewPath("metadata"))

	clusterIP, clusterIPNet, err := net.ParseCIDR(clusterNet.Network)
	if err != nil {
		allErrs = append(allErrs, field.Invalid(field.NewPath("network"), clusterNet.Network, err.Error()))
	} else {
		ones, bitSize := clusterIPNet.Mask.Size()
		if uint32(bitSize-ones) <= clusterNet.HostSubnetLength {
			allErrs = append(allErrs, field.Invalid(field.NewPath("hostSubnetLength"), clusterNet.HostSubnetLength, "subnet length is greater than cluster Mask"))
		}
	}

	serviceIP, serviceIPNet, err := net.ParseCIDR(clusterNet.ServiceNetwork)
	if err != nil {
		allErrs = append(allErrs, field.Invalid(field.NewPath("serviceNetwork"), clusterNet.ServiceNetwork, err.Error()))
	}

	if (clusterIPNet != nil) && (serviceIP != nil) && clusterIPNet.Contains(serviceIP) {
		allErrs = append(allErrs, field.Invalid(field.NewPath("serviceNetwork"), clusterNet.ServiceNetwork, "service network overlaps with cluster network"))
	}
	if (serviceIPNet != nil) && (clusterIP != nil) && serviceIPNet.Contains(clusterIP) {
		allErrs = append(allErrs, field.Invalid(field.NewPath("network"), clusterNet.Network, "cluster network overlaps with service network"))
	}

	return allErrs
}
Exemplo n.º 27
0
func checkRouteOverlaps(routes string, dockerNetwork *net.IPNet) error {
	utils.Debugf("Routes:\n\n%s", routes)
	for _, line := range strings.Split(routes, "\n") {
		if strings.Trim(line, "\r\n\t ") == "" || strings.Contains(line, "default") {
			continue
		}
		_, network, err := net.ParseCIDR(strings.Split(line, " ")[0])
		if err != nil {
			// is this a mask-less IP address?
			if ip := net.ParseIP(strings.Split(line, " ")[0]); ip == nil {
				// fail only if it's neither a network nor a mask-less IP address
				return fmt.Errorf("Unexpected ip route output: %s (%s)", err, line)
			} else {
				_, network, err = net.ParseCIDR(ip.String() + "/32")
				if err != nil {
					return err
				}
			}
		}
		if err == nil && network != nil {
			if networkOverlaps(dockerNetwork, network) {
				return fmt.Errorf("Network %s is already routed: '%s'", dockerNetwork, line)
			}
		}
	}
	return nil
}
Exemplo n.º 28
0
Arquivo: path.go Projeto: osrg/gobgp
func (p *Path) ToLocal() *Path {
	nlri := p.GetNlri()
	f := p.GetRouteFamily()
	switch f {
	case bgp.RF_IPv4_VPN:
		n := nlri.(*bgp.LabeledVPNIPAddrPrefix)
		_, c, _ := net.ParseCIDR(n.IPPrefix())
		ones, _ := c.Mask.Size()
		nlri = bgp.NewIPAddrPrefix(uint8(ones), c.IP.String())
	case bgp.RF_IPv6_VPN:
		n := nlri.(*bgp.LabeledVPNIPv6AddrPrefix)
		_, c, _ := net.ParseCIDR(n.IPPrefix())
		ones, _ := c.Mask.Size()
		nlri = bgp.NewIPAddrPrefix(uint8(ones), c.IP.String())
	default:
		return p
	}
	path := NewPath(p.OriginInfo().source, nlri, p.IsWithdraw, p.GetPathAttrs(), p.OriginInfo().timestamp, false)
	path.delPathAttr(bgp.BGP_ATTR_TYPE_EXTENDED_COMMUNITIES)
	if f == bgp.RF_IPv4_VPN {
		nh := path.GetNexthop()
		path.delPathAttr(bgp.BGP_ATTR_TYPE_MP_REACH_NLRI)
		path.setPathAttr(bgp.NewPathAttributeNextHop(nh.String()))
	}
	return path
}
Exemplo n.º 29
0
func parseNetworkOptions(option options.Generic) (*networkConfiguration, error) {
	var err error
	config := &networkConfiguration{}

	// Parse generic label first, config will be re-assigned
	if genData, ok := option[netlabel.GenericData]; ok && genData != nil {
		if config, err = parseNetworkGenericOptions(genData); err != nil {
			return nil, err
		}
	}

	// Process VLAN related options
	if _, ok := option["vlanid"]; ok {
		config.VlanId = int(option["vlanid"].(float64))
	}
	if _, ok := option["ifname"]; ok {
		config.IfName = option["ifname"].(string)
	}
	if _, ok := option["AddressIPv4"]; ok {

		addressIPv4 := option["AddressIPv4"].(string)
		if addressIPv4 != "" {
			ip, netv4, err := net.ParseCIDR(option["AddressIPv4"].(string))
			if err != nil {
				return nil, err
			}
			bipNet := &net.IPNet{
				IP:   ip,
				Mask: netv4.Mask,
			}

			config.AddressIPv4 = bipNet
			logrus.Infof("config.AddressIPv4: %#v", config.AddressIPv4)
		}
	}
	if _, ok := option["FixedCIDR"]; ok {
		fixedCIDR := option["FixedCIDR"].(string)
		if fixedCIDR != "" {
			_, fCIDR, err := net.ParseCIDR(option["FixedCIDR"].(string))
			if err != nil {
				return nil, err
			}
			config.FixedCIDR = fCIDR
			logrus.Infof("config.FixedCIDR: %#v", config.FixedCIDR)
		}
	}

	// Process well-known labels next
	if _, ok := option[netlabel.EnableIPv6]; ok {
		config.EnableIPv6 = option[netlabel.EnableIPv6].(bool)
	}

	// Finally validate the configuration
	if err = config.Validate(); err != nil {
		return nil, err
	}

	return config, nil
}
Exemplo n.º 30
0
Arquivo: natpmp.go Projeto: rht/bssim
func natpmp_PotentialGateways() ([]net.IP, error) {
	_, ipNet_10, err := net.ParseCIDR("10.0.0.0/8")
	if err != nil {
		panic(err)
	}

	_, ipNet_172_16, err := net.ParseCIDR("172.16.0.0/12")
	if err != nil {
		panic(err)
	}

	_, ipNet_192_168, err := net.ParseCIDR("192.168.0.0/16")
	if err != nil {
		panic(err)
	}

	ifaces, err := net.Interfaces()
	if err != nil {
		return nil, err
	}

	var ips []net.IP

	for _, iface := range ifaces {
		addrs, err := iface.Addrs()
		if err != nil {
			return nil, err
		}

		for _, addr := range addrs {
			switch x := addr.(type) {
			case *net.IPNet:
				var ipNet *net.IPNet
				if ipNet_10.Contains(x.IP) {
					ipNet = ipNet_10
				} else if ipNet_172_16.Contains(x.IP) {
					ipNet = ipNet_172_16
				} else if ipNet_192_168.Contains(x.IP) {
					ipNet = ipNet_192_168
				}

				if ipNet != nil {
					ip := x.IP.Mask(x.Mask)
					ip = ip.To4()
					if ip != nil {
						ip[3] = ip[3] | 0x01
						ips = append(ips, ip)
					}
				}
			}
		}
	}

	if len(ips) == 0 {
		return nil, ErrNoNATFound
	}

	return ips, nil
}