Beispiel #1
0
func TestRouteTableCMD(t *testing.T) {
	cmds := [][]string{
		generateCMD(net.IPNet{
			net.IPv4(166, 111, 8, 28),
			net.IPv4Mask(255, 255, 255, 0),
		}, net.IPv4(166, 111, 8, 1), true),
		generateCMD(net.IPNet{
			net.IPv4(0, 0, 0, 0),
			net.IPv4Mask(0, 0, 0, 0),
		}, net.IPv4(166, 111, 8, 1), false),
		generateCMD(net.IPNet{
			net.IPv4(10, 0, 0, 0),
			net.IPv4Mask(255, 255, 255, 255),
		}, net.IPv4(166, 111, 8, 1), false),
	}
	assert_cmd := func(cmd []string, str string) {
		if strings.Join(cmd, " ") != str {
			t.Errorf("Error route CMD, expect %s\n", str)
		}
	}
	if runtime.GOOS == "darwin" {
		assert_cmd(cmds[0], "route delete -net 166.111.8.28 166.111.8.1 255.255.255.0")
		assert_cmd(cmds[1], "route add -net 0.0.0.0 166.111.8.1 0.0.0.0")
		assert_cmd(cmds[2], "route add -net 10.0.0.0 166.111.8.1 255.255.255.255")
	} else if runtime.GOOS == "linux" {
		assert_cmd(cmds[0], "ip route del 166.111.8.28/24")
		assert_cmd(cmds[1], "ip route add 0.0.0.0/0 via 166.111.8.1")
		assert_cmd(cmds[2], "ip route add 10.0.0.0/32 via 166.111.8.1")
	}
}
Beispiel #2
0
// Make sure we drop a worker after a connection is severed
func TestWorkerDrop(t *testing.T) {
	// Start up server listening on our channel based connection
	s := NewServerState()

	conn := newChannelReadWriter()
	mc := NewMessageConn(conn, time.Duration(10)*time.Second)

	go s.handleConnection(mc)

	// Now lets connect a worker
	ws := WorkerState{
		Host: "smith",
		Addrs: []net.IPNet{
			{net.IPv4(192, 1, 1, 1), net.IPv4Mask(255, 255, 255, 0)},
		},
		Port:     56,
		Capacity: 1,
		Load:     0,
	}

	clientAddrs := []net.IPNet{
		{net.IPv4(192, 1, 1, 2), net.IPv4Mask(255, 255, 255, 0)},
	}

	mc.Send(ws)

	// We block until we are able to find a worker, which means our connection
	// was successful
	var wr WorkerResponse

	for {
		var err error

		wr, err = s.sch.findWorker(clientAddrs)

		if err == nil {
			break
		}
	}

	// Make sure we have the right host back
	if wr.Host != "smith" {
		t.Error("Bad worker")
	}

	// Now lets close the connection which should drop the worker
	conn.Close()

	// Now lets wait for that drop
	for {
		var err error

		_, err = s.sch.findWorker(clientAddrs)

		if err != nil {
			break
		}
	}
}
Beispiel #3
0
func (s *NetworkSuite) TestFilterBridgeAddresses(c *gc.C) {
	lxcFakeNetConfig := filepath.Join(c.MkDir(), "lxc-net")
	// We create an LXC bridge named "foobar", and then put 10.0.3.1,
	// 10.0.3.4 and 10.0.3.5/24 on that bridge.
	// We also put 10.0.4.1 and 10.0.5.1/24 onto whatever bridge LXD is
	// configured to use.
	netConf := []byte(`
  # comments ignored
LXC_BR= ignored
LXC_ADDR = "fooo"
 LXC_BRIDGE = " foobar " # detected, spaces stripped
anything else ignored
LXC_BRIDGE="ignored"`[1:])
	err := ioutil.WriteFile(lxcFakeNetConfig, netConf, 0644)
	c.Assert(err, jc.ErrorIsNil)
	s.PatchValue(&network.InterfaceByNameAddrs, func(name string) ([]net.Addr, error) {
		if name == "foobar" {
			return []net.Addr{
				&net.IPAddr{IP: net.IPv4(10, 0, 3, 1)},
				&net.IPAddr{IP: net.IPv4(10, 0, 3, 4)},
				// Try a CIDR 10.0.3.5/24 as well.
				&net.IPNet{IP: net.IPv4(10, 0, 3, 5), Mask: net.IPv4Mask(255, 255, 255, 0)},
			}, nil
		} else if name == network.DefaultLXDBridge {
			return []net.Addr{
				&net.IPAddr{IP: net.IPv4(10, 0, 4, 1)},
				// Try a CIDR 10.0.5.1/24 as well.
				&net.IPNet{IP: net.IPv4(10, 0, 5, 1), Mask: net.IPv4Mask(255, 255, 255, 0)},
			}, nil
		}
		c.Fatalf("unknown bridge name: %q", name)
		return nil, nil
	})
	s.PatchValue(&network.LXCNetDefaultConfig, lxcFakeNetConfig)

	inputAddresses := network.NewAddresses(
		"127.0.0.1",
		"2001:db8::1",
		"10.0.0.1",
		"10.0.3.1",  // filtered (directly as IP)
		"10.0.3.3",  // filtered (by the 10.0.3.5/24 CIDR)
		"10.0.3.5",  // filtered (directly)
		"10.0.3.4",  // filtered (directly)
		"10.0.4.1",  // filtered (directly from LXD bridge)
		"10.0.5.10", // filtered (from LXD bridge, 10.0.5.1/24)
		"10.0.6.10", // unfiltered
		"192.168.123.42",
	)
	filteredAddresses := network.NewAddresses(
		"127.0.0.1",
		"2001:db8::1",
		"10.0.0.1",
		"10.0.6.10",
		"192.168.123.42",
	)
	c.Assert(network.FilterBridgeAddresses(inputAddresses), jc.DeepEquals, filteredAddresses)
}
Beispiel #4
0
// Given a netmask, calculates the number of available hosts
func NetworkSize(mask net.IPMask) int32 {
	m := net.IPv4Mask(0, 0, 0, 0)
	for i := 0; i < net.IPv4len; i++ {
		m[i] = ^mask[i]
	}
	return int32(binary.BigEndian.Uint32(m)) + 1
}
func TestParseInterfaceStanzaStaticPostUp(t *testing.T) {
	options := []string{
		"address 192.168.1.100",
		"netmask 255.255.255.0",
		"post-up route add gw 192.168.1.1 -net 192.168.1.0 netmask 255.255.255.0",
	}
	expect := []route{
		{
			destination: net.IPNet{
				IP:   net.IPv4(192, 168, 1, 0),
				Mask: net.IPv4Mask(255, 255, 255, 0),
			},
			gateway: net.IPv4(192, 168, 1, 1),
		},
	}

	iface, err := parseInterfaceStanza([]string{"eth", "inet", "static"}, options)
	if err != nil {
		t.FailNow()
	}
	static, ok := iface.configMethod.(configMethodStatic)
	if !ok {
		t.FailNow()
	}
	if !reflect.DeepEqual(static.routes, expect) {
		t.FailNow()
	}
}
Beispiel #6
0
// Parse 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])
}
Beispiel #7
0
func TestAddRouteSourceSelection(t *testing.T) {
	tstIp := "127.1.1.1"
	tl := testLink{name: "tstEth", linkType: "dummy"}

	addLink(t, tl.name, tl.linkType)
	defer deleteLink(t, tl.name)

	ip := net.ParseIP(tstIp)
	mask := net.IPv4Mask(255, 255, 255, 255)
	ipNet := &net.IPNet{IP: ip, Mask: mask}

	iface, err := net.InterfaceByName(tl.name)
	if err != nil {
		t.Fatalf("Lost created link %#v", tl)
	}

	if err := NetworkLinkAddIp(iface, ip, ipNet); err != nil {
		t.Fatalf("Could not add IP address %s to interface %#v: %s", ip.String(), iface, err)
	}

	upLink(t, tl.name)
	defer downLink(t, tl.name)

	if err := AddRoute("127.0.0.0/8", tstIp, "", tl.name); err != nil {
		t.Fatalf("Failed to add route with source address")
	}
}
Beispiel #8
0
func TestAddDelNetworkIp(t *testing.T) {
	if testing.Short() {
		return
	}

	ifaceName := "lo"
	ip := net.ParseIP("127.0.1.1")
	mask := net.IPv4Mask(255, 255, 255, 255)
	ipNet := &net.IPNet{IP: ip, Mask: mask}

	iface, err := net.InterfaceByName(ifaceName)
	if err != nil {
		t.Skip("No 'lo' interface; skipping tests")
	}

	if err := NetworkLinkAddIp(iface, ip, ipNet); err != nil {
		t.Fatalf("Could not add IP address %s to interface %#v: %s", ip.String(), iface, err)
	}

	if !ipAssigned(iface, ip) {
		t.Fatalf("Could not locate address '%s' in lo address list.", ip.String())
	}

	if err := NetworkLinkDelIp(iface, ip, ipNet); err != nil {
		t.Fatalf("Could not delete IP address %s from interface %#v: %s", ip.String(), iface, err)
	}

	if ipAssigned(iface, ip) {
		t.Fatalf("Located address '%s' in lo address list after removal.", ip.String())
	}
}
Beispiel #9
0
func (S) TestUnmarshalRoundtrip(c *C) {
	for i, t := range []encoding.BinaryMarshaler{
		Bool(true),
		Bool(false),
		Integers{Integer{IntegerOpGt, 1}},
		Integers{},
		Strings{"foo", "bar"},
		Strings{},
		(*Regexp)(regexp.MustCompile(`\d`)),
		(*Regexp)(regexp.MustCompile("")),
		CIDRs{
			net.IPNet{IP: net.IPv4(127, 0, 0, 1), Mask: net.IPv4Mask(255, 255, 255, 0)},
			net.IPNet{IP: net.IPv6loopback, Mask: net.CIDRMask(8, 16*8)},
		},
		CIDRs{},
	} {
		c.Log(i)
		info := Commentf("i = %d", i)

		b, err := t.MarshalBinary()
		c.Assert(err, IsNil, info)

		parsed, err := UnmarshalBinary(b)
		c.Assert(err, IsNil, info)
		c.Assert(parsed, DeepEquals, t)
	}
}
Beispiel #10
0
// ParseIPv4Mask 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 {
		if len(s) != 8 {
			return nil
		}
		// net.IPMask.String() actually outputs things like ffffff00
		// so write a horrible parser for that as well  :-(
		m := []int{}
		for i := 0; i < 4; i++ {
			b := "0x" + s[2*i:2*i+2]
			d, err := strconv.ParseInt(b, 0, 0)
			if err != nil {
				return nil
			}
			m = append(m, int(d))
		}
		s := fmt.Sprintf("%d.%d.%d.%d", m[0], m[1], m[2], m[3])
		mask = net.ParseIP(s)
		if mask == nil {
			return nil
		}
	}
	return net.IPv4Mask(mask[12], mask[13], mask[14], mask[15])
}
Beispiel #11
0
func TestNetworkSize(t *testing.T) {
	mask := net.IPv4Mask(255, 255, 255, 0)
	result := NetworkSize(mask)
	expected := int32(256)
	if result != expected {
		t.Fatalf("got %v, expected %v\n", result, expected)
	}
}
Beispiel #12
0
func HexToIpv4Mask(hex_mask string) (mask net.IPMask, err error) {
	a, err := hex.DecodeString(hex_mask)
	if err != nil {
		return
	}

	mask = net.IPv4Mask(a[0], a[1], a[2], a[3])
	return
}
Beispiel #13
0
// NetList : subnet helper function
func NetList(ip net.IP, subnet net.IP) (IPlist []net.IP) {
	//ip, ipnet, err := net.ParseCIDR(cidrNet)
	mask := net.IPv4Mask(subnet[0], subnet[1], subnet[2], subnet[3])
	ipnet := net.IPNet{ip, mask}
	for ip := ip.Mask(mask); ipnet.Contains(ip); incIP(ip) {
		IPlist = append(IPlist, net.IP{ip[0], ip[1], ip[2], ip[3]})
	}
	return
}
func main() {
	const logDirEnvVar = "FAKE_LOG_DIR"
	logDir := os.Getenv(logDirEnvVar)
	if logDir == "" {
		log.Fatalf("missing required arg %q", logDirEnvVar)
	}

	stdin, err := ioutil.ReadAll(os.Stdin)
	if err != nil {
		log.Fatalf("error reading stdin bytes: %s", err)
	}

	env, err := parseEnviron(os.Environ())
	if err != nil {
		log.Fatalf("unable to parse environment: %s", err)
	}

	args := os.Args

	logInfo := LogInfo{
		Args:  args,
		Env:   env,
		Stdin: string(stdin),
	}

	logBytes, err := json.Marshal(logInfo)
	if err != nil {
		log.Fatalf("unable to json marshal log info")
	}

	logFilePath := filepath.Join(logDir, filepath.Base(args[0])+".log")
	err = ioutil.WriteFile(logFilePath, logBytes, 0600)
	if err != nil {
		log.Fatalf("unable to write log file: %s", err)
	}

	result := types.Result{
		IP4: &types.IPConfig{
			IP: net.IPNet{
				IP:   net.ParseIP("169.254.1.2"),
				Mask: net.IPv4Mask(255, 255, 255, 0),
			},
		},
	}

	outputBytes, err := json.Marshal(result)
	if err != nil {
		log.Fatalf("unable to json marshal result data: %s", err)
	}

	_, err = os.Stdout.Write(outputBytes)
	if err != nil {
		log.Fatalf("unable to write result to stdout: %s", err)
	}

}
func printFailoverIp(failoverIp, localIp string) {
	var failover api.Failover
	if err := api.Get("/failover/"+failoverIp, &failover); err != nil {
		fatal(err)
	}

	a := net.ParseIP(failover.Netmask)
	_, bits := net.IPv4Mask(a[0], a[1], a[2], a[3]).Size()
	fmt.Printf(format, failover.Ip, bits, failover.Active_server_ip, failover.Server_ip, failover.Server_number, dutyMark(failover.Active_server_ip.String(), localIp))
}
Beispiel #16
0
func TestParseInterfaceStanzaStaticPostUp(t *testing.T) {
	for _, tt := range []struct {
		options []string
		expect  []route
	}{
		{
			options: []string{
				"address 192.168.1.100",
				"netmask 255.255.255.0",
				"post-up route add gw 192.168.1.1 -net 192.168.1.0 netmask 255.255.255.0",
			},
			expect: []route{
				{
					destination: net.IPNet{
						IP:   net.IPv4(192, 168, 1, 0),
						Mask: net.IPv4Mask(255, 255, 255, 0),
					},
					gateway: net.IPv4(192, 168, 1, 1),
				},
			},
		},
		{
			options: []string{
				"address 192.168.1.100",
				"netmask 255.255.255.0",
				"post-up route add gw 192.168.1.1 -net 192.168.1.0/24 || true",
			},
			expect: []route{
				{
					destination: func() net.IPNet {
						if _, net, err := net.ParseCIDR("192.168.1.0/24"); err == nil {
							return *net
						} else {
							panic(err)
						}
					}(),
					gateway: net.IPv4(192, 168, 1, 1),
				},
			},
		},
	} {
		iface, err := parseInterfaceStanza([]string{"eth", "inet", "static"}, tt.options)
		if err != nil {
			t.Fatalf("bad error (%+v): want nil, got %s\n", tt, err)
		}
		static, ok := iface.configMethod.(configMethodStatic)
		if !ok {
			t.Fatalf("bad config method (%+v): want configMethodStatic, got %T\n", tt, iface.configMethod)
		}
		if !reflect.DeepEqual(static.routes, tt.expect) {
			t.Fatalf("bad routes (%+v): want %#v, got %#v\n", tt, tt.expect, static.routes)
		}
	}
}
Beispiel #17
0
func IPMaskStringToCIDR(netmask string) string {
	netmaskList := strings.Split(netmask, ".")
	var mint []int
	for _, v := range netmaskList {
		strv, _ := strconv.Atoi(v)
		mint = append(mint, strv)
	}
	myIPMask := net.IPv4Mask(byte(mint[0]), byte(mint[1]), byte(mint[2]), byte(mint[3]))
	ones, _ := myIPMask.Size()
	return strconv.Itoa(ones)
}
Beispiel #18
0
Datei: kvm.go Projekt: nhlfr/rkt
func addRoute(link netlink.Link, podIP net.IP) error {
	route := netlink.Route{
		LinkIndex: link.Attrs().Index,
		Scope:     netlink.SCOPE_LINK,
		Dst: &net.IPNet{
			IP:   podIP,
			Mask: net.IPv4Mask(0xff, 0xff, 0xff, 0xff),
		},
	}
	return netlink.RouteAdd(&route)
}
Beispiel #19
0
// This function returns true if and only if the passed IP address belongs to
// one of the ranges reserved in RFC 1918 for use in private networks
//
// This function is only part of this package as it is used internally and is
// public as it is deemed useful for developers to assertain whether or not a
// given external IP address such as one returned by GetConnectionStatus is
// public or not and as creating a standalone package just for this one function
// seemed excessive.
func IsPrivateIPAddress(addr net.IP) bool {
	ip4 := addr.To4()
	if ip4 == nil || !ip4.IsGlobalUnicast() {
		return false
	}
	var (
		aAddr = net.IPv4(10, 0, 0, 0)
		aMask = net.IPv4Mask(255, 0, 0, 0)

		bAddr = net.IPv4(172, 16, 0, 0)
		bMask = net.IPv4Mask(255, 240, 0, 0)

		cAddr = net.IPv4(192, 168, 0, 0)
		cMask = net.IPv4Mask(255, 255, 0, 0)
	)

	return ip4.Mask(aMask).Equal(aAddr) ||
		ip4.Mask(bMask).Equal(bAddr) ||
		ip4.Mask(cMask).Equal(cAddr)
}
Beispiel #20
0
func (S) TestCIDRsUnmarshalInvalid(c *C) {
	for _, t := range []struct {
		d string
		b []byte
	}{
		{"short ipv4", mustMarshal(CIDRs{net.IPNet{IP: net.IPv4(127, 0, 0, 1), Mask: net.IPv4Mask(255, 255, 255, 0)}})[:5]},
		{"short ipv6", mustMarshal(CIDRs{net.IPNet{IP: net.IPv6loopback, Mask: net.CIDRMask(8, 16*8)}})[:6]},
	} {
		c.Assert(new(CIDRs).UnmarshalBinary(t.b), Not(IsNil), Commentf(t.d))
	}
}
Beispiel #21
0
// Given a netmask, calculates the number of available hosts
func networkSize(mask net.IPMask) (int32, error) {
	m := net.IPv4Mask(0, 0, 0, 0)
	for i := 0; i < net.IPv4len; i++ {
		m[i] = ^mask[i]
	}
	buf := bytes.NewBuffer(m)
	var n int32
	if err := binary.Read(buf, binary.BigEndian, &n); err != nil {
		return 0, err
	}
	return n + 1, nil
}
Beispiel #22
0
func TestBroadcast(t *testing.T) {
	var (
		self = net.IPv4(10, 0, 42, 1)
		mask = net.IPv4Mask(255, 255, 255, 0)
		brd  = net.IPv4(10, 0, 42, 255)
	)

	ifce, err := NewTAP("test")
	if err != nil {
		t.Fatalf("creating TAP error: %v\n", err)
	}

	setupIfce(t, net.IPNet{IP: self, Mask: mask}, ifce.Name())
	startBroadcast(t, brd)

	dataCh := make(chan []byte, 8)
	startRead(dataCh, ifce)

	timeout := time.NewTimer(8 * time.Second).C

readFrame:
	for {
		select {
		case buffer := <-dataCh:
			ethertype := waterutil.MACEthertype(buffer)
			if ethertype != waterutil.IPv4 {
				continue readFrame
			}
			if !waterutil.IsBroadcast(waterutil.MACDestination(buffer)) {
				continue readFrame
			}
			packet := waterutil.MACPayload(buffer)
			if !waterutil.IsIPv4(packet) {
				continue readFrame
			}
			if !waterutil.IPv4Source(packet).Equal(self) {
				continue readFrame
			}
			if !waterutil.IPv4Destination(packet).Equal(brd) {
				continue readFrame
			}
			if waterutil.IPv4Protocol(packet) != waterutil.ICMP {
				continue readFrame
			}
			t.Logf("received broadcast frame: %#v\n", buffer)
			break readFrame
		case <-timeout:
			t.Fatal("Waiting for broadcast packet timeout")
		}
	}
}
Beispiel #23
0
func GetLocalNets() (nets []Net) {
	const MAXINTERFACES = 16
	ipaddrs := make([]int, MAXINTERFACES)
	ipmasks := make([]int, MAXINTERFACES)
	ipn := C.GetLocalNets((*C.long)(unsafe.Pointer(&ipaddrs[0])), (*C.long)(unsafe.Pointer(&ipmasks[0])))
	nets = make([]Net, 0)
	for i := 0; i < int(ipn); i++ {
		ip := net.IPv4(byte(ipaddrs[i]), byte(ipaddrs[i]>>8), byte(ipaddrs[i]>>16), byte(ipaddrs[i]>>24))
		mask := net.IPv4Mask(byte(ipmasks[i]), byte(ipmasks[i]>>8), byte(ipmasks[i]>>16), byte(ipmasks[i]>>24))
		n := Net{IP: ip, Subnet: ip.Mask(mask)}
		nets = append(nets, n)
	}
	return
}
func updateFailoverIp(failoverIp, activeServerIp, localIp string) {
	var (
		failover api.Failover
		params   = url.Values{}
	)
	params.Add("active_server_ip", activeServerIp)
	if err := api.Post("/failover/"+failoverIp, params, &failover); err != nil {
		fatal(err)
	}

	a := net.ParseIP(failover.Netmask)
	_, bits := net.IPv4Mask(a[0], a[1], a[2], a[3]).Size()
	fmt.Printf(format, failover.Ip, bits, failover.Active_server_ip, failover.Server_ip, failover.Server_number, dutyMark(failover.Active_server_ip.String(), localIp))
}
func printAllFailoverIPs(failoverIp, localIp string) {
	var ips []api.Failover
	if err := api.Get("/failover", &ips); err != nil {
		fatal(err)
	}

	for _, d := range ips {
		a := net.ParseIP(d.Netmask)
		_, bits := net.IPv4Mask(a[0], a[1], a[2], a[3]).Size()
		mark := ' '
		if d.Ip.String() == failoverIp {
			mark = dutyMark(d.Active_server_ip.String(), localIp)
		}
		fmt.Printf(format, d.Ip, bits, d.Active_server_ip, d.Server_ip, d.Server_number, mark)
	}
}
Beispiel #26
0
func TestGetMatchingIP(t *testing.T) {
	examples := []MatchExample{
		{
			// Basic hello world example
			exp: net.IPNet{net.IPv4(192, 1, 1, 25), net.IPv4Mask(255, 255, 255, 0)},
			err: nil,
			as: []net.IPNet{
				{net.IPv4(192, 1, 1, 4), net.IPv4Mask(255, 255, 255, 0)},
			},
			bs: []net.IPNet{
				{net.IPv4(192, 1, 1, 25), net.IPv4Mask(255, 255, 255, 0)},
			}},
		{
			// They are different 192 networks, but matching 172
			exp: net.IPNet{net.IPv4(172, 16, 2, 26), net.IPv4Mask(255, 255, 0, 0)},
			err: nil,
			as: []net.IPNet{
				{net.IPv4(192, 1, 1, 4), net.IPv4Mask(255, 255, 255, 0)},
				{net.IPv4(172, 16, 2, 6), net.IPv4Mask(255, 255, 0, 0)},
			},
			bs: []net.IPNet{
				{net.IPv4(192, 2, 2, 24), net.IPv4Mask(255, 255, 255, 0)},
				{net.IPv4(172, 16, 2, 26), net.IPv4Mask(255, 255, 0, 0)},
			}},
	}

	for _, example := range examples {
		res, err := getMatchingIP(example.as, example.bs)

		if example.err != nil {
			if err == nil {
				t.Errorf("Got no error when we should of gotten one")
			}
		} else {
			if err != nil {
				t.Errorf("Did not match ", err)
			}

			if !reflect.DeepEqual(res, example.exp) {
				t.Errorf("Bad IP match %s != %s", res.String(), example.exp.String())
			}
		}
	}
}
func TestParseInterfaceStanzaStaticAddress(t *testing.T) {
	options := []string{"address 192.168.1.100", "netmask 255.255.255.0"}
	expect := net.IPNet{
		IP:   net.IPv4(192, 168, 1, 100),
		Mask: net.IPv4Mask(255, 255, 255, 0),
	}

	iface, err := parseInterfaceStanza([]string{"eth", "inet", "static"}, options)
	if err != nil {
		t.FailNow()
	}
	static, ok := iface.configMethod.(configMethodStatic)
	if !ok {
		t.FailNow()
	}
	if !reflect.DeepEqual(static.address, expect) {
		t.FailNow()
	}
}
Beispiel #28
0
func GetLans() ([]*net.IPNet, error) {
	ifaces, err := net.Interfaces()
	if err != nil {
		return nil, err
	}

	nets := make([]*net.IPNet, 0, len(ifaces))

	aList, err := getAdapterList()
	if err != nil {
		return nil, err
	}

	for _, ifi := range ifaces {
		for ai := aList; ai != nil; ai = ai.Next {
			index := ai.Index

			if ifi.Index == int(index) {
				ipl := &ai.IpAddressList
				for ; ipl != nil; ipl = ipl.Next {
					ipStr := strings.Trim(string(ipl.IpAddress.String[:]), "\x00")
					maskStr := strings.Trim(string(ipl.IpMask.String[:]), "\x00")
					ip := net.ParseIP(ipStr)
					maskip := net.ParseIP(maskStr)
					if ip.IsUnspecified() || maskip.IsUnspecified() {
						continue
					}
					nets = append(nets, &net.IPNet{
						IP: ip,
						Mask: net.IPv4Mask(
							maskip[net.IPv6len-net.IPv4len],
							maskip[net.IPv6len-net.IPv4len+1],
							maskip[net.IPv6len-net.IPv4len+2],
							maskip[net.IPv6len-net.IPv4len+3],
						),
					})
				}
			}
		}
	}
	return nets, err
}
Beispiel #29
0
func (s *NetworkSuite) TestFilterLXCAddresses(c *gc.C) {
	lxcFakeNetConfig := filepath.Join(c.MkDir(), "lxc-net")
	netConf := []byte(`
  # comments ignored
LXC_BR= ignored
LXC_ADDR = "fooo"
 LXC_BRIDGE = " foobar " # detected, spaces stripped
anything else ignored
LXC_BRIDGE="ignored"`[1:])
	err := ioutil.WriteFile(lxcFakeNetConfig, netConf, 0644)
	c.Assert(err, jc.ErrorIsNil)
	s.PatchValue(&network.InterfaceByNameAddrs, func(name string) ([]net.Addr, error) {
		c.Assert(name, gc.Equals, "foobar")
		return []net.Addr{
			&net.IPAddr{IP: net.IPv4(10, 0, 3, 1)},
			&net.IPAddr{IP: net.IPv4(10, 0, 3, 4)},
			// Try a CIDR 10.0.3.5/24 as well.
			&net.IPNet{IP: net.IPv4(10, 0, 3, 5), Mask: net.IPv4Mask(255, 255, 255, 0)},
		}, nil
	})
	s.PatchValue(&network.LXCNetDefaultConfig, lxcFakeNetConfig)

	inputAddresses := network.NewAddresses(
		"127.0.0.1",
		"2001:db8::1",
		"10.0.0.1",
		"10.0.3.1", // filtered (directly as IP)
		"10.0.3.3", // filtered (by the 10.0.3.5/24 CIDR)
		"10.0.3.5", // filtered (directly)
		"10.0.3.4", // filtered (directly)
		"192.168.123.42",
	)
	filteredAddresses := network.NewAddresses(
		"127.0.0.1",
		"2001:db8::1",
		"10.0.0.1",
		"192.168.123.42",
	)
	c.Assert(network.FilterLXCAddresses(inputAddresses), jc.DeepEquals, filteredAddresses)
}
Beispiel #30
0
func TestPortSelection(t *testing.T) {
	// Create the localhost IP net
	ipnet := &net.IPNet{
		IP:   net.IPv4(127, 0, 0, 1),
		Mask: net.IPv4Mask(0xff, 0, 0, 0),
	}
	// Make sure bootstrappers can select unused ports
	for i := 0; i < len(config.BootPorts); i++ {
		if bs, _, err := New(ipnet, []byte("magic"), big.NewInt(int64(i)), 11111); err != nil {
			t.Fatalf("failed to create bootstrapper: %v.", err)
		} else {
			if err := bs.Boot(); err != nil {
				t.Fatalf("failed to boot bootstrapper: %v.", err)
			}
			defer bs.Terminate()
		}
	}
	// Ensure failure after all ports are used
	if _, _, err := New(ipnet, []byte("magic"), big.NewInt(333), 11111); err == nil {
		t.Errorf("bootstrapper created even though no ports were available.")
	}
}