utils.go 7.8 KB

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