ref: Complete the move of netconfig and netstate to release.go.x.lib.
This involves deleting the old copies and updating import paths.
Change-Id: I562f423b8253af37a5534bce4872d2abaf936334
MultiPart: 2/2
diff --git a/lib/netconfig/example_test.go b/lib/netconfig/example_test.go
deleted file mode 100644
index 33ab162..0000000
--- a/lib/netconfig/example_test.go
+++ /dev/null
@@ -1,20 +0,0 @@
-package netconfig_test
-
-import (
- "fmt"
- "log"
-
- "v.io/x/ref/lib/netconfig"
-)
-
-func ExampleNetConfigWatcher() {
- w, err := netconfig.NewNetConfigWatcher()
- if err != nil {
- log.Fatalf("oops: %s", err)
- }
- fmt.Println("Do something to your network. You should see one or more dings.")
- for {
- <-w.Channel()
- fmt.Println("ding")
- }
-}
diff --git a/lib/netconfig/ipaux_bsd.go b/lib/netconfig/ipaux_bsd.go
deleted file mode 100644
index 507f013..0000000
--- a/lib/netconfig/ipaux_bsd.go
+++ /dev/null
@@ -1,192 +0,0 @@
-// +build darwin dragonfly freebsd netbsd openbsd
-
-package netconfig
-
-// We connect to the Route socket and parse messages to
-// look for network configuration changes. This is generic
-// to all BSD based systems (including MacOS). The net
-// library already has code to parse the messages so all
-// we need to do is look for message types.
-
-import (
- "errors"
- "net"
- "sync"
- "syscall"
- "time"
-
- "v.io/x/lib/vlog"
-)
-
-/*
-#include <sys/socket.h>
-*/
-import "C"
-
-type bsdNetConfigWatcher struct {
- sync.Mutex
- t *time.Timer
- c chan struct{}
- s int
- stopped bool
-}
-
-func (w *bsdNetConfigWatcher) Stop() {
- w.Lock()
- defer w.Unlock()
- if w.stopped {
- return
- }
- w.stopped = true
- syscall.Close(w.s)
-}
-
-func (w *bsdNetConfigWatcher) Channel() chan struct{} {
- return w.c
-}
-
-// NewNetConfigWatcher returns a watcher that sends a message
-// on the Channel() whenever the config changes.
-func NewNetConfigWatcher() (NetConfigWatcher, error) {
- s, err := syscall.Socket(C.PF_ROUTE, syscall.SOCK_RAW, syscall.AF_UNSPEC)
- if err != nil {
- vlog.Infof("socket failed: %s", err)
- return nil, err
- }
- w := &bsdNetConfigWatcher{c: make(chan struct{}, 1), s: s}
- go w.watcher()
- return w, nil
-}
-
-func (w *bsdNetConfigWatcher) ding() {
- w.Lock()
- defer w.Unlock()
- w.t = nil
- if w.stopped {
- return
- }
- // Don't let us hang in the lock. The default is safe because the requirement
- // is that the client get a message after the last config change. Since this is
- // a queued chan, we really don't have to stuff anything in it if there's already
- // something there.
- select {
- case w.c <- struct{}{}:
- default:
- }
-}
-
-func (w *bsdNetConfigWatcher) watcher() {
- defer w.Stop()
-
- // Loop waiting for messages.
- for {
- b := make([]byte, 4096)
- nr, err := syscall.Read(w.s, b)
- if err != nil {
- return
- }
- msgs, err := syscall.ParseRoutingMessage(b[:nr])
- if err != nil {
- vlog.Infof("Couldn't parse: %s", err)
- continue
- }
-
- // Decode the addresses.
- for _, m := range msgs {
- switch m.(type) {
- case *syscall.InterfaceMessage:
- case *syscall.InterfaceAddrMessage:
- case *syscall.RouteMessage:
- default:
- continue
- }
- // Changing networks usually spans many seconds and involves
- // multiple network config changes. We add histeresis by
- // setting an alarm when the first change is detected and
- // not informing the client till the alarm goes off.
- // NOTE(p): I chose 3 seconds because that covers all the
- // events involved in moving from one wifi network to another.
- w.Lock()
- if w.t == nil {
- w.t = time.AfterFunc(3*time.Second, w.ding)
- }
- w.Unlock()
- }
- }
-
- w.Stop()
- w.Lock()
- close(w.c)
- if w.t != nil {
- w.t.Stop()
- }
- w.Unlock()
-}
-
-func toIP(sa syscall.Sockaddr) (net.IP, error) {
- switch v := sa.(type) {
- case *syscall.SockaddrInet4:
- return net.IPv4(v.Addr[0], v.Addr[1], v.Addr[2], v.Addr[3]), nil
- case *syscall.SockaddrInet6:
- return net.IP(v.Addr[:]), nil
- }
- return net.IPv6zero, errors.New("unknown sockaddr ip")
-}
-
-func toIPNet(sa syscall.Sockaddr, msa syscall.Sockaddr) (net.IPNet, error) {
- var x net.IPNet
- var err error
- x.IP, err = toIP(sa)
- if err != nil {
- return x, err
- }
- switch v := msa.(type) {
- case *syscall.SockaddrInet4:
- x.Mask = net.IPv4Mask(v.Addr[0], v.Addr[1], v.Addr[2], v.Addr[3])
- return x, nil
- case *syscall.SockaddrInet6:
- x.Mask = net.IPMask(v.Addr[:])
- return x, nil
- }
- return x, errors.New("unknown sockaddr ipnet")
-}
-
-// IPRoutes returns all kernel known routes. If defaultOnly is set, only default routes
-// are returned.
-func GetIPRoutes(defaultOnly bool) []*IPRoute {
- var x []*IPRoute
- rib, err := syscall.RouteRIB(syscall.NET_RT_DUMP, 0)
- if err != nil {
- vlog.Infof("Couldn't read: %s", err)
- return x
- }
- msgs, err := syscall.ParseRoutingMessage(rib)
- if err != nil {
- vlog.Infof("Couldn't parse: %s", err)
- return x
- }
- for _, m := range msgs {
- switch v := m.(type) {
- case *syscall.RouteMessage:
- addrs, err := syscall.ParseRoutingSockaddr(m)
- if err != nil {
- return x
- }
- if addrs[0] == nil || addrs[1] == nil || addrs[2] == nil {
- continue
- }
- r := new(IPRoute)
- if r.Gateway, err = toIP(addrs[1]); err != nil {
- continue
- }
- if r.Net, err = toIPNet(addrs[0], addrs[2]); err != nil {
- continue
- }
- r.IfcIndex = int(v.Header.Index)
- if !defaultOnly || IsDefaultIPRoute(r) {
- x = append(x, r)
- }
- }
- }
- return x
-}
diff --git a/lib/netconfig/ipaux_linux.go b/lib/netconfig/ipaux_linux.go
deleted file mode 100644
index e36b9e5..0000000
--- a/lib/netconfig/ipaux_linux.go
+++ /dev/null
@@ -1,457 +0,0 @@
-// +build linux
-
-package netconfig
-
-// We connect to the Netlink Route socket and parse messages to
-// look for network configuration changes. This is very Linux
-// specific, hence the file name.
-
-import (
- "errors"
- "fmt"
- "net"
- "sync"
- "syscall"
- "time"
- "unsafe"
-
- "v.io/x/lib/vlog"
-)
-
-/*
-#include <linux/rtnetlink.h>
-*/
-import "C"
-
-// All rtnetlink attributes start with this header.
-type rtAttrHdr C.struct_rtattr
-
-const rtAttrHdrLen = C.sizeof_struct_rtattr
-
-// The address change messages (RTM_NEWADDR, RTM_DELADDR, RTM_GETADDR).
-type ifaddrMsgHdr C.struct_ifaddrmsg
-
-const ifaddrMsgHdrLen = C.sizeof_struct_ifaddrmsg
-
-type rtAttribute fmt.Stringer
-
-type rtAddressMessage struct {
- name string
- hdr ifaddrMsgHdr
- attributes []rtAttribute
-}
-
-// Attribute types (see rtnetlink(7))
-type ifaAddress net.IP
-type ifaLocal net.IP
-type ifaBroadcast net.IP
-type ifaAnycast net.IP
-type ifaMulticast net.IP
-type ifaLabel string
-type ifaCacheInfo C.struct_ifa_cacheinfo
-
-const ifaCacheInfoLen = C.sizeof_struct_ifa_cacheinfo
-
-// String routines to make debugging easier.
-func (a ifaAddress) String() string { return "Address=" + net.IP(a).String() }
-func (a ifaLocal) String() string { return "Local=" + net.IP(a).String() }
-func (a ifaBroadcast) String() string { return "Braodcast=" + net.IP(a).String() }
-func (a ifaAnycast) String() string { return "Anycast=" + net.IP(a).String() }
-func (a ifaMulticast) String() string { return "Anycast=" + net.IP(a).String() }
-func (a ifaLabel) String() string { return "Label=" + string(a) }
-func (a ifaCacheInfo) String() string {
- return fmt.Sprintf("CacheInfo[preferred %d valid %d cstamp %d tstamp %d]", a.ifa_prefered, a.ifa_valid, a.cstamp, a.tstamp)
-}
-func (m *rtAddressMessage) String() string {
- return fmt.Sprintf("%s: index %d %v", m.name, m.hdr.ifa_index, m.attributes)
-}
-
-// Address looks for the address attribute in an rtAddressMessage. If it isn't there, just assume the null address.
-func (m *rtAddressMessage) Address() net.IP {
- for _, a := range m.attributes {
- switch a.(type) {
- case ifaAddress:
- return net.IP(a.(ifaAddress))
- }
- }
- return net.IPv4zero
-}
-
-func parsertAddressAttribute(b []byte) (rtAttribute, []byte, error) {
- if len(b) == 0 {
- return nil, nil, nil
- }
- if len(b) < rtAttrHdrLen {
- return nil, nil, errors.New("attribute too short")
- }
- ahdr := (*rtAttrHdr)(unsafe.Pointer(&b[0]))
- rounded := ((ahdr.rta_len + 3) / 4) * 4
- if len(b) < int(rounded) {
- return nil, nil, errors.New("attribute too short")
- }
- remaining := b[rounded:]
- b = b[rtAttrHdrLen:ahdr.rta_len]
- switch ahdr.rta_type {
- case C.IFA_ADDRESS:
- return rtAttribute(ifaAddress(net.IP(b))), remaining, nil
- case C.IFA_LOCAL:
- return rtAttribute(ifaLocal(b)), remaining, nil
- case C.IFA_LABEL:
- return rtAttribute(ifaLabel(b)), remaining, nil
- case C.IFA_BROADCAST:
- return rtAttribute(ifaBroadcast(b)), remaining, nil
- case C.IFA_ANYCAST:
- return rtAttribute(ifaAnycast(b)), remaining, nil
- case C.IFA_CACHEINFO:
- if len(b) < ifaCacheInfoLen {
- return nil, nil, errors.New("attribute too short")
- }
- return rtAttribute(ifaCacheInfo(*(*C.struct_ifa_cacheinfo)(unsafe.Pointer(&b[0])))), remaining, nil
- case C.IFA_MULTICAST:
- return rtAttribute(ifaMulticast(b)), remaining, nil
- }
- return nil, remaining, errors.New("unknown attribute")
-}
-
-func parsertAddressMessage(nlm syscall.NetlinkMessage) (*rtAddressMessage, error) {
- var name string
- switch nlm.Header.Type {
- case C.RTM_NEWADDR:
- name = "RTM_NEWADDR"
- case C.RTM_DELADDR:
- name = "RTM_DELADDR"
- case C.RTM_GETADDR:
- name = "RTM_GETADDR"
- default:
- return nil, fmt.Errorf("unknown message type")
- }
- if len(nlm.Data) < ifaddrMsgHdrLen {
- return nil, errors.New("bad length")
- }
- m := &rtAddressMessage{name: name, hdr: *(*ifaddrMsgHdr)(unsafe.Pointer(&nlm.Data[0]))}
- b := nlm.Data[ifaddrMsgHdrLen:]
- for {
- var a rtAttribute
- var err error
- a, b, err = parsertAddressAttribute(b)
- if b == nil {
- break
- }
- if err == nil {
- m.attributes = append(m.attributes, a)
- }
- }
- return m, nil
-}
-
-// The link change messages (RTM_NEWLINK, RTM_DELLINK, RTM_GETLINK).
-type ifInfoMsgHdr C.struct_ifinfomsg
-
-const ifInfoMsgHdrLen = C.sizeof_struct_ifinfomsg
-
-type rtLinkMessage struct {
- name string
- hdr ifInfoMsgHdr
- attributes []rtAttribute
-}
-
-// Attribute types (see rtnetlink(7))
-type iflaAddress []byte
-type iflaBroadcast []byte
-type iflaIFName string
-type iflaMTU uint32
-type iflaLink int
-type iflaQDisc string
-type iflaOperstate int
-type iflaStats C.struct_rtnl_link_stats
-
-const iflaStatsLen = C.sizeof_struct_rtnl_link_stats
-
-// String routines to make debugging easier.
-func (a iflaAddress) String() string { return fmt.Sprintf("HWAddress=%v", []byte(a)) }
-func (a iflaBroadcast) String() string { return fmt.Sprintf("HWBroadcast=%v", []byte(a)) }
-func (a iflaIFName) String() string { return "Name=" + string(a) }
-func (a iflaMTU) String() string { return fmt.Sprintf("MTU=%d", uint32(a)) }
-func (a iflaLink) String() string { return fmt.Sprintf("Type=%d", int(a)) }
-func (a iflaQDisc) String() string { return "Qdisc=" + string(a) }
-func (a iflaStats) String() string {
- return fmt.Sprintf("Stats[rx %d tx %d ...]", a.rx_packets, a.tx_packets)
-}
-func (a iflaOperstate) String() string { return fmt.Sprintf("Operstate=%d", int(a)) }
-func (m *rtLinkMessage) String() string {
- return fmt.Sprintf("%s: index %d %v", m.name, m.hdr.ifi_index, m.attributes)
-}
-
-func parseRTLinkAttribute(b []byte) (rtAttribute, []byte, error) {
- if len(b) == 0 {
- return nil, nil, nil
- }
- if len(b) < rtAttrHdrLen {
- return nil, nil, errors.New("attribute too short")
- }
- ahdr := (*rtAttrHdr)(unsafe.Pointer(&b[0]))
- rounded := ((ahdr.rta_len + 3) / 4) * 4
- if len(b) < int(rounded) {
- return nil, nil, errors.New("attribute too short")
- }
- remaining := b[rounded:]
- b = b[rtAttrHdrLen:ahdr.rta_len]
- switch ahdr.rta_type {
- case C.IFLA_ADDRESS:
- return rtAttribute(iflaAddress(b)), remaining, nil
- case C.IFLA_BROADCAST:
- return rtAttribute(iflaBroadcast(b)), remaining, nil
- case C.IFLA_IFNAME:
- return rtAttribute(iflaIFName(string(b))), remaining, nil
- case C.IFLA_MTU:
- return rtAttribute(iflaMTU(*(*C.uint)(unsafe.Pointer(&b[0])))), remaining, nil
- case C.IFLA_LINK:
- return rtAttribute(iflaMTU(*(*C.int)(unsafe.Pointer(&b[0])))), remaining, nil
- case C.IFLA_QDISC:
- return rtAttribute(iflaQDisc(string(b))), remaining, nil
- case C.IFLA_STATS:
- if len(b) < iflaStatsLen {
- return nil, remaining, errors.New("attribute too short")
- }
- return rtAttribute(iflaStats(*(*C.struct_rtnl_link_stats)(unsafe.Pointer(&b[0])))), remaining, nil
- case C.IFLA_OPERSTATE:
- return rtAttribute(iflaOperstate(*(*C.int)(unsafe.Pointer(&b[0])))), remaining, nil
- }
- return nil, remaining, errors.New("unknown attribute")
-}
-
-func parsertLinkMessage(nlm syscall.NetlinkMessage) (*rtLinkMessage, error) {
- var name string
- switch nlm.Header.Type {
- case C.RTM_NEWLINK:
- name = "RTM_NEWLINK"
- case C.RTM_DELLINK:
- name = "RTM_DELLINK"
- case C.RTM_GETLINK:
- name = "RTM_GETLINK"
- default:
- return nil, fmt.Errorf("unknown message type")
- }
- if len(nlm.Data) < ifInfoMsgHdrLen {
- return nil, errors.New("bad length")
- }
- m := &rtLinkMessage{name: name, hdr: *(*ifInfoMsgHdr)(unsafe.Pointer(&nlm.Data[0]))}
- b := nlm.Data[ifInfoMsgHdrLen:]
- for {
- var a rtAttribute
- var err error
- a, b, err = parseRTLinkAttribute(b)
- if b == nil {
- break
- }
- if err == nil {
- m.attributes = append(m.attributes, a)
- }
- }
- return m, nil
-}
-
-type rtnetlinkWatcher struct {
- sync.Mutex
- t *time.Timer
- c chan struct{}
- s int
- stopped bool
-}
-
-func (w *rtnetlinkWatcher) Stop() {
- w.Lock()
- defer w.Unlock()
- if w.stopped {
- return
- }
- w.stopped = true
- syscall.Close(w.s)
-}
-
-func (w *rtnetlinkWatcher) Channel() chan struct{} {
- return w.c
-}
-
-const (
- GROUPS = C.RTMGRP_LINK | C.RTMGRP_IPV4_IFADDR | C.RTMGRP_IPV4_MROUTE | C.RTMGRP_IPV4_ROUTE | C.RTMGRP_IPV6_IFADDR | C.RTMGRP_IPV6_MROUTE | C.RTMGRP_IPV6_ROUTE | C.RTMGRP_NOTIFY
-)
-
-// NewNetConfigWatcher returns a watcher that wakes up anyone
-// calling the Wait routine whenever the configuration changes.
-func NewNetConfigWatcher() (NetConfigWatcher, error) {
- s, err := syscall.Socket(syscall.AF_NETLINK, syscall.SOCK_RAW, syscall.NETLINK_ROUTE)
- if err != nil {
- vlog.Infof("netconfig socket failed: %s", err)
- return nil, err
- }
-
- lsa := &syscall.SockaddrNetlink{Family: syscall.AF_NETLINK, Groups: GROUPS}
- if err := syscall.Bind(s, lsa); err != nil {
- vlog.Infof("netconfig bind failed: %s", err)
- return nil, err
- }
-
- w := &rtnetlinkWatcher{c: make(chan struct{}, 1), s: s}
- go w.watcher()
- return w, nil
-}
-
-func (w *rtnetlinkWatcher) ding() {
- w.Lock()
- defer w.Unlock()
- w.t = nil
- if w.stopped {
- return
- }
- // Don't let us hang in the lock. The default is safe because the requirement
- // is that the client get a message after the last config change. Since this is
- // a queued chan, we really don't have to stuff anything in it if there's already
- // something there.
- select {
- case w.c <- struct{}{}:
- default:
- }
-}
-
-func (w *rtnetlinkWatcher) watcher() {
- var newAddrs []net.IP
- for {
- rb := make([]byte, 4096)
- nr, _, err := syscall.Recvfrom(w.s, rb, 0)
- if err != nil {
- break
- }
- rb = rb[:nr]
- msgs, err := syscall.ParseNetlinkMessage(rb)
- if err != nil {
- vlog.Infof("ParseNetlinkMessage failed: %s", err)
- continue
- }
- L:
- for _, m := range msgs {
- if am, err := parsertAddressMessage(m); err == nil {
- // NOTE(p): We get continuous NEWADDR messages about some
- // IPv6 addresses in Google corp. Just ignore duplicate back
- // to back NEWADDRs about the same addresses.
- if am.name == "RTM_NEWADDR" {
- addr := am.Address()
- for _, a := range newAddrs {
- if addr.Equal(a) {
- break L
- }
- }
- newAddrs = append(newAddrs, addr)
- } else {
- newAddrs = nil
- }
- } else if _, err := parsertLinkMessage(m); err == nil {
- newAddrs = nil
- } else {
- continue
- }
- // Changing networks usually spans many seconds and involves
- // multiple network config changes. We add histeresis by
- // setting an alarm when the first change is detected and
- // not informing the client till the alarm goes off.
- // NOTE(p): I chose 3 seconds because that covers all the
- // events involved in moving from one wifi network to another.
- w.Lock()
- if w.t == nil {
- w.t = time.AfterFunc(3*time.Second, w.ding)
- }
- w.Unlock()
- }
- }
-
- w.Stop()
- w.Lock()
- close(w.c)
- if w.t != nil {
- w.t.Stop()
- }
- w.Unlock()
-}
-func toIP(a []byte) (net.IP, error) {
- switch len(a) {
- case 4:
- return net.IPv4(a[0], a[1], a[2], a[3]), nil
- case 16:
- return net.IP(a), nil
- }
- return net.IPv6unspecified, errors.New("unknown ip address len")
-}
-
-// IPRoutes returns all kernel known routes. If defaultOnly is set, only default routes
-// are returned.
-func GetIPRoutes(defaultOnly bool) []*IPRoute {
- var iproutes []*IPRoute
- rib, err := syscall.NetlinkRIB(syscall.RTM_GETROUTE, syscall.AF_UNSPEC)
- if err != nil {
- vlog.Infof("Couldn't read: %s", err)
- return iproutes
- }
- msgs, err := syscall.ParseNetlinkMessage(rib)
- if err != nil {
- vlog.Infof("Couldn't parse: %s", err)
- return iproutes
- }
-L:
- for _, m := range msgs {
- if m.Header.Type != syscall.RTM_NEWROUTE {
- continue
- }
- attrs, err := syscall.ParseNetlinkRouteAttr(&m)
- if err != nil {
- continue
- }
- r := new(IPRoute)
- for _, a := range attrs {
- switch a.Attr.Type {
- case syscall.RTA_DST:
- if r.Net.IP, err = toIP(a.Value[:]); err != nil {
- continue L
- }
- case syscall.RTA_GATEWAY:
- if r.Gateway, err = toIP(a.Value[:]); err != nil {
- continue L
- }
- case syscall.RTA_OIF:
- r.IfcIndex = int(a.Value[0])
- case syscall.RTA_PREFSRC:
- if r.PreferredSource, err = toIP(a.Value[:]); err != nil {
- continue L
- }
- }
- }
-
- // There is no RTA_DST attribute if destination is a default gateway.
- // Set the destination IP with zero IP, if not set yet.
- if r.Net.IP == nil {
- if r.Gateway == nil {
- continue
- }
- if r.Gateway.To4() != nil {
- r.Net.IP = net.IPv4zero
- } else {
- r.Net.IP = net.IPv6zero
- }
- }
-
- addrLen := 128
- if r.Net.IP.To4() != nil {
- addrLen = 32
- }
-
- b := m.Data[:syscall.SizeofRtMsg]
- a := (*syscall.RtMsg)(unsafe.Pointer(&b[0]))
- if int(a.Dst_len) > addrLen {
- continue
- }
- r.Net.Mask = net.CIDRMask(int(a.Dst_len), addrLen)
- if !defaultOnly || IsDefaultIPRoute(r) {
- iproutes = append(iproutes, r)
- }
- }
- return iproutes
-}
diff --git a/lib/netconfig/ipaux_other.go b/lib/netconfig/ipaux_other.go
deleted file mode 100644
index 948c0c7..0000000
--- a/lib/netconfig/ipaux_other.go
+++ /dev/null
@@ -1,55 +0,0 @@
-// +build !linux,!darwin,!dragonfly,!freebsd,!netbsd,!openbsd
-// TODO(bprosnitz) Should change for nacl?
-
-package netconfig
-
-// Code to signal a network change every 2 minutes. We use
-// this for systems where we don't yet have a good way to
-// watch for network changes.
-
-import (
- "time"
-)
-
-type timerNetConfigWatcher struct {
- c chan struct{} // channel to signal confg changes
- stop chan struct{} // channel to tell the watcher to stop
-}
-
-// Stop any waiter
-func (w *timerNetConfigWatcher) Stop() {
- w.stop <- struct{}{}
-}
-
-func (w *timerNetConfigWatcher) Channel() chan struct{} {
- return w.c
-}
-
-func (w *timerNetConfigWatcher) watcher() {
- for {
- select {
- case <-w.stop:
- close(w.c)
- return
- case <-time.NewTimer(2 * time.Minute).C:
- select {
- case w.c <- struct{}{}:
- default:
- }
- }
- }
-}
-
-func NewNetConfigWatcher() (NetConfigWatcher, error) {
- w := &timerNetConfigWatcher{}
- w.c = make(chan struct{})
- w.stop = make(chan struct{}, 1)
- go w.watcher()
- return w, nil
-}
-
-func GetIPRoutes(defaultOnly bool) []*IPRoute {
- // TODO(nlacasse,bprosnitz): Consider implementing? For now return
- // empty array, since that seems to keep things working.
- return []*IPRoute{}
-}
diff --git a/lib/netconfig/iproute.go b/lib/netconfig/iproute.go
deleted file mode 100644
index 43115e3..0000000
--- a/lib/netconfig/iproute.go
+++ /dev/null
@@ -1,40 +0,0 @@
-// package netconfig implements a network configuration watcher.
-// NOTE(p): This is also where we should put any code that changes
-// network configuration.
-
-package netconfig
-
-import "net"
-
-func isZeroSlice(a []byte) bool {
- for _, i := range a {
- if i != 0 {
- return false
- }
- }
- return true
-}
-
-// IsDefaultRoute returns true if r is a default route, i.e., that it matches any destination address.
-func IsDefaultIPRoute(r *IPRoute) bool {
- if !r.Net.IP.Equal(net.IPv4zero) && !r.Net.IP.Equal(net.IPv6zero) {
- return false
- }
- return isZeroSlice(r.Net.Mask[:])
-}
-
-// IsDefaultIPv4Route returns true if r is a default IPv4 route.
-func IsDefaultIPv4Route(r *IPRoute) bool {
- if !r.Net.IP.Equal(net.IPv4zero) && !r.Net.IP.Equal(net.IPv6zero) {
- return false
- }
- return len(r.Net.Mask) == 4 && isZeroSlice(r.Net.Mask[:])
-}
-
-// IsDefaultIPv6Route returns true if r is a default IPv6 route.
-func IsDefaultIPv6Route(r *IPRoute) bool {
- if !r.Net.IP.Equal(net.IPv4zero) && !r.Net.IP.Equal(net.IPv6zero) {
- return false
- }
- return len(r.Net.Mask) == 16 && isZeroSlice(r.Net.Mask[:])
-}
diff --git a/lib/netconfig/model.go b/lib/netconfig/model.go
deleted file mode 100644
index 27898cc..0000000
--- a/lib/netconfig/model.go
+++ /dev/null
@@ -1,30 +0,0 @@
-// package netconfig implements a network configuration watcher.
-// NOTE(p): This is also where we should put any code that changes
-// network configuration.
-
-package netconfig
-
-import (
- "net"
-)
-
-// NetConfigWatcher sends on channel whenever an interface or interface address
-// is added or deleted.
-type NetConfigWatcher interface {
- // Stop watching.
- Stop()
-
- // A channel that returns an item whenever the network addresses or
- // interfaces have changed. It is up to the caller to reread the
- // network configuration in such cases.
- Channel() chan struct{}
-}
-
-// IPRoute represents a route in the kernel's routing table.
-// Any route with a nil Gateway is a directly connected network.
-type IPRoute struct {
- Net net.IPNet
- Gateway net.IP
- PreferredSource net.IP
- IfcIndex int
-}
diff --git a/lib/netstate/isgloballyroutable.go b/lib/netstate/isgloballyroutable.go
deleted file mode 100644
index ee6bae5..0000000
--- a/lib/netstate/isgloballyroutable.go
+++ /dev/null
@@ -1,29 +0,0 @@
-package netstate
-
-import (
- "net"
-)
-
-var privateCIDRs = []net.IPNet{
- net.IPNet{IP: net.IPv4(10, 0, 0, 0), Mask: net.IPv4Mask(0xff, 0, 0, 0)},
- net.IPNet{IP: net.IPv4(172, 16, 0, 0), Mask: net.IPv4Mask(0xff, 0xf0, 0, 0)},
- net.IPNet{IP: net.IPv4(192, 168, 0, 0), Mask: net.IPv4Mask(0xff, 0xff, 0, 0)},
-}
-
-// IsGloballyRoutable returns true if the argument is a globally routable IP address.
-func IsGloballyRoutableIP(ip net.IP) bool {
- if !ip.IsGlobalUnicast() {
- return false
- }
- if ip4 := ip.To4(); ip4 != nil {
- for _, cidr := range privateCIDRs {
- if cidr.Contains(ip4) {
- return false
- }
- }
- if ip4.Equal(net.IPv4bcast) {
- return false
- }
- }
- return true
-}
diff --git a/lib/netstate/isgloballyroutable_test.go b/lib/netstate/isgloballyroutable_test.go
deleted file mode 100644
index dd0885a..0000000
--- a/lib/netstate/isgloballyroutable_test.go
+++ /dev/null
@@ -1,31 +0,0 @@
-package netstate
-
-import (
- "net"
- "testing"
-)
-
-func TestIsGloballyRoutable(t *testing.T) {
- tests := []struct {
- ip string
- want bool
- }{
- {"192.168.1.1", false},
- {"192.169.0.3", true},
- {"10.1.1.1", false},
- {"172.17.100.255", false},
- {"172.32.0.1", true},
- {"255.255.255.255", false},
- {"127.0.0.1", false},
- {"224.0.0.1", false},
- {"FF02::FB", false},
- {"fe80::be30:5bff:fed3:843f", false},
- {"2620:0:1000:8400:be30:5bff:fed3:843f", true},
- }
- for _, test := range tests {
- ip := net.ParseIP(test.ip)
- if got := IsGloballyRoutableIP(ip); got != test.want {
- t.Fatalf("%s: want %v got %v", test.ip, test.want, got)
- }
- }
-}
diff --git a/lib/netstate/netstate.go b/lib/netstate/netstate.go
deleted file mode 100644
index 623e7b2..0000000
--- a/lib/netstate/netstate.go
+++ /dev/null
@@ -1,398 +0,0 @@
-// Package netstate provides routines to obtain the available set of
-// of network addresess, for determining changes to those addresses and for
-// selecting from amongst them according to some set of policies that are
-// implemented by applying simple predicates (functions with names of the form
-// Is<condition>) to filter or find the first matching address from a list
-// of addresses. The intent is to make it easy to create policies that do
-// things like 'find the first IPv4 unicast address that is globally routable,
-// failing that use a private IPv4 address, and failing that, an IPv6 address'.
-//
-// A simple usage would be:
-//
-// state, _ := netstate.GetAccessibleIPs()
-// ipv4 := state.Filter(netstate.IsPublicUnicastIPv4)
-// // ipv4 will contain all of the public IPv4 addresses, if any.
-//
-// The example policy described above would be implemented using a
-// series of calls to Filter with appropriate predicates.
-//
-// In some cases, it may be necessary to take IP routing information
-// into account and hence interface hosting the address. The interface
-// hosting each address is provided in the AddrIfc structure used to represent
-// addresses and the IP routing information is provided by the GetAccessibleIPs
-// function which will typically be used to obtain the available IP addresses.
-//
-// Although most commercial networking hardware supports IPv6, some consumer
-// devices and more importantly many ISPs do not, so routines are provided
-// to allow developers to easily distinguish between the two and to use
-// whichever is appropriate for their product/situation.
-//
-// The term 'accessible' is used to refer to any non-loopback IP address.
-// The term 'public' is used to refer to any globally routable IP address.
-//
-// All IPv6 addresses are intended to be 'public', but any starting with
-// fc00::/7 (RFC4193) are reserved for private use, but the go
-// net libraries do not appear to recognise this. Similarly fe80::/10
-// (RFC 4291) are reserved for 'site-local' usage, but again this is not
-// implemented in the go libraries. Any developer who needs to distinguish
-// these cases will need to write their own routines to test for them.
-//
-// When using the go net package it is important to remember that IPv6
-// addresses subsume IPv4 and hence in many cases the same internal
-// representation is used for both, thus testing for the length of the IP
-// address is unreliable. The reliable test is to use the net.To4() which
-// will return a non-nil result if can be used as an IPv4 one. Any address
-// can be used as an IPv6 and hence the only reliable way to test for an IPv6
-// address that is not an IPv4 one also is for the To4 call to return nil for
-// it.
-package netstate
-
-import (
- "fmt"
- "net"
- "strings"
-
- "v.io/v23/ipc"
-
- "v.io/x/ref/lib/netconfig"
-)
-
-// AddrIfc represents a network address and the network interface that
-// hosts it.
-type AddrIfc struct {
- // Network address
- Addr net.Addr
-
- // The name of the network interface this address is hosted on, empty
- // if this information is not available.
- Name string
-
- // The IPRoutes of the network interface this address is hosted on,
- // nil if this information is not available.
- IPRoutes []*netconfig.IPRoute
-}
-
-func (a *AddrIfc) String() string {
- if a.IPRoutes != nil {
- r := fmt.Sprintf("%s: %s[", a.Addr, a.Name)
- for _, rt := range a.IPRoutes {
- src := ""
- if rt.PreferredSource != nil {
- src = ", src: " + rt.PreferredSource.String()
- }
- r += fmt.Sprintf("{%d: net: %s, gw: %s%s}, ", rt.IfcIndex, rt.Net, rt.Gateway, src)
- }
- r = strings.TrimSuffix(r, ", ")
- r += "]"
- return r
- }
- return a.Addr.String()
-}
-
-func (a *AddrIfc) Address() net.Addr {
- return a.Addr
-}
-
-func (a *AddrIfc) InterfaceIndex() int {
- if len(a.IPRoutes) == 0 {
- return -1
- }
- return a.IPRoutes[0].IfcIndex
-}
-
-func (a *AddrIfc) InterfaceName() string {
- return a.Name
-}
-
-func (a *AddrIfc) Networks() []net.Addr {
- nets := []net.Addr{}
- for _, r := range a.IPRoutes {
- nets = append(nets, &r.Net)
- }
- return nets
-}
-
-type AddrList []ipc.Address
-
-func (al AddrList) String() string {
- r := ""
- for _, v := range al {
- r += fmt.Sprintf("(%s) ", v)
- }
- return strings.TrimRight(r, " ")
-}
-
-// GetAll gets all of the available addresses on the device, including
-// loopback addresses, non-IP protocols etc.
-func GetAll() (AddrList, error) {
- interfaces, err := net.Interfaces()
- if err != nil {
- return nil, err
- }
- routes := netconfig.GetIPRoutes(false)
- routeTable := make(map[int][]*netconfig.IPRoute)
- for _, r := range routes {
- routeTable[r.IfcIndex] = append(routeTable[r.IfcIndex], r)
- }
- var all AddrList
- for _, ifc := range interfaces {
- addrs, err := ifc.Addrs()
- if err != nil {
- continue
- }
- for _, a := range addrs {
- all = append(all, &AddrIfc{a, ifc.Name, routeTable[ifc.Index]})
- }
- }
- return all, nil
-}
-
-// GetAccessibleIPs returns all of the accessible IP addresses on the device
-// - i.e. excluding loopback and unspecified addresses.
-// The IP addresses returned will be host addresses.
-func GetAccessibleIPs() (AddrList, error) {
- all, err := GetAll()
- if err != nil {
- return nil, err
- }
- return all.Map(ConvertAccessibleIPHost), nil
-}
-
-// AddressPredicate defines the function signature for predicate functions
-// to be used with AddrList
-type AddressPredicate func(a ipc.Address) bool
-
-// Filter returns all of the addresses for which the predicate
-// function is true.
-func (al AddrList) Filter(predicate AddressPredicate) AddrList {
- r := AddrList{}
- for _, a := range al {
- if predicate(a) {
- r = append(r, a)
- }
- }
- return r
-}
-
-type Mapper func(a ipc.Address) ipc.Address
-
-// Map will apply the Mapper function to all of the items in its receiver
-// and return a new AddrList containing all of the non-nil results from
-// said calls.
-func (al AddrList) Map(mapper Mapper) AddrList {
- var ral AddrList
- for _, a := range al {
- if na := mapper(a); na != nil {
- ral = append(ral, na)
- }
- }
- return ral
-}
-
-// ConvertToIPHost converts the network address component of an ipc.Address into
-// an instance with a net.Addr that contains an IP host address (as opposed to a
-// network CIDR for example).
-func ConvertToIPHost(a ipc.Address) ipc.Address {
- aifc, ok := a.(*AddrIfc)
- if !ok {
- return nil
- }
- aifc.Addr = AsIPAddr(aifc.Addr)
- return aifc
-}
-
-// ConvertAccessibleIPHost converts the network address component of an ipc.Address
-// into an instance with a net.Addr that contains an IP host address (as opposed to a
-// network CIDR for example) with filtering out a loopback or non-accessible IPs.
-func ConvertAccessibleIPHost(a ipc.Address) ipc.Address {
- if !IsAccessibleIP(a) {
- return nil
- }
- aifc, ok := a.(*AddrIfc)
- if !ok {
- return nil
- }
- if ip := AsIPAddr(aifc.Addr); ip != nil {
- aifc.Addr = ip
- }
- return aifc
-}
-
-// IsIPProtocol returns true if its parameter is one of the allowed
-// network/protocol values for IP.
-func IsIPProtocol(n string) bool {
- // Removed the training IP version number.
- n = strings.TrimRightFunc(n, func(r rune) bool { return r == '4' || r == '6' })
- switch n {
- case "ip+net", "ip", "tcp", "udp", "ws", "wsh":
- return true
- default:
- return false
- }
-}
-
-// AsIPAddr returns its argument as a net.IPAddr if that's possible.
-func AsIPAddr(a net.Addr) *net.IPAddr {
- if v, ok := a.(*net.IPAddr); ok {
- return v
- }
- if ipn, ok := a.(*net.IPNet); ok {
- return &net.IPAddr{IP: ipn.IP}
- }
- if IsIPProtocol(a.Network()) {
- if r := net.ParseIP(a.String()); r != nil {
- return &net.IPAddr{IP: r}
- }
- }
- return nil
-}
-
-// AsIP returns its argument as a net.IP if that's possible.
-func AsIP(a net.Addr) net.IP {
- ipAddr := AsIPAddr(a)
- if ipAddr == nil {
- return nil
- }
- return ipAddr.IP
-}
-
-// IsUnspecified returns true if its argument is an unspecified IP address
-func IsUnspecifiedIP(a ipc.Address) bool {
- if ip := AsIP(a.Address()); ip != nil {
- return ip.IsUnspecified()
- }
- return false
-}
-
-// IsLoopback returns true if its argument is a loopback IP address
-func IsLoopbackIP(a ipc.Address) bool {
- if ip := AsIP(a.Address()); ip != nil && !ip.IsUnspecified() {
- return ip.IsLoopback()
- }
- return false
-}
-
-// IsAccessible returns true if its argument is an accessible (non-loopback)
-// IP address.
-func IsAccessibleIP(a ipc.Address) bool {
- if ip := AsIP(a.Address()); ip != nil && !ip.IsUnspecified() {
- return !ip.IsLoopback()
- }
- return false
-}
-
-// IsUnicastIP returns true if its argument is a unicast IP address.
-func IsUnicastIP(a ipc.Address) bool {
- if ip := AsIP(a.Address()); ip != nil && !ip.IsUnspecified() {
- // ipv4 or v6
- return !(ip.IsMulticast() || ip.IsLinkLocalMulticast() || ip.IsInterfaceLocalMulticast())
- }
- return false
-}
-
-// IsUnicastIPv4 returns true if its argument is a unicast IP4 address
-func IsUnicastIPv4(a ipc.Address) bool {
- if ip := AsIP(a.Address()); ip != nil && ip.To4() != nil {
- return !ip.IsUnspecified() && !ip.IsMulticast()
- }
- return false
-}
-
-// IsPublicUnicastIPv4 returns true if its argument is a globally routable,
-// public IPv4 unicast address.
-func IsPublicUnicastIPv4(a ipc.Address) bool {
- if ip := AsIP(a.Address()); ip != nil && !ip.IsUnspecified() {
- if t := ip.To4(); t != nil && IsGloballyRoutableIP(t) {
- return !ip.IsMulticast()
- }
- }
- return false
-}
-
-// IsUnicastIPv6 returns true if its argument is a unicast IPv6 address
-func IsUnicastIPv6(a ipc.Address) bool {
- if ip := AsIP(a.Address()); ip != nil && ip.To4() == nil {
- return !ip.IsUnspecified() && !(ip.IsLinkLocalMulticast() || ip.IsInterfaceLocalMulticast())
- }
- return false
-}
-
-// IsUnicastIPv6 returns true if its argument is a globally routable IP6
-// address
-func IsPublicUnicastIPv6(a ipc.Address) bool {
- if ip := AsIP(a.Address()); ip != nil && ip.To4() == nil {
- if t := ip.To16(); t != nil && IsGloballyRoutableIP(t) {
- return true
- }
- }
- return false
-}
-
-// IsPublicUnicastIP returns true if its argument is a global routable IPv4
-// or 6 address.
-func IsPublicUnicastIP(a ipc.Address) bool {
- if ip := AsIP(a.Address()); ip != nil {
- if t := ip.To4(); t != nil && IsGloballyRoutableIP(t) {
- return true
- }
- if t := ip.To16(); t != nil && IsGloballyRoutableIP(t) {
- return true
- }
- }
- return false
-}
-
-func diffAB(a, b AddrList) AddrList {
- diff := AddrList{}
- for _, av := range a {
- found := false
- for _, bv := range b {
- if av.Address().Network() == bv.Address().Network() &&
- av.Address().String() == bv.Address().String() {
- found = true
- break
- }
- }
- if !found {
- diff = append(diff, av)
- }
- }
- return diff
-}
-
-// FindAdded returns the set addresses that are present in b, but not
-// in a - i.e. have been added.
-func FindAdded(a, b AddrList) AddrList {
- return diffAB(b, a)
-}
-
-// FindRemoved returns the set of addresses that are present in a, but not
-// in b - i.e. have been removed.
-func FindRemoved(a, b AddrList) AddrList {
- return diffAB(a, b)
-}
-
-// SameMachine returns true if the provided addr is on the device executing this
-// function.
-func SameMachine(addr net.Addr) (bool, error) {
- // The available interfaces may change between calls.
- addrs, err := GetAll()
- if err != nil {
- return false, err
- }
- ips := make(map[string]struct{})
- for _, a := range addrs {
- ip, _, err := net.ParseCIDR(a.Address().String())
- if err != nil {
- return false, err
- }
- ips[ip.String()] = struct{}{}
- }
-
- client, _, err := net.SplitHostPort(addr.String())
- if err != nil {
- return false, err
- }
- _, islocal := ips[client]
- return islocal, nil
-}
diff --git a/lib/netstate/netstate_test.go b/lib/netstate/netstate_test.go
deleted file mode 100644
index 954b9d4..0000000
--- a/lib/netstate/netstate_test.go
+++ /dev/null
@@ -1,448 +0,0 @@
-package netstate_test
-
-import (
- "net"
- "reflect"
- "testing"
-
- "v.io/v23/ipc"
-
- "v.io/x/ref/lib/netconfig"
- "v.io/x/ref/lib/netstate"
-)
-
-func TestGet(t *testing.T) {
- // We assume that this machine running this test has at least
- // one non-loopback interface.
- all, err := netstate.GetAll()
- if err != nil {
- t.Fatalf("unexpected error: %s", err)
- }
- all = all.Map(netstate.ConvertToIPHost)
- accessible, err := netstate.GetAccessibleIPs()
- if err != nil {
- t.Fatalf("unexpected error: %s", err)
- }
- if len(all) == 0 || len(accessible) == 0 {
- t.Errorf("expected non zero lengths, not %d and %d", len(all), len(accessible))
- }
- if len(accessible) > len(all) {
- t.Errorf("should never be more accessible addresses than 'all' addresses")
- }
- loopback := netstate.FindAdded(accessible, all)
- if got, want := loopback.Filter(netstate.IsLoopbackIP), loopback; !reflect.DeepEqual(got, want) {
- t.Errorf("got %v, want %v", got, want)
- }
-}
-
-type ma struct {
- n, a string
-}
-
-func (a *ma) Network() string {
- return a.n
-}
-
-func (a *ma) String() string {
- return a.a
-}
-
-func mkAddr(n, a string) net.Addr {
- ip := net.ParseIP(a)
- return &ma{n: n, a: ip.String()}
-}
-
-func TestAsIP(t *testing.T) {
- lh := net.ParseIP("127.0.0.1")
- if got, want := netstate.AsIP(&net.IPAddr{IP: lh}), "127.0.0.1"; got == nil || got.String() != want {
- t.Errorf("got %v, want %v", got, want)
- }
- if got, want := netstate.AsIP(&net.IPNet{IP: lh}), "127.0.0.1"; got == nil || got.String() != want {
- t.Errorf("got %v, want %v", got, want)
- }
- if got, want := netstate.AsIP(&ma{"tcp", lh.String()}), "127.0.0.1"; got == nil || got.String() != want {
- t.Errorf("got %v, want %v", got, want)
- }
-}
-
-func TestRoutes(t *testing.T) {
- accessible, err := netstate.GetAccessibleIPs()
- if err != nil {
- t.Fatalf("unexpected error: %s", err)
- }
- ifcl, err := netstate.GetInterfaces()
- if err != nil {
- t.Fatalf("unexpected error: %s", err)
- }
-
- if len(ifcl) == 0 || len(accessible) == 0 {
- t.Errorf("expected non zero lengths, not %d and %d", len(ifcl), len(accessible))
- }
-
- routes := netstate.GetRoutes()
- // Make sure that the routes refer to valid interfaces
- for _, r := range routes {
- found := false
- for _, ifc := range ifcl {
- if r.IfcIndex == ifc.Index {
- found = true
- break
- }
- }
- if !found {
- t.Errorf("failed to find ifc index %d", r.IfcIndex)
- }
- }
-}
-
-func mkAddrIfc(n, a string) *netstate.AddrIfc {
- ip := net.ParseIP(a)
- return &netstate.AddrIfc{
- Addr: &ma{n: n, a: ip.String()},
- }
-}
-
-type hw struct{}
-
-func (*hw) Network() string { return "mac" }
-func (*hw) String() string { return "01:23:45:67:89:ab:cd:ef" }
-
-func TestPredicates(t *testing.T) {
- hwifc := &netstate.AddrIfc{Addr: &hw{}}
- if got, want := netstate.IsUnicastIP(hwifc), false; got != want {
- t.Errorf("got %t, want %t", got, want)
-
- }
- cases := []struct {
- f func(a ipc.Address) bool
- a string
- r bool
- }{
- {netstate.IsUnspecifiedIP, "0.0.0.0", true},
- {netstate.IsUnspecifiedIP, "::", true},
- {netstate.IsUnspecifiedIP, "127.0.0.1", false},
- {netstate.IsUnspecifiedIP, "::1", false},
-
- {netstate.IsLoopbackIP, "0.0.0.0", false},
- {netstate.IsLoopbackIP, "::", false},
- {netstate.IsLoopbackIP, "127.0.0.1", true},
- {netstate.IsLoopbackIP, "::1", true},
-
- {netstate.IsAccessibleIP, "0.0.0.0", false},
- {netstate.IsAccessibleIP, "::", false},
- {netstate.IsAccessibleIP, "127.0.0.1", false},
- {netstate.IsAccessibleIP, "::1", false},
- {netstate.IsAccessibleIP, "224.0.0.2", true},
- {netstate.IsAccessibleIP, "fc00:1234::", true},
- {netstate.IsAccessibleIP, "192.168.1.1", true},
- {netstate.IsAccessibleIP, "2001:4860:0:2001::68", true},
-
- {netstate.IsUnicastIP, "0.0.0.0", false},
- {netstate.IsUnicastIP, "::", false},
- {netstate.IsUnicastIP, "127.0.0.1", true},
- {netstate.IsUnicastIP, "::1", true},
- {netstate.IsUnicastIP, "192.168.1.2", true},
- {netstate.IsUnicastIP, "74.125.239.36", true},
- {netstate.IsUnicastIP, "224.0.0.2", false},
- {netstate.IsUnicastIP, "fc00:1235::", true},
- {netstate.IsUnicastIP, "ff01::01", false},
- {netstate.IsUnicastIP, "2001:4860:0:2001::69", true},
-
- {netstate.IsUnicastIPv4, "0.0.0.0", false},
- {netstate.IsUnicastIPv4, "::", false},
- {netstate.IsUnicastIPv4, "127.0.0.1", true},
- {netstate.IsUnicastIPv4, "::1", false},
- {netstate.IsUnicastIPv4, "192.168.1.3", true},
- {netstate.IsUnicastIPv6, "74.125.239.37", false},
- {netstate.IsUnicastIPv4, "224.0.0.2", false},
- {netstate.IsUnicastIPv4, "fc00:1236::", false},
- {netstate.IsUnicastIPv4, "ff01::02", false},
- {netstate.IsUnicastIPv4, "2001:4860:0:2001::6a", false},
-
- {netstate.IsUnicastIPv6, "0.0.0.0", false},
- {netstate.IsUnicastIPv6, "::", false},
- {netstate.IsUnicastIPv6, "127.0.0.1", false},
- {netstate.IsUnicastIPv6, "::1", true},
- {netstate.IsUnicastIPv6, "192.168.1.4", false},
- {netstate.IsUnicastIPv6, "74.125.239.38", false},
- {netstate.IsUnicastIPv6, "224.0.0.2", false},
- {netstate.IsUnicastIPv6, "fc00:1237::", true},
- {netstate.IsUnicastIPv6, "ff01::03", false},
- {netstate.IsUnicastIPv6, "2607:f8b0:4003:c00::6b", true},
-
- {netstate.IsPublicUnicastIP, "0.0.0.0", false},
- {netstate.IsPublicUnicastIP, "::", false},
- {netstate.IsPublicUnicastIP, "127.0.0.1", false},
- {netstate.IsPublicUnicastIP, "::1", false},
- {netstate.IsPublicUnicastIP, "192.168.1.2", false},
- {netstate.IsPublicUnicastIP, "74.125.239.39", true},
- {netstate.IsPublicUnicastIP, "224.0.0.2", false},
- // Arguably this is buggy, the fc00:/7 prefix is supposed to be
- // non-routable.
- {netstate.IsPublicUnicastIP, "fc00:1238::", true},
- {netstate.IsPublicUnicastIP, "ff01::01", false},
- {netstate.IsPublicUnicastIP, "2001:4860:0:2001::69", true},
-
- {netstate.IsPublicUnicastIPv4, "0.0.0.0", false},
- {netstate.IsPublicUnicastIPv4, "::", false},
- {netstate.IsPublicUnicastIPv4, "127.0.0.1", false},
- {netstate.IsPublicUnicastIPv4, "::1", false},
- {netstate.IsPublicUnicastIPv4, "192.168.1.3", false},
- {netstate.IsPublicUnicastIPv4, "74.125.239.40", true},
- {netstate.IsPublicUnicastIPv4, "224.0.0.2", false},
- {netstate.IsPublicUnicastIPv4, "fc00:1239::", false},
- {netstate.IsPublicUnicastIPv4, "ff01::02", false},
- {netstate.IsPublicUnicastIPv4, "2001:4860:0:2001::6a", false},
-
- {netstate.IsPublicUnicastIPv6, "0.0.0.0", false},
- {netstate.IsPublicUnicastIPv6, "::", false},
- {netstate.IsPublicUnicastIPv6, "127.0.0.1", false},
- {netstate.IsPublicUnicastIPv6, "::1", false},
- {netstate.IsPublicUnicastIPv6, "192.168.1.4", false},
- {netstate.IsPublicUnicastIPv6, "74.125.239.41", false},
- {netstate.IsPublicUnicastIPv6, "224.0.0.2", false},
- // Arguably this is buggy, the fc00:/7 prefix is supposed to be
- // non-routable.
- {netstate.IsPublicUnicastIPv6, "fc00:123a::", true},
- {netstate.IsPublicUnicastIPv6, "ff01::03", false},
- {netstate.IsPublicUnicastIPv6, "2607:f8b0:4003:c00::6b", true},
- }
- for i, c := range cases {
- net := "tcp"
- if got, want := c.f(mkAddrIfc(net, c.a)), c.r; got != want {
- t.Errorf("#%d: %s %s: got %t, want %t", i+1, net, c.a, got, want)
- }
- }
-}
-
-func TestRoutePredicate(t *testing.T) {
- net1_ip, net1, _ := net.ParseCIDR("192.168.1.10/24")
- net2_ip, net2, _ := net.ParseCIDR("172.16.1.11/24")
- net3_ip, net3, _ := net.ParseCIDR("172.16.2.12/24")
- // net4 and net5 are on the same interface.
- net4_ip, net4, _ := net.ParseCIDR("172.19.39.142/23")
- net5_ip, net5, _ := net.ParseCIDR("2620::1000:5e01:56e4:3aff:fef1:1383/64")
-
- rt1 := []*netconfig.IPRoute{{*net1, net.ParseIP("192.168.1.1"), nil, 1}}
- rt2 := []*netconfig.IPRoute{{*net2, net.ParseIP("172.16.1.1"), nil, 2}}
- rt3 := []*netconfig.IPRoute{{*net3, net.ParseIP("172.16.2.1"), nil, 3}}
- rt4_0 := &netconfig.IPRoute{*net4, net.ParseIP("172.19.39.142"), nil, 6}
- rt4_1 := &netconfig.IPRoute{*net5, net.ParseIP("fe80::5:73ff:fea0:fb"), nil, 6}
- rt4 := []*netconfig.IPRoute{rt4_0, rt4_1}
-
- net1_addr := &netstate.AddrIfc{&net.IPAddr{IP: net1_ip}, "eth0", rt1}
- net2_addr := &netstate.AddrIfc{&net.IPAddr{IP: net2_ip}, "eth1", rt2}
- net3_addr := &netstate.AddrIfc{&net.IPAddr{IP: net3_ip}, "eth2", rt3}
- net4_addr := &netstate.AddrIfc{&net.IPAddr{IP: net4_ip}, "wn0", rt4}
- net5_addr := &netstate.AddrIfc{&net.IPAddr{IP: net5_ip}, "wn0", rt4}
-
- al := netstate.AddrList{}
- if got, want := al.Filter(netstate.IsOnDefaultRoute), (netstate.AddrList{}); !reflect.DeepEqual(got, want) {
- t.Errorf("got %v, want %v", got, want)
- }
-
- al = netstate.AddrList{net1_addr, net2_addr, net3_addr, net4_addr, net5_addr}
- if got, want := al.Filter(netstate.IsOnDefaultRoute), (netstate.AddrList{}); !reflect.DeepEqual(got, want) {
- t.Errorf("got %v, want %v", got, want)
- }
-
- defaultRoute := net.IPNet{net.IPv4zero, make([]byte, net.IPv4len)}
- // Make eth1 a default route.
- rt2[0].Net = defaultRoute
- if got, want := al.Filter(netstate.IsOnDefaultRoute), (netstate.AddrList{net2_addr}); !reflect.DeepEqual(got, want) {
- t.Errorf("got %v, want %v", got, want)
- }
-
- // Make wn0 a default route also.
- rt3[0].Net = defaultRoute
- if got, want := al.Filter(netstate.IsOnDefaultRoute), (netstate.AddrList{net2_addr, net3_addr}); !reflect.DeepEqual(got, want) {
- t.Errorf("got %v, want %v", got, want)
- }
-
- // Restore the original route.
- rt2[0].Net = *net2
- rt4_0.Net = defaultRoute
- if got, want := al.Filter(netstate.IsOnDefaultRoute), (netstate.AddrList{net3_addr, net4_addr}); !reflect.DeepEqual(got, want) {
- t.Errorf("got %v, want %v", got, want)
- }
-
- // Shouldn't return the IPv6 default route so long as al doesn't
- // contain any IPv6 default routes.
- rt4_0.Net = *net4
- rt4_1.Net = defaultRoute
- if got, want := al.Filter(netstate.IsOnDefaultRoute), (netstate.AddrList{net3_addr}); !reflect.DeepEqual(got, want) {
- t.Errorf("got %v, want %v", got, want)
- }
-
- // Now that we have an IPv6 default route that matches an IPv6 gateway
- // we can expect to find the IPv6 host address
- rt4_1.Net = net.IPNet{net.IPv6zero, make([]byte, net.IPv6len)}
- if got, want := al.Filter(netstate.IsOnDefaultRoute), (netstate.AddrList{net3_addr, net5_addr}); !reflect.DeepEqual(got, want) {
- t.Errorf("got %v, want %v", got, want)
- }
-}
-
-var (
- a = mkAddrIfc("tcp4", "1.2.3.4")
- b = mkAddrIfc("tcp4", "1.2.3.5")
- c = mkAddrIfc("tcp4", "1.2.3.6")
- d = mkAddrIfc("tcp4", "1.2.3.7")
- a6 = mkAddrIfc("tcp6", "2001:4860:0:2001::68")
- b6 = mkAddrIfc("tcp6", "2001:4860:0:2001::69")
- c6 = mkAddrIfc("tcp6", "2001:4860:0:2001::70")
- d6 = mkAddrIfc("tcp6", "2001:4860:0:2001::71")
-)
-
-func TestRemoved(t *testing.T) {
- al := netstate.AddrList{a, b, c, a6, b6, c6}
- bl := netstate.AddrList{}
-
- // no changes.
- got, want := netstate.FindRemoved(al, al), netstate.AddrList{}
- if !reflect.DeepEqual(got, want) {
- t.Errorf("got %#v, want %#v", got, want)
- }
-
- // missing everything
- if got, want := netstate.FindRemoved(al, bl), al; !reflect.DeepEqual(got, want) {
- t.Errorf("got %s, want %s", got, want)
- }
-
- // missing nothing
- if got, want := netstate.FindRemoved(bl, al), (netstate.AddrList{}); !reflect.DeepEqual(got, want) {
- t.Errorf("got %s, want %s", got, want)
- }
-
- // remove some addresses
- bl = netstate.AddrList{a, b, a6, b6}
- if got, want := netstate.FindRemoved(al, bl), (netstate.AddrList{c, c6}); !reflect.DeepEqual(got, want) {
- t.Errorf("got %s, want %s", got, want)
- }
-
- // add some addresses
- bl = netstate.AddrList{a, b, c, a6, b6, c6, d6}
- if got, want := netstate.FindRemoved(al, bl), (netstate.AddrList{}); !reflect.DeepEqual(got, want) {
- t.Errorf("got %s, want %s", got, want)
- }
-
- // change some addresses
- bl = netstate.AddrList{a, b, d, a6, d6, c6}
- if got, want := netstate.FindRemoved(al, bl), (netstate.AddrList{c, b6}); !reflect.DeepEqual(got, want) {
- t.Errorf("got %s, want %s", got, want)
- }
-}
-
-func TestAdded(t *testing.T) {
- al := netstate.AddrList{a, b, c, a6, b6, c6}
- bl := netstate.AddrList{}
-
- // no changes.
- if got, want := netstate.FindAdded(al, al), (netstate.AddrList{}); !reflect.DeepEqual(got, want) {
- t.Errorf("got %s, want %s", got, want)
- }
-
- // add nothing
- if got, want := netstate.FindAdded(al, bl), bl; !reflect.DeepEqual(got, want) {
- t.Errorf("got %s, want %s", got, want)
- }
-
- // add everything
- if got, want := netstate.FindAdded(bl, al), al; !reflect.DeepEqual(got, want) {
- t.Errorf("got %s, want %s", got, want)
- }
-
- // add some addresses
- bl = netstate.AddrList{a, b, c, d, a6, b6, c6, d6}
- if got, want := netstate.FindAdded(al, bl), (netstate.AddrList{d, d6}); !reflect.DeepEqual(got, want) {
- t.Errorf("got %s, want %s", got, want)
- }
-
- // remove some addresses
- bl = netstate.AddrList{a, b, c, b6}
- if got, want := netstate.FindAdded(al, bl), (netstate.AddrList{}); !reflect.DeepEqual(got, want) {
- t.Errorf("got %s, want %s", got, want)
- }
-
- // change some addresses
- bl = netstate.AddrList{a, d, c, a6, d6, c6}
- if got, want := netstate.FindAdded(al, bl), (netstate.AddrList{d, d6}); !reflect.DeepEqual(got, want) {
- t.Errorf("got %s, want %s", got, want)
- }
-}
-
-// buildNonLocalhostTestAddress constructs a selection of test addresses
-// that are local.
-func buildNonLocalhostTestAddress(t *testing.T) []string {
- addrs, err := net.InterfaceAddrs()
- if err != nil {
- t.Errorf("InterfaceAddrs() failed: %v\n", err)
- }
-
- ips := make([]string, 0, len(addrs))
- for _, a := range addrs {
- ip, _, err := net.ParseCIDR(a.String())
- if err != nil {
- t.Errorf("ParseCIDR() failed: %v\n", err)
- }
- ips = append(ips, net.JoinHostPort(ip.String(), "111"))
- }
- return ips
-}
-
-func TestSameMachine(t *testing.T) {
- cases := []struct {
- Addr *ma
- Same bool
- Err error
- }{
- {
- Addr: &ma{
- n: "tcp",
- a: "batman.com:4444",
- },
- Same: false,
- Err: nil,
- },
- {
- Addr: &ma{
- n: "tcp",
- a: "127.0.0.1:1000",
- },
- Same: true,
- Err: nil,
- },
- {
- Addr: &ma{
- n: "tcp",
- a: "::1/128",
- },
- Same: false,
- Err: &net.AddrError{Err: "too many colons in address", Addr: "::1/128"},
- },
- }
-
- for _, a := range buildNonLocalhostTestAddress(t) {
- cases = append(cases, struct {
- Addr *ma
- Same bool
- Err error
- }{
- Addr: &ma{
- n: "tcp",
- a: a,
- },
- Same: true,
- Err: nil,
- })
- }
-
- for _, v := range cases {
- issame, err := netstate.SameMachine(v.Addr)
- if !reflect.DeepEqual(err, v.Err) {
- t.Errorf("Bad error: got %#v, expected %#v\n", err, v.Err)
- }
- if issame != v.Same {
- t.Errorf("for Endpoint address %v: got %v, expected %v\n", v.Addr.a, issame, v.Same)
- }
- }
-}
diff --git a/lib/netstate/route.go b/lib/netstate/route.go
deleted file mode 100644
index 906dc9e..0000000
--- a/lib/netstate/route.go
+++ /dev/null
@@ -1,105 +0,0 @@
-package netstate
-
-import (
- "fmt"
- "net"
- "strings"
-
- "v.io/v23/ipc"
-
- "v.io/x/ref/lib/netconfig"
-)
-
-// Interface represents a network interface.
-type Interface struct {
- Index int
- Name string
-}
-type InterfaceList []*Interface
-
-// GetInterfaces returns a list of all of the network interfaces on this
-// device.
-func GetInterfaces() (InterfaceList, error) {
- ifcl := InterfaceList{}
- interfaces, err := net.Interfaces()
- if err != nil {
- return nil, err
- }
- for _, ifc := range interfaces {
- ifcl = append(ifcl, &Interface{ifc.Index, ifc.Name})
- }
- return ifcl, nil
-}
-
-func (ifcl InterfaceList) String() string {
- r := ""
- for _, ifc := range ifcl {
- r += fmt.Sprintf("(%d: %s) ", ifc.Index, ifc.Name)
- }
- return strings.TrimRight(r, " ")
-}
-
-// IPRouteList is a slice of IPRoutes as returned by the netconfig package.
-type IPRouteList []*netconfig.IPRoute
-
-func (rl IPRouteList) String() string {
- r := ""
- for _, rt := range rl {
- src := ""
- if len(rt.PreferredSource) > 0 {
- src = ", src: " + rt.PreferredSource.String()
- }
- r += fmt.Sprintf("(%d: net: %s, gw: %s%s) ", rt.IfcIndex, rt.Net, rt.Gateway, src)
- }
- return strings.TrimRight(r, " ")
-}
-
-func GetRoutes() IPRouteList {
- return netconfig.GetIPRoutes(false)
-}
-
-// RoutePredicate defines the function signature for predicate functions
-// to be used with RouteList
-type RoutePredicate func(r *netconfig.IPRoute) bool
-
-// Filter returns all of the routes for which the predicate
-// function is true.
-func (rl IPRouteList) Filter(predicate RoutePredicate) IPRouteList {
- r := IPRouteList{}
- for _, rt := range rl {
- if predicate(rt) {
- r = append(r, rt)
- }
- }
- return r
-}
-
-// IsDefaultRoute returns true if the supplied IPRoute is a default route.
-func IsDefaultRoute(r *netconfig.IPRoute) bool {
- return netconfig.IsDefaultIPRoute(r)
-}
-
-// IsOnDefaultRoute returns true for addresses that are on an interface that
-// has a default route set for the supplied address.
-func IsOnDefaultRoute(a ipc.Address) bool {
- aifc, ok := a.(*AddrIfc)
- if !ok || len(aifc.IPRoutes) == 0 {
- return false
- }
- ipv4 := IsUnicastIPv4(a)
- for _, r := range aifc.IPRoutes {
- // Ignore entries with a nil gateway.
- if r.Gateway == nil {
- continue
- }
- // We have a default route, so we check the gateway to make sure
- // it matches the format of the default route.
- if ipv4 {
- return netconfig.IsDefaultIPv4Route(r) && r.Gateway.To4() != nil
- }
- if netconfig.IsDefaultIPv6Route(r) {
- return true
- }
- }
- return false
-}
diff --git a/profiles/gce/init.go b/profiles/gce/init.go
index e92b472..cf52683 100644
--- a/profiles/gce/init.go
+++ b/profiles/gce/init.go
@@ -14,8 +14,8 @@
"v.io/v23/ipc"
"v.io/x/lib/vlog"
+ "v.io/x/lib/netstate"
"v.io/x/ref/lib/flags"
- "v.io/x/ref/lib/netstate"
"v.io/x/ref/profiles/internal"
"v.io/x/ref/profiles/internal/gce"
_ "v.io/x/ref/profiles/internal/ipc/protocols/tcp"
diff --git a/profiles/internal/ipc/full_test.go b/profiles/internal/ipc/full_test.go
index a8e0077..d01c409 100644
--- a/profiles/internal/ipc/full_test.go
+++ b/profiles/internal/ipc/full_test.go
@@ -29,8 +29,8 @@
"v.io/x/lib/vlog"
"v.io/x/ref/profiles/internal/ipc/stream"
+ "v.io/x/lib/netstate"
"v.io/x/ref/lib/flags"
- "v.io/x/ref/lib/netstate"
"v.io/x/ref/lib/stats"
"v.io/x/ref/lib/testutil"
tsecurity "v.io/x/ref/lib/testutil/security"
diff --git a/profiles/internal/ipc/server.go b/profiles/internal/ipc/server.go
index c289c3d..b1a6739 100644
--- a/profiles/internal/ipc/server.go
+++ b/profiles/internal/ipc/server.go
@@ -25,7 +25,7 @@
"v.io/x/lib/vlog"
"v.io/x/ref/profiles/internal/ipc/stream"
- "v.io/x/ref/lib/netstate"
+ "v.io/x/lib/netstate"
"v.io/x/ref/lib/stats"
"v.io/x/ref/profiles/internal/ipc/stream/vc"
"v.io/x/ref/profiles/internal/lib/publisher"
diff --git a/profiles/internal/ipc/server_test.go b/profiles/internal/ipc/server_test.go
index 2670900..b43c634 100644
--- a/profiles/internal/ipc/server_test.go
+++ b/profiles/internal/ipc/server_test.go
@@ -15,7 +15,7 @@
"v.io/v23/verror"
"v.io/x/lib/vlog"
- "v.io/x/ref/lib/netstate"
+ "v.io/x/lib/netstate"
tsecurity "v.io/x/ref/lib/testutil/security"
imanager "v.io/x/ref/profiles/internal/ipc/stream/manager"
"v.io/x/ref/profiles/internal/ipc/stream/vc"
diff --git a/profiles/internal/ipc/sort_endpoints.go b/profiles/internal/ipc/sort_endpoints.go
index 61a3e5f..b51eb7a 100644
--- a/profiles/internal/ipc/sort_endpoints.go
+++ b/profiles/internal/ipc/sort_endpoints.go
@@ -8,7 +8,7 @@
"v.io/v23/naming"
"v.io/x/lib/vlog"
- "v.io/x/ref/lib/netstate"
+ "v.io/x/lib/netstate"
"v.io/x/ref/profiles/internal/ipc/version"
inaming "v.io/x/ref/profiles/internal/naming"
)
diff --git a/profiles/internal/util.go b/profiles/internal/util.go
index 90bac92..ea659e6 100644
--- a/profiles/internal/util.go
+++ b/profiles/internal/util.go
@@ -8,9 +8,9 @@
"v.io/v23/ipc"
"v.io/x/lib/vlog"
+ "v.io/x/lib/netstate"
"v.io/x/ref/lib/exec"
"v.io/x/ref/lib/flags"
- "v.io/x/ref/lib/netstate"
)
// ParseFlags parses all registered flags taking into account overrides from other
diff --git a/profiles/roaming/net_watcher.go b/profiles/roaming/net_watcher.go
index 89f0e97..0cf414e 100644
--- a/profiles/roaming/net_watcher.go
+++ b/profiles/roaming/net_watcher.go
@@ -9,7 +9,7 @@
"v.io/v23"
"v.io/v23/config"
- "v.io/x/ref/lib/netstate"
+ "v.io/x/lib/netstate"
"v.io/x/ref/profiles/roaming"
)
diff --git a/profiles/roaming/print_addrs.go b/profiles/roaming/print_addrs.go
index 98a82cd..eda0e7e 100644
--- a/profiles/roaming/print_addrs.go
+++ b/profiles/roaming/print_addrs.go
@@ -4,7 +4,7 @@
import (
"fmt"
- "v.io/x/ref/lib/netstate"
+ "v.io/x/lib/netstate"
)
func main() {
diff --git a/profiles/roaming/roaminginit.go b/profiles/roaming/roaminginit.go
index adbe94b..e43f512 100644
--- a/profiles/roaming/roaminginit.go
+++ b/profiles/roaming/roaminginit.go
@@ -19,9 +19,9 @@
"v.io/v23/ipc"
"v.io/x/lib/vlog"
+ "v.io/x/lib/netconfig"
+ "v.io/x/lib/netstate"
"v.io/x/ref/lib/flags"
- "v.io/x/ref/lib/netconfig"
- "v.io/x/ref/lib/netstate"
"v.io/x/ref/profiles/internal"
_ "v.io/x/ref/profiles/internal/ipc/protocols/tcp"
_ "v.io/x/ref/profiles/internal/ipc/protocols/ws"
diff --git a/profiles/static/staticinit.go b/profiles/static/staticinit.go
index f837434..b94f6ff 100644
--- a/profiles/static/staticinit.go
+++ b/profiles/static/staticinit.go
@@ -8,8 +8,8 @@
"v.io/v23/ipc"
"v.io/x/lib/vlog"
+ "v.io/x/lib/netstate"
"v.io/x/ref/lib/flags"
- "v.io/x/ref/lib/netstate"
"v.io/x/ref/profiles/internal"
_ "v.io/x/ref/profiles/internal/ipc/protocols/tcp"
_ "v.io/x/ref/profiles/internal/ipc/protocols/ws"
diff --git a/services/mgmt/binary/binaryd/main.go b/services/mgmt/binary/binaryd/main.go
index ad6e1ae..e20c7d2 100644
--- a/services/mgmt/binary/binaryd/main.go
+++ b/services/mgmt/binary/binaryd/main.go
@@ -10,7 +10,7 @@
"v.io/v23/context"
"v.io/x/lib/vlog"
- "v.io/x/ref/lib/netstate"
+ "v.io/x/lib/netstate"
"v.io/x/ref/lib/signals"
_ "v.io/x/ref/profiles/roaming"
"v.io/x/ref/services/mgmt/binary/impl"
diff --git a/services/mgmt/device/starter/starter.go b/services/mgmt/device/starter/starter.go
index f1fc91d..b53337b 100644
--- a/services/mgmt/device/starter/starter.go
+++ b/services/mgmt/device/starter/starter.go
@@ -11,7 +11,7 @@
"strconv"
"time"
- "v.io/x/ref/lib/netstate"
+ "v.io/x/lib/netstate"
"v.io/x/ref/profiles/roaming"
"v.io/x/ref/services/mgmt/device/config"
"v.io/x/ref/services/mgmt/device/impl"
diff --git a/services/mounttable/lib/neighborhood.go b/services/mounttable/lib/neighborhood.go
index 17b6b3a..bed075c 100644
--- a/services/mounttable/lib/neighborhood.go
+++ b/services/mounttable/lib/neighborhood.go
@@ -6,8 +6,8 @@
"strconv"
"strings"
+ "v.io/x/lib/netconfig"
"v.io/x/ref/lib/glob"
- "v.io/x/ref/lib/netconfig"
"v.io/v23"
"v.io/v23/ipc"