utils.go 5.5 KB

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