utils.go 6.0 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. return netX.Contains(netY.IP) || netY.Contains(netX.IP)
  54. }
  55. // NetworkRange calculates the first and last IP addresses in an IPNet
  56. func NetworkRange(network *net.IPNet) (net.IP, net.IP) {
  57. if network == nil {
  58. return nil, nil
  59. }
  60. firstIP := network.IP.Mask(network.Mask)
  61. lastIP := types.GetIPCopy(firstIP)
  62. for i := 0; i < len(firstIP); i++ {
  63. lastIP[i] = firstIP[i] | ^network.Mask[i]
  64. }
  65. if network.IP.To4() != nil {
  66. firstIP = firstIP.To4()
  67. lastIP = lastIP.To4()
  68. }
  69. return firstIP, lastIP
  70. }
  71. // GetIfaceAddr returns the first IPv4 address and slice of IPv6 addresses for the specified network interface
  72. func GetIfaceAddr(name string) (net.Addr, []net.Addr, error) {
  73. iface, err := net.InterfaceByName(name)
  74. if err != nil {
  75. return nil, nil, err
  76. }
  77. addrs, err := iface.Addrs()
  78. if err != nil {
  79. return nil, nil, err
  80. }
  81. var addrs4 []net.Addr
  82. var addrs6 []net.Addr
  83. for _, addr := range addrs {
  84. ip := (addr.(*net.IPNet)).IP
  85. if ip4 := ip.To4(); ip4 != nil {
  86. addrs4 = append(addrs4, addr)
  87. } else if ip6 := ip.To16(); len(ip6) == net.IPv6len {
  88. addrs6 = append(addrs6, addr)
  89. }
  90. }
  91. switch {
  92. case len(addrs4) == 0:
  93. return nil, nil, fmt.Errorf("Interface %v has no IPv4 addresses", name)
  94. case len(addrs4) > 1:
  95. fmt.Printf("Interface %v has more than 1 IPv4 address. Defaulting to using %v\n",
  96. name, (addrs4[0].(*net.IPNet)).IP)
  97. }
  98. return addrs4[0], addrs6, nil
  99. }
  100. func genMAC(ip net.IP) net.HardwareAddr {
  101. hw := make(net.HardwareAddr, 6)
  102. // The first byte of the MAC address has to comply with these rules:
  103. // 1. Unicast: Set the least-significant bit to 0.
  104. // 2. Address is locally administered: Set the second-least-significant bit (U/L) to 1.
  105. hw[0] = 0x02
  106. // The first 24 bits of the MAC represent the Organizationally Unique Identifier (OUI).
  107. // Since this address is locally administered, we can do whatever we want as long as
  108. // it doesn't conflict with other addresses.
  109. hw[1] = 0x42
  110. // Fill the remaining 4 bytes based on the input
  111. if ip == nil {
  112. rand.Read(hw[2:])
  113. } else {
  114. copy(hw[2:], ip.To4())
  115. }
  116. return hw
  117. }
  118. // GenerateRandomMAC returns a new 6-byte(48-bit) hardware address (MAC)
  119. func GenerateRandomMAC() net.HardwareAddr {
  120. return genMAC(nil)
  121. }
  122. // GenerateMACFromIP returns a locally administered MAC address where the 4 least
  123. // significant bytes are derived from the IPv4 address.
  124. func GenerateMACFromIP(ip net.IP) net.HardwareAddr {
  125. return genMAC(ip)
  126. }
  127. // GenerateRandomName returns a new name joined with a prefix. This size
  128. // specified is used to truncate the randomly generated value
  129. func GenerateRandomName(prefix string, size int) (string, error) {
  130. id := make([]byte, 32)
  131. if _, err := io.ReadFull(rand.Reader, id); err != nil {
  132. return "", err
  133. }
  134. return prefix + hex.EncodeToString(id)[:size], nil
  135. }
  136. // GenerateIfaceName returns an interface name using the passed in
  137. // prefix and the length of random bytes. The api ensures that the
  138. // there are is no interface which exists with that name.
  139. func GenerateIfaceName(prefix string, len int) (string, error) {
  140. for i := 0; i < 3; i++ {
  141. name, err := GenerateRandomName(prefix, len)
  142. if err != nil {
  143. continue
  144. }
  145. if _, err := net.InterfaceByName(name); err != nil {
  146. if strings.Contains(err.Error(), "no such") {
  147. return name, nil
  148. }
  149. return "", err
  150. }
  151. }
  152. return "", types.InternalErrorf("could not generate interface name")
  153. }
  154. func byteArrayToInt(array []byte, numBytes int) uint64 {
  155. if numBytes <= 0 || numBytes > 8 {
  156. panic("Invalid argument")
  157. }
  158. num := 0
  159. for i := 0; i <= len(array)-1; i++ {
  160. num += int(array[len(array)-1-i]) << uint(i*8)
  161. }
  162. return uint64(num)
  163. }
  164. // ATo64 converts a byte array into a uint32
  165. func ATo64(array []byte) uint64 {
  166. return byteArrayToInt(array, 8)
  167. }
  168. // ATo32 converts a byte array into a uint32
  169. func ATo32(array []byte) uint32 {
  170. return uint32(byteArrayToInt(array, 4))
  171. }
  172. // ATo16 converts a byte array into a uint16
  173. func ATo16(array []byte) uint16 {
  174. return uint16(byteArrayToInt(array, 2))
  175. }
  176. func intToByteArray(val uint64, numBytes int) []byte {
  177. array := make([]byte, numBytes)
  178. for i := numBytes - 1; i >= 0; i-- {
  179. array[i] = byte(val & 0xff)
  180. val = val >> 8
  181. }
  182. return array
  183. }
  184. // U64ToA converts a uint64 to a byte array
  185. func U64ToA(val uint64) []byte {
  186. return intToByteArray(uint64(val), 8)
  187. }
  188. // U32ToA converts a uint64 to a byte array
  189. func U32ToA(val uint32) []byte {
  190. return intToByteArray(uint64(val), 4)
  191. }
  192. // U16ToA converts a uint64 to a byte array
  193. func U16ToA(val uint16) []byte {
  194. return intToByteArray(uint64(val), 2)
  195. }