utils.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. // Network utility functions.
  2. package netutils
  3. import (
  4. "bytes"
  5. "crypto/rand"
  6. "encoding/hex"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "net"
  11. "strings"
  12. "github.com/vishvananda/netlink"
  13. )
  14. var (
  15. // ErrNetworkOverlapsWithNameservers preformatted error
  16. ErrNetworkOverlapsWithNameservers = errors.New("requested network overlaps with nameserver")
  17. // ErrNetworkOverlaps preformatted error
  18. ErrNetworkOverlaps = errors.New("requested network overlaps with existing network")
  19. // ErrNoDefaultRoute preformatted error
  20. ErrNoDefaultRoute = errors.New("no default route")
  21. networkGetRoutesFct = netlink.RouteList
  22. )
  23. // ErrInvalidProtocolBinding is returned when the port binding protocol is not valid.
  24. type ErrInvalidProtocolBinding string
  25. func (ipb ErrInvalidProtocolBinding) Error() string {
  26. return fmt.Sprintf("invalid transport protocol: %s", string(ipb))
  27. }
  28. // TransportPort represent a local Layer 4 endpoint
  29. type TransportPort struct {
  30. Proto Protocol
  31. Port uint16
  32. }
  33. // PortBinding represent a port binding between the container an the host
  34. type PortBinding struct {
  35. Proto Protocol
  36. IP net.IP
  37. Port uint16
  38. HostIP net.IP
  39. HostPort uint16
  40. }
  41. // HostAddr returns the host side tranport address
  42. func (p PortBinding) HostAddr() (net.Addr, error) {
  43. switch p.Proto {
  44. case UDP:
  45. return &net.UDPAddr{IP: p.HostIP, Port: int(p.HostPort)}, nil
  46. case TCP:
  47. return &net.TCPAddr{IP: p.HostIP, Port: int(p.HostPort)}, nil
  48. default:
  49. return nil, ErrInvalidProtocolBinding(p.Proto.String())
  50. }
  51. }
  52. // ContainerAddr returns the container side tranport address
  53. func (p PortBinding) ContainerAddr() (net.Addr, error) {
  54. switch p.Proto {
  55. case UDP:
  56. return &net.UDPAddr{IP: p.IP, Port: int(p.Port)}, nil
  57. case TCP:
  58. return &net.TCPAddr{IP: p.IP, Port: int(p.Port)}, nil
  59. default:
  60. return nil, ErrInvalidProtocolBinding(p.Proto.String())
  61. }
  62. }
  63. // GetCopy returns a copy of this PortBinding structure instance
  64. func (p *PortBinding) GetCopy() PortBinding {
  65. return PortBinding{
  66. Proto: p.Proto,
  67. IP: GetIPCopy(p.IP),
  68. Port: p.Port,
  69. HostIP: GetIPCopy(p.HostIP),
  70. HostPort: p.HostPort,
  71. }
  72. }
  73. // Equal checks if this instance of PortBinding is equal to the passed one
  74. func (p *PortBinding) Equal(o *PortBinding) bool {
  75. if p == o {
  76. return true
  77. }
  78. if o == nil {
  79. return false
  80. }
  81. if p.Proto != o.Proto || p.Port != o.Port || p.HostPort != o.HostPort {
  82. return false
  83. }
  84. if p.IP != nil {
  85. if !p.IP.Equal(o.IP) {
  86. return false
  87. }
  88. } else {
  89. if o.IP != nil {
  90. return false
  91. }
  92. }
  93. if p.HostIP != nil {
  94. if !p.HostIP.Equal(o.HostIP) {
  95. return false
  96. }
  97. } else {
  98. if o.HostIP != nil {
  99. return false
  100. }
  101. }
  102. return true
  103. }
  104. const (
  105. // ICMP is for the ICMP ip protocol
  106. ICMP = 1
  107. // TCP is for the TCP ip protocol
  108. TCP = 6
  109. // UDP is for the UDP ip protocol
  110. UDP = 17
  111. )
  112. // Protocol represents a IP protocol number
  113. type Protocol uint8
  114. func (p Protocol) String() string {
  115. switch p {
  116. case 1:
  117. return "icmp"
  118. case 6:
  119. return "tcp"
  120. case 17:
  121. return "udp"
  122. default:
  123. return fmt.Sprintf("%d", p)
  124. }
  125. }
  126. // ParseProtocol returns the respective Protocol type for the passed string
  127. func ParseProtocol(s string) Protocol {
  128. switch strings.ToLower(s) {
  129. case "icmp":
  130. return 1
  131. case "udp":
  132. return 17
  133. case "tcp":
  134. return 6
  135. default:
  136. return 0
  137. }
  138. }
  139. // CheckNameserverOverlaps checks whether the passed network overlaps with any of the nameservers
  140. func CheckNameserverOverlaps(nameservers []string, toCheck *net.IPNet) error {
  141. if len(nameservers) > 0 {
  142. for _, ns := range nameservers {
  143. _, nsNetwork, err := net.ParseCIDR(ns)
  144. if err != nil {
  145. return err
  146. }
  147. if NetworkOverlaps(toCheck, nsNetwork) {
  148. return ErrNetworkOverlapsWithNameservers
  149. }
  150. }
  151. }
  152. return nil
  153. }
  154. // CheckRouteOverlaps checks whether the passed network overlaps with any existing routes
  155. func CheckRouteOverlaps(toCheck *net.IPNet) error {
  156. networks, err := networkGetRoutesFct(nil, netlink.FAMILY_V4)
  157. if err != nil {
  158. return err
  159. }
  160. for _, network := range networks {
  161. if network.Dst != nil && NetworkOverlaps(toCheck, network.Dst) {
  162. return ErrNetworkOverlaps
  163. }
  164. }
  165. return nil
  166. }
  167. // NetworkOverlaps detects overlap between one IPNet and another
  168. func NetworkOverlaps(netX *net.IPNet, netY *net.IPNet) bool {
  169. if len(netX.IP) == len(netY.IP) {
  170. if firstIP, _ := NetworkRange(netX); netY.Contains(firstIP) {
  171. return true
  172. }
  173. if firstIP, _ := NetworkRange(netY); netX.Contains(firstIP) {
  174. return true
  175. }
  176. }
  177. return false
  178. }
  179. // NetworkRange calculates the first and last IP addresses in an IPNet
  180. func NetworkRange(network *net.IPNet) (net.IP, net.IP) {
  181. var netIP net.IP
  182. if network.IP.To4() != nil {
  183. netIP = network.IP.To4()
  184. } else if network.IP.To16() != nil {
  185. netIP = network.IP.To16()
  186. } else {
  187. return nil, nil
  188. }
  189. lastIP := make([]byte, len(netIP), len(netIP))
  190. for i := 0; i < len(netIP); i++ {
  191. lastIP[i] = netIP[i] | ^network.Mask[i]
  192. }
  193. return netIP.Mask(network.Mask), net.IP(lastIP)
  194. }
  195. // GetIfaceAddr returns the first IPv4 address and slice of IPv6 addresses for the specified network interface
  196. func GetIfaceAddr(name string) (net.Addr, []net.Addr, error) {
  197. iface, err := net.InterfaceByName(name)
  198. if err != nil {
  199. return nil, nil, err
  200. }
  201. addrs, err := iface.Addrs()
  202. if err != nil {
  203. return nil, nil, err
  204. }
  205. var addrs4 []net.Addr
  206. var addrs6 []net.Addr
  207. for _, addr := range addrs {
  208. ip := (addr.(*net.IPNet)).IP
  209. if ip4 := ip.To4(); ip4 != nil {
  210. addrs4 = append(addrs4, addr)
  211. } else if ip6 := ip.To16(); len(ip6) == net.IPv6len {
  212. addrs6 = append(addrs6, addr)
  213. }
  214. }
  215. switch {
  216. case len(addrs4) == 0:
  217. return nil, nil, fmt.Errorf("Interface %v has no IPv4 addresses", name)
  218. case len(addrs4) > 1:
  219. fmt.Printf("Interface %v has more than 1 IPv4 address. Defaulting to using %v\n",
  220. name, (addrs4[0].(*net.IPNet)).IP)
  221. }
  222. return addrs4[0], addrs6, nil
  223. }
  224. // GenerateRandomMAC returns a new 6-byte(48-bit) hardware address (MAC)
  225. func GenerateRandomMAC() net.HardwareAddr {
  226. hw := make(net.HardwareAddr, 6)
  227. // The first byte of the MAC address has to comply with these rules:
  228. // 1. Unicast: Set the least-significant bit to 0.
  229. // 2. Address is locally administered: Set the second-least-significant bit (U/L) to 1.
  230. // 3. As "small" as possible: The veth address has to be "smaller" than the bridge address.
  231. hw[0] = 0x02
  232. // The first 24 bits of the MAC represent the Organizationally Unique Identifier (OUI).
  233. // Since this address is locally administered, we can do whatever we want as long as
  234. // it doesn't conflict with other addresses.
  235. hw[1] = 0x42
  236. // Randomly generate the remaining 4 bytes (2^32)
  237. _, err := rand.Read(hw[2:])
  238. if err != nil {
  239. return nil
  240. }
  241. return hw
  242. }
  243. // GenerateRandomName returns a new name joined with a prefix. This size
  244. // specified is used to truncate the randomly generated value
  245. func GenerateRandomName(prefix string, size int) (string, error) {
  246. id := make([]byte, 32)
  247. if _, err := io.ReadFull(rand.Reader, id); err != nil {
  248. return "", err
  249. }
  250. return prefix + hex.EncodeToString(id)[:size], nil
  251. }
  252. // GetIPCopy returns a copy of the passed IP address
  253. func GetIPCopy(from net.IP) net.IP {
  254. to := make(net.IP, len(from))
  255. copy(to, from)
  256. return to
  257. }
  258. // GetIPNetCopy returns a copy of the passed IP Network
  259. func GetIPNetCopy(from *net.IPNet) *net.IPNet {
  260. if from == nil {
  261. return nil
  262. }
  263. bm := make(net.IPMask, len(from.Mask))
  264. copy(bm, from.Mask)
  265. return &net.IPNet{IP: GetIPCopy(from.IP), Mask: bm}
  266. }
  267. // CompareIPNet returns equal if the two IP Networks are equal
  268. func CompareIPNet(a, b *net.IPNet) bool {
  269. if a == b {
  270. return true
  271. }
  272. if a == nil || b == nil {
  273. return false
  274. }
  275. return a.IP.Equal(b.IP) && bytes.Equal(a.Mask, b.Mask)
  276. }