utils.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. // Network utility functions.
  2. package netutils
  3. import (
  4. "crypto/rand"
  5. "encoding/hex"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "net"
  10. "strings"
  11. "github.com/docker/libnetwork/types"
  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. // CheckNameserverOverlaps checks whether the passed network overlaps with any of the nameservers
  24. func CheckNameserverOverlaps(nameservers []string, toCheck *net.IPNet) error {
  25. if len(nameservers) > 0 {
  26. for _, ns := range nameservers {
  27. _, nsNetwork, err := net.ParseCIDR(ns)
  28. if err != nil {
  29. return err
  30. }
  31. if NetworkOverlaps(toCheck, nsNetwork) {
  32. return ErrNetworkOverlapsWithNameservers
  33. }
  34. }
  35. }
  36. return nil
  37. }
  38. // CheckRouteOverlaps checks whether the passed network overlaps with any existing routes
  39. func CheckRouteOverlaps(toCheck *net.IPNet) error {
  40. networks, err := networkGetRoutesFct(nil, netlink.FAMILY_V4)
  41. if err != nil {
  42. return err
  43. }
  44. for _, network := range networks {
  45. if network.Dst != nil && NetworkOverlaps(toCheck, network.Dst) {
  46. return ErrNetworkOverlaps
  47. }
  48. }
  49. return nil
  50. }
  51. // NetworkOverlaps detects overlap between one IPNet and another
  52. func NetworkOverlaps(netX *net.IPNet, netY *net.IPNet) bool {
  53. // Check if both netX and netY are ipv4 or ipv6
  54. if (netX.IP.To4() != nil && netY.IP.To4() != nil) ||
  55. (netX.IP.To4() == nil && netY.IP.To4() == nil) {
  56. if firstIP, _ := NetworkRange(netX); netY.Contains(firstIP) {
  57. return true
  58. }
  59. if firstIP, _ := NetworkRange(netY); netX.Contains(firstIP) {
  60. return true
  61. }
  62. }
  63. return false
  64. }
  65. // NetworkRange calculates the first and last IP addresses in an IPNet
  66. func NetworkRange(network *net.IPNet) (net.IP, net.IP) {
  67. if network == nil {
  68. return nil, nil
  69. }
  70. firstIP := network.IP.Mask(network.Mask)
  71. lastIP := types.GetIPCopy(firstIP)
  72. for i := 0; i < len(firstIP); i++ {
  73. lastIP[i] = firstIP[i] | ^network.Mask[i]
  74. }
  75. if network.IP.To4() != nil {
  76. firstIP = firstIP.To4()
  77. lastIP = lastIP.To4()
  78. }
  79. return firstIP, lastIP
  80. }
  81. // GetIfaceAddr returns the first IPv4 address and slice of IPv6 addresses for the specified network interface
  82. func GetIfaceAddr(name string) (net.Addr, []net.Addr, error) {
  83. iface, err := net.InterfaceByName(name)
  84. if err != nil {
  85. return nil, nil, err
  86. }
  87. addrs, err := iface.Addrs()
  88. if err != nil {
  89. return nil, nil, err
  90. }
  91. var addrs4 []net.Addr
  92. var addrs6 []net.Addr
  93. for _, addr := range addrs {
  94. ip := (addr.(*net.IPNet)).IP
  95. if ip4 := ip.To4(); ip4 != nil {
  96. addrs4 = append(addrs4, addr)
  97. } else if ip6 := ip.To16(); len(ip6) == net.IPv6len {
  98. addrs6 = append(addrs6, addr)
  99. }
  100. }
  101. switch {
  102. case len(addrs4) == 0:
  103. return nil, nil, fmt.Errorf("Interface %v has no IPv4 addresses", name)
  104. case len(addrs4) > 1:
  105. fmt.Printf("Interface %v has more than 1 IPv4 address. Defaulting to using %v\n",
  106. name, (addrs4[0].(*net.IPNet)).IP)
  107. }
  108. return addrs4[0], addrs6, nil
  109. }
  110. func genMAC(ip net.IP) net.HardwareAddr {
  111. hw := make(net.HardwareAddr, 6)
  112. // The first byte of the MAC address has to comply with these rules:
  113. // 1. Unicast: Set the least-significant bit to 0.
  114. // 2. Address is locally administered: Set the second-least-significant bit (U/L) to 1.
  115. hw[0] = 0x02
  116. // The first 24 bits of the MAC represent the Organizationally Unique Identifier (OUI).
  117. // Since this address is locally administered, we can do whatever we want as long as
  118. // it doesn't conflict with other addresses.
  119. hw[1] = 0x42
  120. // Fill the remaining 4 bytes based on the input
  121. if ip == nil {
  122. rand.Read(hw[2:])
  123. } else {
  124. copy(hw[2:], ip.To4())
  125. }
  126. return hw
  127. }
  128. // GenerateRandomMAC returns a new 6-byte(48-bit) hardware address (MAC)
  129. func GenerateRandomMAC() net.HardwareAddr {
  130. return genMAC(nil)
  131. }
  132. // GenerateMACFromIP returns a locally administered MAC address where the 4 least
  133. // significant bytes are derived from the IPv4 address.
  134. func GenerateMACFromIP(ip net.IP) net.HardwareAddr {
  135. return genMAC(ip)
  136. }
  137. // GenerateRandomName returns a new name joined with a prefix. This size
  138. // specified is used to truncate the randomly generated value
  139. func GenerateRandomName(prefix string, size int) (string, error) {
  140. id := make([]byte, 32)
  141. if _, err := io.ReadFull(rand.Reader, id); err != nil {
  142. return "", err
  143. }
  144. return prefix + hex.EncodeToString(id)[:size], nil
  145. }
  146. // GenerateIfaceName returns an interface name using the passed in
  147. // prefix and the length of random bytes. The api ensures that the
  148. // there are is no interface which exists with that name.
  149. func GenerateIfaceName(prefix string, len int) (string, error) {
  150. for i := 0; i < 3; i++ {
  151. name, err := GenerateRandomName(prefix, len)
  152. if err != nil {
  153. continue
  154. }
  155. if _, err := net.InterfaceByName(name); err != nil {
  156. if strings.Contains(err.Error(), "no such") {
  157. return name, nil
  158. }
  159. return "", err
  160. }
  161. }
  162. return "", types.InternalErrorf("could not generate interface name")
  163. }