utils.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. // Network utility functions.
  2. package netutils
  3. import (
  4. "context"
  5. "crypto/rand"
  6. "encoding/hex"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "net"
  11. "strings"
  12. "sync"
  13. "github.com/containerd/log"
  14. "github.com/docker/docker/libnetwork/types"
  15. )
  16. var (
  17. // ErrNetworkOverlapsWithNameservers preformatted error
  18. ErrNetworkOverlapsWithNameservers = errors.New("requested network overlaps with nameserver")
  19. // ErrNetworkOverlaps preformatted error
  20. ErrNetworkOverlaps = errors.New("requested network overlaps with existing network")
  21. )
  22. // CheckNameserverOverlaps checks whether the passed network overlaps with any of the nameservers
  23. func CheckNameserverOverlaps(nameservers []string, toCheck *net.IPNet) error {
  24. if len(nameservers) > 0 {
  25. for _, ns := range nameservers {
  26. _, nsNetwork, err := net.ParseCIDR(ns)
  27. if err != nil {
  28. return err
  29. }
  30. if NetworkOverlaps(toCheck, nsNetwork) {
  31. return ErrNetworkOverlapsWithNameservers
  32. }
  33. }
  34. }
  35. return nil
  36. }
  37. // NetworkOverlaps detects overlap between one IPNet and another
  38. func NetworkOverlaps(netX *net.IPNet, netY *net.IPNet) bool {
  39. return netX.Contains(netY.IP) || netY.Contains(netX.IP)
  40. }
  41. // NetworkRange calculates the first and last IP addresses in an IPNet
  42. func NetworkRange(network *net.IPNet) (net.IP, net.IP) {
  43. if network == nil {
  44. return nil, nil
  45. }
  46. firstIP := network.IP.Mask(network.Mask)
  47. lastIP := types.GetIPCopy(firstIP)
  48. for i := 0; i < len(firstIP); i++ {
  49. lastIP[i] = firstIP[i] | ^network.Mask[i]
  50. }
  51. if network.IP.To4() != nil {
  52. firstIP = firstIP.To4()
  53. lastIP = lastIP.To4()
  54. }
  55. return firstIP, lastIP
  56. }
  57. func genMAC(ip net.IP) net.HardwareAddr {
  58. hw := make(net.HardwareAddr, 6)
  59. // The first byte of the MAC address has to comply with these rules:
  60. // 1. Unicast: Set the least-significant bit to 0.
  61. // 2. Address is locally administered: Set the second-least-significant bit (U/L) to 1.
  62. hw[0] = 0x02
  63. // The first 24 bits of the MAC represent the Organizationally Unique Identifier (OUI).
  64. // Since this address is locally administered, we can do whatever we want as long as
  65. // it doesn't conflict with other addresses.
  66. hw[1] = 0x42
  67. // Fill the remaining 4 bytes based on the input
  68. if ip == nil {
  69. rand.Read(hw[2:])
  70. } else {
  71. copy(hw[2:], ip.To4())
  72. }
  73. return hw
  74. }
  75. // GenerateRandomMAC returns a new 6-byte(48-bit) hardware address (MAC)
  76. func GenerateRandomMAC() net.HardwareAddr {
  77. return genMAC(nil)
  78. }
  79. // GenerateMACFromIP returns a locally administered MAC address where the 4 least
  80. // significant bytes are derived from the IPv4 address.
  81. func GenerateMACFromIP(ip net.IP) net.HardwareAddr {
  82. return genMAC(ip)
  83. }
  84. // GenerateRandomName returns a string of the specified length, created by joining the prefix to random hex characters.
  85. // The length must be strictly larger than len(prefix), or an error will be returned.
  86. func GenerateRandomName(prefix string, length int) (string, error) {
  87. if length <= len(prefix) {
  88. return "", fmt.Errorf("invalid length %d for prefix %s", length, prefix)
  89. }
  90. // We add 1 here as integer division will round down, and we want to round up.
  91. b := make([]byte, (length-len(prefix)+1)/2)
  92. if _, err := io.ReadFull(rand.Reader, b); err != nil {
  93. return "", err
  94. }
  95. // By taking a slice here, we ensure that the string is always the correct length.
  96. return (prefix + hex.EncodeToString(b))[:length], nil
  97. }
  98. // ReverseIP accepts a V4 or V6 IP string in the canonical form and returns a reversed IP in
  99. // the dotted decimal form . This is used to setup the IP to service name mapping in the optimal
  100. // way for the DNS PTR queries.
  101. func ReverseIP(IP string) string {
  102. var reverseIP []string
  103. if net.ParseIP(IP).To4() != nil {
  104. reverseIP = strings.Split(IP, ".")
  105. l := len(reverseIP)
  106. for i, j := 0, l-1; i < l/2; i, j = i+1, j-1 {
  107. reverseIP[i], reverseIP[j] = reverseIP[j], reverseIP[i]
  108. }
  109. } else {
  110. reverseIP = strings.Split(IP, ":")
  111. // Reversed IPv6 is represented in dotted decimal instead of the typical
  112. // colon hex notation
  113. for key := range reverseIP {
  114. if len(reverseIP[key]) == 0 { // expand the compressed 0s
  115. reverseIP[key] = strings.Repeat("0000", 8-strings.Count(IP, ":"))
  116. } else if len(reverseIP[key]) < 4 { // 0-padding needed
  117. reverseIP[key] = strings.Repeat("0", 4-len(reverseIP[key])) + reverseIP[key]
  118. }
  119. }
  120. reverseIP = strings.Split(strings.Join(reverseIP, ""), "")
  121. l := len(reverseIP)
  122. for i, j := 0, l-1; i < l/2; i, j = i+1, j-1 {
  123. reverseIP[i], reverseIP[j] = reverseIP[j], reverseIP[i]
  124. }
  125. }
  126. return strings.Join(reverseIP, ".")
  127. }
  128. var (
  129. v6ListenableCached bool
  130. v6ListenableOnce sync.Once
  131. )
  132. // IsV6Listenable returns true when `[::1]:0` is listenable.
  133. // IsV6Listenable returns false mostly when the kernel was booted with `ipv6.disable=1` option.
  134. func IsV6Listenable() bool {
  135. v6ListenableOnce.Do(func() {
  136. ln, err := net.Listen("tcp6", "[::1]:0")
  137. if err != nil {
  138. // When the kernel was booted with `ipv6.disable=1`,
  139. // we get err "listen tcp6 [::1]:0: socket: address family not supported by protocol"
  140. // https://github.com/moby/moby/issues/42288
  141. log.G(context.TODO()).Debugf("v6Listenable=false (%v)", err)
  142. } else {
  143. v6ListenableCached = true
  144. ln.Close()
  145. }
  146. })
  147. return v6ListenableCached
  148. }