utils.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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. // GenerateRandomMAC returns a new 6-byte(48-bit) hardware address (MAC)
  111. func GenerateRandomMAC() net.HardwareAddr {
  112. hw := make(net.HardwareAddr, 6)
  113. // The first byte of the MAC address has to comply with these rules:
  114. // 1. Unicast: Set the least-significant bit to 0.
  115. // 2. Address is locally administered: Set the second-least-significant bit (U/L) to 1.
  116. // 3. As "small" as possible: The veth address has to be "smaller" than the bridge address.
  117. hw[0] = 0x02
  118. // The first 24 bits of the MAC represent the Organizationally Unique Identifier (OUI).
  119. // Since this address is locally administered, we can do whatever we want as long as
  120. // it doesn't conflict with other addresses.
  121. hw[1] = 0x42
  122. // Randomly generate the remaining 4 bytes (2^32)
  123. _, err := rand.Read(hw[2:])
  124. if err != nil {
  125. return nil
  126. }
  127. return hw
  128. }
  129. // GenerateRandomName returns a new name joined with a prefix. This size
  130. // specified is used to truncate the randomly generated value
  131. func GenerateRandomName(prefix string, size int) (string, error) {
  132. id := make([]byte, 32)
  133. if _, err := io.ReadFull(rand.Reader, id); err != nil {
  134. return "", err
  135. }
  136. return prefix + hex.EncodeToString(id)[:size], nil
  137. }
  138. // GenerateIfaceName returns an interface name using the passed in
  139. // prefix and the length of random bytes. The api ensures that the
  140. // there are is no interface which exists with that name.
  141. func GenerateIfaceName(prefix string, len int) (string, error) {
  142. for i := 0; i < 3; i++ {
  143. name, err := GenerateRandomName(prefix, len)
  144. if err != nil {
  145. continue
  146. }
  147. if _, err := net.InterfaceByName(name); err != nil {
  148. if strings.Contains(err.Error(), "no such") {
  149. return name, nil
  150. }
  151. return "", err
  152. }
  153. }
  154. return "", types.InternalErrorf("could not generate interface name")
  155. }
  156. func byteArrayToInt(array []byte, numBytes int) uint64 {
  157. if numBytes <= 0 || numBytes > 8 {
  158. panic("Invalid argument")
  159. }
  160. num := 0
  161. for i := 0; i <= len(array)-1; i++ {
  162. num += int(array[len(array)-1-i]) << uint(i*8)
  163. }
  164. return uint64(num)
  165. }
  166. // ATo64 converts a byte array into a uint32
  167. func ATo64(array []byte) uint64 {
  168. return byteArrayToInt(array, 8)
  169. }
  170. // ATo32 converts a byte array into a uint32
  171. func ATo32(array []byte) uint32 {
  172. return uint32(byteArrayToInt(array, 4))
  173. }
  174. // ATo16 converts a byte array into a uint16
  175. func ATo16(array []byte) uint16 {
  176. return uint16(byteArrayToInt(array, 2))
  177. }
  178. func intToByteArray(val uint64, numBytes int) []byte {
  179. array := make([]byte, numBytes)
  180. for i := numBytes - 1; i >= 0; i-- {
  181. array[i] = byte(val & 0xff)
  182. val = val >> 8
  183. }
  184. return array
  185. }
  186. // U64ToA converts a uint64 to a byte array
  187. func U64ToA(val uint64) []byte {
  188. return intToByteArray(uint64(val), 8)
  189. }
  190. // U32ToA converts a uint64 to a byte array
  191. func U32ToA(val uint32) []byte {
  192. return intToByteArray(uint64(val), 4)
  193. }
  194. // U16ToA converts a uint64 to a byte array
  195. func U16ToA(val uint16) []byte {
  196. return intToByteArray(uint64(val), 2)
  197. }