github.com/zhyoulun/cilium@v1.6.12/pkg/policy/cidr.go (about)

     1  // Copyright 2018 Authors of Cilium
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package policy
    16  
    17  import (
    18  	"net"
    19  
    20  	"github.com/cilium/cilium/pkg/ip"
    21  	"github.com/cilium/cilium/pkg/policy/api"
    22  )
    23  
    24  // getPrefixesFromCIDR fetches all CIDRs referred to by the specified slice
    25  // and returns them as regular golang CIDR objects.
    26  func getPrefixesFromCIDR(cidrs api.CIDRSlice) []*net.IPNet {
    27  	result, _ := ip.ParseCIDRs(cidrs.StringSlice())
    28  	return result
    29  }
    30  
    31  // GetPrefixesFromCIDRSet fetches all CIDRs referred to by the specified slice
    32  // and returns them as regular golang CIDR objects.
    33  //
    34  // Assumes that validation already occurred on 'rules'.
    35  func GetPrefixesFromCIDRSet(rules api.CIDRRuleSlice) []*net.IPNet {
    36  	cidrs := api.ComputeResultantCIDRSet(rules)
    37  	return getPrefixesFromCIDR(cidrs)
    38  }
    39  
    40  // GetCIDRPrefixes runs through the specified 'rules' to find every reference
    41  // to a CIDR in the rules, and returns a slice containing all of these CIDRs.
    42  // Multiple rules referring to the same CIDR will result in multiple copies of
    43  // the CIDR in the returned slice.
    44  //
    45  // Assumes that validation already occurred on 'rules'.
    46  func GetCIDRPrefixes(rules api.Rules) []*net.IPNet {
    47  	if len(rules) == 0 {
    48  		return nil
    49  	}
    50  	res := make([]*net.IPNet, 0, 32)
    51  	for _, r := range rules {
    52  		for _, ir := range r.Ingress {
    53  			if len(ir.FromCIDR) > 0 {
    54  				res = append(res, getPrefixesFromCIDR(ir.FromCIDR)...)
    55  			}
    56  			if len(ir.FromCIDRSet) > 0 {
    57  				res = append(res, GetPrefixesFromCIDRSet(ir.FromCIDRSet)...)
    58  			}
    59  		}
    60  		for _, er := range r.Egress {
    61  			if len(er.ToCIDR) > 0 {
    62  				res = append(res, getPrefixesFromCIDR(er.ToCIDR)...)
    63  			}
    64  			if len(er.ToCIDRSet) > 0 {
    65  				res = append(res, GetPrefixesFromCIDRSet(er.ToCIDRSet)...)
    66  			}
    67  		}
    68  	}
    69  	return res
    70  }