utils.go 4.4 KB

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