utils.go 5.6 KB

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