utils.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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. // GetIfaceAddr returns the first IPv4 address and slice of IPv6 addresses for the specified network interface
  55. func GetIfaceAddr(name string) (net.Addr, []net.Addr, error) {
  56. iface, err := net.InterfaceByName(name)
  57. if err != nil {
  58. return nil, nil, err
  59. }
  60. addrs, err := iface.Addrs()
  61. if err != nil {
  62. return nil, nil, err
  63. }
  64. var addrs4, addrs6 []net.Addr
  65. for _, addr := range addrs {
  66. ip := (addr.(*net.IPNet)).IP
  67. if ip4 := ip.To4(); ip4 != nil {
  68. addrs4 = append(addrs4, addr)
  69. } else if ip6 := ip.To16(); len(ip6) == net.IPv6len {
  70. addrs6 = append(addrs6, addr)
  71. }
  72. }
  73. switch {
  74. case len(addrs4) == 0:
  75. return nil, nil, fmt.Errorf("interface %v has no IPv4 addresses", name)
  76. case len(addrs4) > 1:
  77. fmt.Printf("Interface %v has more than 1 IPv4 address. Defaulting to using %v\n",
  78. name, (addrs4[0].(*net.IPNet)).IP)
  79. }
  80. return addrs4[0], addrs6, nil
  81. }
  82. func genMAC(ip net.IP) net.HardwareAddr {
  83. hw := make(net.HardwareAddr, 6)
  84. // The first byte of the MAC address has to comply with these rules:
  85. // 1. Unicast: Set the least-significant bit to 0.
  86. // 2. Address is locally administered: Set the second-least-significant bit (U/L) to 1.
  87. hw[0] = 0x02
  88. // The first 24 bits of the MAC represent the Organizationally Unique Identifier (OUI).
  89. // Since this address is locally administered, we can do whatever we want as long as
  90. // it doesn't conflict with other addresses.
  91. hw[1] = 0x42
  92. // Fill the remaining 4 bytes based on the input
  93. if ip == nil {
  94. rand.Read(hw[2:])
  95. } else {
  96. copy(hw[2:], ip.To4())
  97. }
  98. return hw
  99. }
  100. // GenerateRandomMAC returns a new 6-byte(48-bit) hardware address (MAC)
  101. func GenerateRandomMAC() net.HardwareAddr {
  102. return genMAC(nil)
  103. }
  104. // GenerateMACFromIP returns a locally administered MAC address where the 4 least
  105. // significant bytes are derived from the IPv4 address.
  106. func GenerateMACFromIP(ip net.IP) net.HardwareAddr {
  107. return genMAC(ip)
  108. }
  109. // GenerateRandomName returns a string of the specified length, created by joining the prefix to random hex characters.
  110. // The length must be strictly larger than len(prefix), or an error will be returned.
  111. func GenerateRandomName(prefix string, length int) (string, error) {
  112. if length <= len(prefix) {
  113. return "", fmt.Errorf("invalid length %d for prefix %s", length, prefix)
  114. }
  115. // We add 1 here as integer division will round down, and we want to round up.
  116. b := make([]byte, (length-len(prefix)+1)/2)
  117. if _, err := io.ReadFull(rand.Reader, b); err != nil {
  118. return "", err
  119. }
  120. // By taking a slice here, we ensure that the string is always the correct length.
  121. return (prefix + hex.EncodeToString(b))[:length], nil
  122. }
  123. // ReverseIP accepts a V4 or V6 IP string in the canonical form and returns a reversed IP in
  124. // the dotted decimal form . This is used to setup the IP to service name mapping in the optimal
  125. // way for the DNS PTR queries.
  126. func ReverseIP(IP string) string {
  127. var reverseIP []string
  128. if net.ParseIP(IP).To4() != nil {
  129. reverseIP = strings.Split(IP, ".")
  130. l := len(reverseIP)
  131. for i, j := 0, l-1; i < l/2; i, j = i+1, j-1 {
  132. reverseIP[i], reverseIP[j] = reverseIP[j], reverseIP[i]
  133. }
  134. } else {
  135. reverseIP = strings.Split(IP, ":")
  136. // Reversed IPv6 is represented in dotted decimal instead of the typical
  137. // colon hex notation
  138. for key := range reverseIP {
  139. if len(reverseIP[key]) == 0 { // expand the compressed 0s
  140. reverseIP[key] = strings.Repeat("0000", 8-strings.Count(IP, ":"))
  141. } else if len(reverseIP[key]) < 4 { // 0-padding needed
  142. reverseIP[key] = strings.Repeat("0", 4-len(reverseIP[key])) + reverseIP[key]
  143. }
  144. }
  145. reverseIP = strings.Split(strings.Join(reverseIP, ""), "")
  146. l := len(reverseIP)
  147. for i, j := 0, l-1; i < l/2; i, j = i+1, j-1 {
  148. reverseIP[i], reverseIP[j] = reverseIP[j], reverseIP[i]
  149. }
  150. }
  151. return strings.Join(reverseIP, ".")
  152. }
  153. // ParseAlias parses and validates the specified string as an alias format (name:alias)
  154. func ParseAlias(val string) (string, string, error) {
  155. if val == "" {
  156. return "", "", errors.New("empty string specified for alias")
  157. }
  158. arr := strings.SplitN(val, ":", 3)
  159. if len(arr) > 2 {
  160. return "", "", errors.New("bad format for alias: " + val)
  161. }
  162. if len(arr) == 1 {
  163. return val, val, nil
  164. }
  165. return arr[0], arr[1], nil
  166. }
  167. // ValidateAlias validates that the specified string has a valid alias format (containerName:alias).
  168. func ValidateAlias(val string) (string, error) {
  169. if _, _, err := ParseAlias(val); err != nil {
  170. return val, err
  171. }
  172. return val, nil
  173. }