github.com/cilium/cilium@v1.16.2/pkg/fqdn/helpers.go (about) 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright Authors of Cilium 3 4 package fqdn 5 6 import ( 7 "net/netip" 8 "regexp" 9 10 "github.com/sirupsen/logrus" 11 12 "github.com/cilium/cilium/pkg/fqdn/dns" 13 "github.com/cilium/cilium/pkg/fqdn/matchpattern" 14 "github.com/cilium/cilium/pkg/fqdn/re" 15 "github.com/cilium/cilium/pkg/policy/api" 16 ) 17 18 // mapSelectorsToNamesLocked iterates through all DNS Names in the cache and 19 // evaluates if they match the provided fqdnSelector. If so, the matching DNS 20 // Name with all its associated IPs is collected. 21 // 22 // Returns the mapping of DNS names to all IPs selected by that selector. 23 func (n *NameManager) mapSelectorsToNamesLocked(fqdnSelector api.FQDNSelector) (namesIPMapping map[string][]netip.Addr) { 24 namesIPMapping = make(map[string][]netip.Addr) 25 26 // lookup matching DNS names 27 if len(fqdnSelector.MatchName) > 0 { 28 dnsName := prepareMatchName(fqdnSelector.MatchName) 29 lookupIPs := n.cache.Lookup(dnsName) 30 if len(lookupIPs) > 0 { 31 log.WithFields(logrus.Fields{ 32 "DNSName": dnsName, 33 "IPs": lookupIPs, 34 "matchName": fqdnSelector.MatchName, 35 }).Debug("Emitting matching DNS Name -> IPs for FQDNSelector") 36 namesIPMapping[dnsName] = lookupIPs 37 } 38 } 39 40 if len(fqdnSelector.MatchPattern) > 0 { 41 // lookup matching DNS names 42 dnsPattern := matchpattern.Sanitize(fqdnSelector.MatchPattern) 43 patternREStr := matchpattern.ToAnchoredRegexp(dnsPattern) 44 var ( 45 err error 46 patternRE *regexp.Regexp 47 ) 48 49 if patternRE, err = re.CompileRegex(patternREStr); err != nil { 50 log.WithError(err).Error("Error compiling matchPattern") 51 return namesIPMapping 52 } 53 lookupIPs := n.cache.LookupByRegexp(patternRE) 54 55 for dnsName, ips := range lookupIPs { 56 if len(ips) > 0 { 57 if log.Logger.IsLevelEnabled(logrus.DebugLevel) { 58 log.WithFields(logrus.Fields{ 59 "DNSName": dnsName, 60 "IPs": ips, 61 "matchPattern": fqdnSelector.MatchPattern, 62 }).Debug("Emitting matching DNS Name -> IPs for FQDNSelector") 63 } 64 namesIPMapping[dnsName] = append(namesIPMapping[dnsName], ips...) 65 } 66 } 67 } 68 69 return namesIPMapping 70 } 71 72 // prepareMatchName ensures a ToFQDNs.matchName field is used consistently. 73 func prepareMatchName(matchName string) string { 74 return dns.FQDN(matchName) 75 }