blob: f430147b7ac0f71578ce0d2a06b8bce4022658da [file] [log] [blame]
Cosmos Nicolaou66bc1202014-09-30 20:42:43 -07001package netstate
2
3import (
4 "fmt"
5 "net"
6 "strings"
7
Jiri Simsa764efb72014-12-25 20:57:03 -08008 "v.io/core/veyron2/ipc"
Cosmos Nicolaou66bc1202014-09-30 20:42:43 -07009
Jiri Simsa764efb72014-12-25 20:57:03 -080010 "v.io/core/veyron/lib/netconfig"
Cosmos Nicolaou66bc1202014-09-30 20:42:43 -070011)
12
13// Interface represents a network interface.
14type Interface struct {
15 Index int
16 Name string
17}
18type InterfaceList []*Interface
19
20// GetInterfaces returns a list of all of the network interfaces on this
21// device.
22func GetInterfaces() (InterfaceList, error) {
23 ifcl := InterfaceList{}
24 interfaces, err := net.Interfaces()
25 if err != nil {
26 return nil, err
27 }
28 for _, ifc := range interfaces {
29 ifcl = append(ifcl, &Interface{ifc.Index, ifc.Name})
30 }
31 return ifcl, nil
32}
33
34func (ifcl InterfaceList) String() string {
35 r := ""
36 for _, ifc := range ifcl {
37 r += fmt.Sprintf("(%d: %s) ", ifc.Index, ifc.Name)
38 }
39 return strings.TrimRight(r, " ")
40}
41
42// IPRouteList is a slice of IPRoutes as returned by the netconfig package.
43type IPRouteList []*netconfig.IPRoute
44
45func (rl IPRouteList) String() string {
46 r := ""
47 for _, rt := range rl {
48 src := ""
49 if len(rt.PreferredSource) > 0 {
50 src = ", src: " + rt.PreferredSource.String()
51 }
52 r += fmt.Sprintf("(%d: net: %s, gw: %s%s) ", rt.IfcIndex, rt.Net, rt.Gateway, src)
53 }
54 return strings.TrimRight(r, " ")
55}
56
57func GetRoutes() IPRouteList {
58 return netconfig.GetIPRoutes(false)
59}
60
61// RoutePredicate defines the function signature for predicate functions
62// to be used with RouteList
63type RoutePredicate func(r *netconfig.IPRoute) bool
64
65// Filter returns all of the routes for which the predicate
66// function is true.
67func (rl IPRouteList) Filter(predicate RoutePredicate) IPRouteList {
68 r := IPRouteList{}
69 for _, rt := range rl {
70 if predicate(rt) {
71 r = append(r, rt)
72 }
73 }
74 return r
75}
76
77// IsDefaultRoute returns true if the supplied IPRoute is a default route.
78func IsDefaultRoute(r *netconfig.IPRoute) bool {
79 return netconfig.IsDefaultIPRoute(r)
80}
81
82// IsOnDefaultRoute returns true for addresses that are on an interface that
83// has a default route set for the supplied address.
84func IsOnDefaultRoute(a ipc.Address) bool {
85 aifc, ok := a.(*AddrIfc)
86 if !ok || len(aifc.IPRoutes) == 0 {
87 return false
88 }
89 ipv4 := IsUnicastIPv4(a)
90 for _, r := range aifc.IPRoutes {
91 // Ignore entries with a nil gateway.
92 if r.Gateway == nil {
93 continue
94 }
95 // We have a default route, so we check the gateway to make sure
96 // it matches the format of the default route.
97 if ipv4 {
98 return netconfig.IsDefaultIPv4Route(r) && r.Gateway.To4() != nil
99 }
100 if netconfig.IsDefaultIPv6Route(r) {
101 return true
102 }
103 }
104 return false
105}