github.com/Heebron/moby@v0.0.0-20221111184709-6eab4f55faf7/libnetwork/netutils/utils.go (about)

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