github.com/aporeto-inc/trireme-lib@v10.358.0+incompatible/controller/internal/enforcer/acls/utils.go (about)

     1  package acls
     2  
     3  import (
     4  	"fmt"
     5  	"net"
     6  	"strconv"
     7  	"strings"
     8  )
     9  
    10  // Address is a parsed IP address or CIDR
    11  type Address struct {
    12  	IP      net.IP
    13  	Mask    int
    14  	NoMatch bool
    15  }
    16  
    17  // ParseAddress parses `address` as an IP or CIDR address - based on the notation that we allow in our backend.
    18  // If the address is prefixed with a "!"", then the NoMatch attribute will be true.
    19  // If the Address is of the format "IP/BitMask" (e.g. 192.0.2.0/24), then the mask will be set to 24.
    20  // If the address is of the form "IP" (e.g. 192.0.2.1), then the mask will be added automatically.
    21  func ParseAddress(address string) (*Address, error) {
    22  	var mask int
    23  	var err error
    24  	parts := strings.Split(address, "/")
    25  	nomatch := strings.HasPrefix(parts[0], "!")
    26  	if nomatch {
    27  		parts[0] = parts[0][1:]
    28  	}
    29  	ip := net.ParseIP(parts[0])
    30  	if ip == nil {
    31  		return nil, fmt.Errorf("invalid ip address: %s", parts[0])
    32  	}
    33  
    34  	if len(parts) == 1 {
    35  		if ip.To4() != nil {
    36  			mask = 32
    37  		} else {
    38  			mask = 128
    39  		}
    40  	} else {
    41  		mask, err = strconv.Atoi(parts[1])
    42  		if err != nil {
    43  			return nil, fmt.Errorf("invalid mask '%s': %w", parts[1], err)
    44  		}
    45  	}
    46  
    47  	return &Address{IP: ip, Mask: mask, NoMatch: nomatch}, nil
    48  }