utils.go 4.6 KB

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