utils.go 5.7 KB

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