utils.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. // Network utility functions.
  2. package netutils
  3. import (
  4. "bytes"
  5. "crypto/rand"
  6. "encoding/hex"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "net"
  11. "strings"
  12. "github.com/vishvananda/netlink"
  13. )
  14. var (
  15. // ErrNetworkOverlapsWithNameservers preformatted error
  16. ErrNetworkOverlapsWithNameservers = errors.New("requested network overlaps with nameserver")
  17. // ErrNetworkOverlaps preformatted error
  18. ErrNetworkOverlaps = errors.New("requested network overlaps with existing network")
  19. // ErrNoDefaultRoute preformatted error
  20. ErrNoDefaultRoute = errors.New("no default route")
  21. networkGetRoutesFct = netlink.RouteList
  22. )
  23. // ErrInvalidProtocolBinding is returned when the port binding protocol is not valid.
  24. type ErrInvalidProtocolBinding string
  25. func (ipb ErrInvalidProtocolBinding) Error() string {
  26. return fmt.Sprintf("invalid transport protocol: %s", string(ipb))
  27. }
  28. // TransportPort represent a local Layer 4 endpoint
  29. type TransportPort struct {
  30. Proto Protocol
  31. Port uint16
  32. }
  33. // PortBinding represent a port binding between the container an the host
  34. type PortBinding struct {
  35. Proto Protocol
  36. IP net.IP
  37. Port uint16
  38. HostIP net.IP
  39. HostPort uint16
  40. }
  41. // HostAddr returns the host side tranport address
  42. func (p PortBinding) HostAddr() (net.Addr, error) {
  43. switch p.Proto {
  44. case UDP:
  45. return &net.UDPAddr{IP: p.HostIP, Port: int(p.HostPort)}, nil
  46. case TCP:
  47. return &net.TCPAddr{IP: p.HostIP, Port: int(p.HostPort)}, nil
  48. default:
  49. return nil, ErrInvalidProtocolBinding(p.Proto.String())
  50. }
  51. }
  52. // ContainerAddr returns the container side tranport address
  53. func (p PortBinding) ContainerAddr() (net.Addr, error) {
  54. switch p.Proto {
  55. case UDP:
  56. return &net.UDPAddr{IP: p.IP, Port: int(p.Port)}, nil
  57. case TCP:
  58. return &net.TCPAddr{IP: p.IP, Port: int(p.Port)}, nil
  59. default:
  60. return nil, ErrInvalidProtocolBinding(p.Proto.String())
  61. }
  62. }
  63. // GetCopy returns a copy of this PortBinding structure instance
  64. func (p *PortBinding) GetCopy() PortBinding {
  65. return PortBinding{
  66. Proto: p.Proto,
  67. IP: GetIPCopy(p.IP),
  68. Port: p.Port,
  69. HostIP: GetIPCopy(p.HostIP),
  70. HostPort: p.HostPort,
  71. }
  72. }
  73. const (
  74. // ICMP is for the ICMP ip protocol
  75. ICMP = 1
  76. // TCP is for the TCP ip protocol
  77. TCP = 6
  78. // UDP is for the UDP ip protocol
  79. UDP = 17
  80. )
  81. // Protocol represents a IP protocol number
  82. type Protocol uint8
  83. func (p Protocol) String() string {
  84. switch p {
  85. case 1:
  86. return "icmp"
  87. case 6:
  88. return "tcp"
  89. case 17:
  90. return "udp"
  91. default:
  92. return fmt.Sprintf("%d", p)
  93. }
  94. }
  95. // ParseProtocol returns the respective Protocol type for the passed string
  96. func ParseProtocol(s string) Protocol {
  97. switch strings.ToLower(s) {
  98. case "icmp":
  99. return 1
  100. case "udp":
  101. return 6
  102. case "tcp":
  103. return 17
  104. default:
  105. return 0
  106. }
  107. }
  108. // CheckNameserverOverlaps checks whether the passed network overlaps with any of the nameservers
  109. func CheckNameserverOverlaps(nameservers []string, toCheck *net.IPNet) error {
  110. if len(nameservers) > 0 {
  111. for _, ns := range nameservers {
  112. _, nsNetwork, err := net.ParseCIDR(ns)
  113. if err != nil {
  114. return err
  115. }
  116. if NetworkOverlaps(toCheck, nsNetwork) {
  117. return ErrNetworkOverlapsWithNameservers
  118. }
  119. }
  120. }
  121. return nil
  122. }
  123. // CheckRouteOverlaps checks whether the passed network overlaps with any existing routes
  124. func CheckRouteOverlaps(toCheck *net.IPNet) error {
  125. networks, err := networkGetRoutesFct(nil, netlink.FAMILY_V4)
  126. if err != nil {
  127. return err
  128. }
  129. for _, network := range networks {
  130. if network.Dst != nil && NetworkOverlaps(toCheck, network.Dst) {
  131. return ErrNetworkOverlaps
  132. }
  133. }
  134. return nil
  135. }
  136. // NetworkOverlaps detects overlap between one IPNet and another
  137. func NetworkOverlaps(netX *net.IPNet, netY *net.IPNet) bool {
  138. if len(netX.IP) == len(netY.IP) {
  139. if firstIP, _ := NetworkRange(netX); netY.Contains(firstIP) {
  140. return true
  141. }
  142. if firstIP, _ := NetworkRange(netY); netX.Contains(firstIP) {
  143. return true
  144. }
  145. }
  146. return false
  147. }
  148. // NetworkRange calculates the first and last IP addresses in an IPNet
  149. func NetworkRange(network *net.IPNet) (net.IP, net.IP) {
  150. var netIP net.IP
  151. if network.IP.To4() != nil {
  152. netIP = network.IP.To4()
  153. } else if network.IP.To16() != nil {
  154. netIP = network.IP.To16()
  155. } else {
  156. return nil, nil
  157. }
  158. lastIP := make([]byte, len(netIP), len(netIP))
  159. for i := 0; i < len(netIP); i++ {
  160. lastIP[i] = netIP[i] | ^network.Mask[i]
  161. }
  162. return netIP.Mask(network.Mask), net.IP(lastIP)
  163. }
  164. // GetIfaceAddr returns the first IPv4 address and slice of IPv6 addresses for the specified network interface
  165. func GetIfaceAddr(name string) (net.Addr, []net.Addr, error) {
  166. iface, err := net.InterfaceByName(name)
  167. if err != nil {
  168. return nil, nil, err
  169. }
  170. addrs, err := iface.Addrs()
  171. if err != nil {
  172. return nil, nil, err
  173. }
  174. var addrs4 []net.Addr
  175. var addrs6 []net.Addr
  176. for _, addr := range addrs {
  177. ip := (addr.(*net.IPNet)).IP
  178. if ip4 := ip.To4(); ip4 != nil {
  179. addrs4 = append(addrs4, addr)
  180. } else if ip6 := ip.To16(); len(ip6) == net.IPv6len {
  181. addrs6 = append(addrs6, addr)
  182. }
  183. }
  184. switch {
  185. case len(addrs4) == 0:
  186. return nil, nil, fmt.Errorf("Interface %v has no IPv4 addresses", name)
  187. case len(addrs4) > 1:
  188. fmt.Printf("Interface %v has more than 1 IPv4 address. Defaulting to using %v\n",
  189. name, (addrs4[0].(*net.IPNet)).IP)
  190. }
  191. return addrs4[0], addrs6, nil
  192. }
  193. // GenerateRandomMAC returns a new 6-byte(48-bit) hardware address (MAC)
  194. func GenerateRandomMAC() net.HardwareAddr {
  195. hw := make(net.HardwareAddr, 6)
  196. // The first byte of the MAC address has to comply with these rules:
  197. // 1. Unicast: Set the least-significant bit to 0.
  198. // 2. Address is locally administered: Set the second-least-significant bit (U/L) to 1.
  199. // 3. As "small" as possible: The veth address has to be "smaller" than the bridge address.
  200. hw[0] = 0x02
  201. // The first 24 bits of the MAC represent the Organizationally Unique Identifier (OUI).
  202. // Since this address is locally administered, we can do whatever we want as long as
  203. // it doesn't conflict with other addresses.
  204. hw[1] = 0x42
  205. // Randomly generate the remaining 4 bytes (2^32)
  206. _, err := rand.Read(hw[2:])
  207. if err != nil {
  208. return nil
  209. }
  210. return hw
  211. }
  212. // GenerateRandomName returns a new name joined with a prefix. This size
  213. // specified is used to truncate the randomly generated value
  214. func GenerateRandomName(prefix string, size int) (string, error) {
  215. id := make([]byte, 32)
  216. if _, err := io.ReadFull(rand.Reader, id); err != nil {
  217. return "", err
  218. }
  219. return prefix + hex.EncodeToString(id)[:size], nil
  220. }
  221. // GetIPCopy returns a copy of the passed IP address
  222. func GetIPCopy(from net.IP) net.IP {
  223. to := make(net.IP, len(from))
  224. copy(to, from)
  225. return to
  226. }
  227. // GetIPNetCopy returns a copy of the passed IP Network
  228. func GetIPNetCopy(from *net.IPNet) *net.IPNet {
  229. if from == nil {
  230. return nil
  231. }
  232. bm := make(net.IPMask, len(from.Mask))
  233. copy(bm, from.Mask)
  234. return &net.IPNet{IP: GetIPCopy(from.IP), Mask: bm}
  235. }
  236. // CompareIPNet returns equal if the two IP Networks are equal
  237. func CompareIPNet(a, b *net.IPNet) bool {
  238. if a == b {
  239. return true
  240. }
  241. if a == nil || b == nil {
  242. return false
  243. }
  244. return a.IP.Equal(b.IP) && bytes.Equal(a.Mask, b.Mask)
  245. }