// ensureSecRules ensures that the list passed has all the rules
// that it needs, if one is missing it will create it inside the oracle
// cloud environment and it will return nil
// if none rule is missing then it will return nil
962049
func (f Firewall) ensureSecRules(seclist response.SecList, rules []network.IngressRule) error {
	// get all security rules associated with the seclist
	secRules, err := f.getSecRules(seclist.Name)
	if err != nil {
		return errors.Trace(err)
	}
	logger.Tracef("list %v has sec rules: %v", seclist.Name, secRules)

	converted, err := f.convertFromSecRules(secRules...)
	if err != nil {
		return errors.Trace(err)
	}
	logger.Tracef("converted rules are: %v", converted)
	asIngressRules := converted[seclist.Name]
	missing := []network.IngressRule{}

	// search through all rules and find the missing ones
	for _, toAdd := range rules {
		found := false
		for _, exists := range asIngressRules {
			sort.Strings(toAdd.SourceCIDRs)
			sort.Strings(exists.SourceCIDRs)
			logger.Tracef("comparing %v to %v", toAdd.SourceCIDRs, exists.SourceCIDRs)
			if reflect.DeepEqual(toAdd, exists) {
				found = true
				break
			}
		}
		if found {
			continue
		}
		missing = append(missing, toAdd)
	}
	if len(missing) == 0 {
		return nil
	}
	logger.Tracef("Found missing rules: %v", missing)
	// convert the missing rules back to sec rules
	asSecRule, err := f.convertToSecRules(seclist, missing)
	if err != nil {
		return errors.Trace(err)
	}

	for _, val := range asSecRule {
		_, err = f.client.CreateSecRule(val)
		if err != nil {
			return errors.Trace(err)
		}
	}
	return nil
}
389332
func (s *CreateAppInput) SetCustomRules(v []*CustomRule) *CreateAppInput {
	s.CustomRules = v
	return s
}
250860
func (i *Instance) processRulesFromList(rulelist [][]string, methodType string) error {
	var err error
	for _, cr := range rulelist {
		// HACK: Adding a retry loop to avoid iptables error of "invalid argument"
		// Once in a while iptables
	L:
		for retry := 0; retry < 3; retry++ {
			switch methodType {
			case "Append":
				if err = i.ipt.Append(cr[0], cr[1], cr[2:]...); err == nil {
					break L
				}
			case "Insert":
				order, err := strconv.Atoi(cr[2])
				if err != nil {
					zap.L().Error("Incorrect format for iptables insert")
					return errors.New("invalid format")
				}
				if err = i.ipt.Insert(cr[0], cr[1], order, cr[3:]...); err == nil {
					break L
				}

			case "Delete":
				if err = i.ipt.Delete(cr[0], cr[1], cr[2:]...); err == nil {
					break L
				}

			default:
				return errors.New("invalid method type")
			}
		}
		if err != nil && methodType != "Delete" {
			return fmt.Errorf("unable to %s rule for table %s and chain %s with error %s", methodType, cr[0], cr[1], err)
		}
	}

	return nil
}
708300
func prepareRules(c context.Context, cfg policy.ConfigBundle, revision string) (policy.Queryable, error) {
	parsed, ok := cfg[delegationCfg].(*admin.DelegationPermissions)
	if !ok {
		return nil, fmt.Errorf("wrong type of delegation.cfg - %T", cfg[delegationCfg])
	}

	rules := make([]*delegationRule, 0, len(parsed.Rules)+1)
	for _, msg := range parsed.Rules {
		rule, err := makeDelegationRule(c, msg)
		if err != nil {
			return nil, err
		}
		rules = append(rules, rule)
	}

	// Add an implicit rule that allows trusted LUCI microservices to grab
	// delegation tokens for 'project:*' identities. "auth-luci-services" is a
	// magical group also mentioned in luci-py's components.auth.
	//
	// TODO(vadimsh): Currently relied on by Buildbucket. Buildbucket should
	// switch to using 'project:...' identities directly without going through
	// the token server.
	rule, err := makeDelegationRule(c, &admin.DelegationRule{
		Name:                 "allow-project-identities",
		Requestor:            []string{"group:auth-luci-services"},
		AllowedToImpersonate: []string{Projects},
		AllowedAudience:      []string{Requestor},
		TargetService:        []string{"*"},
		MaxValidityDuration:  86400,
	})
	if err != nil {
		panic(err) // should be impossible, this is a hardcoded rule
	}
	rules = append(rules, rule)

	requestors := make([]*identityset.Set, len(rules))
	for i, r := range rules {
		requestors[i] = r.requestors
	}

	return &Rules{
		revision:   revision,
		rules:      rules,
		requestors: identityset.Union(requestors...),
	}, nil
}
1057012
func (s *ListRulesOutput) SetRules(v []*RuleSummary) *ListRulesOutput {
	s.Rules = v
	return s
}
963526
func (c *Compiler) GetRules() (*Rules, error) {
	if c.cptr.errors != 0 {
		return nil, errors.New("Compiler cannot be used after parse error")
	}
	var yrRules *C.YR_RULES
	if err := newError(C.yr_compiler_get_rules(c.cptr, &yrRules)); err != nil {
		return nil, err
	}
	r := &Rules{rules: &rules{cptr: yrRules}}
	runtime.SetFinalizer(r.rules, (*rules).finalize)
	keepAlive(c)
	return r, nil
}
753899
func (m *IptablesManager) RemoveRules() {
	// Set of tables that have had iptables rules in any Cilium version
	tables := []string{"nat", "mangle", "raw", "filter"}
	for _, t := range tables {
		removeCiliumRules(t, "iptables")
	}

	// Set of tables that have had ip6tables rules in any Cilium version
	if m.ip6tables {
		tables6 := []string{"mangle", "raw"}
		for _, t := range tables6 {
			removeCiliumRules(t, "ip6tables")
		}
	}

	for _, c := range ciliumChains {
		c.remove()
	}
}
437620
func (r *Rules) GetRules() (rv []Rule) {
	for p := unsafe.Pointer(r.cptr.rules_list_head); (*C.YR_RULE)(p).g_flags&C.RULE_GFLAGS_NULL == 0; p = unsafe.Pointer(uintptr(p) + unsafe.Sizeof(*r.cptr.rules_list_head)) {
		rv = append(rv, Rule{(*C.YR_RULE)(p)})
	}
	return
}
307579
func (tqsc *Controller) GetQueryRules(ruleSource string) *rules.Rules {
	tqsc.mu.Lock()
	defer tqsc.mu.Unlock()
	return tqsc.queryRulesMap[ruleSource]
}
1007353
func (s *ModifyRuleOutput) SetRules(v []*Rule) *ModifyRuleOutput {
	s.Rules = v
	return s
}
318962
func (c *Compiler) checkSafetyRuleBodies() {
	for _, name := range c.sorted {
		m := c.Modules[name]
		WalkRules(m, func(r *Rule) bool {
			safe := ReservedVars.Copy()
			safe.Update(r.Head.Args.Vars())
			r.Body = c.checkBodySafety(safe, m, r.Body, r.Loc())
			return false
		})
	}
}
283124
func (c *Compiler) checkSafetyRuleHeads() {

	for _, name := range c.sorted {
		m := c.Modules[name]
		WalkRules(m, func(r *Rule) bool {
			safe := r.Body.Vars(safetyCheckVarVisitorParams)
			safe.Update(r.Head.Args.Vars())
			unsafe := r.Head.Vars().Diff(safe)
			for v := range unsafe {
				if !v.IsGenerated() {
					c.err(NewError(UnsafeVarErr, r.Loc(), "var %v is unsafe", v))
				}
			}
			return false
		})
	}
}
1336386
func (i *Instance) trapRules(cfg *ACLInfo, isHostPU bool) [][]string {

	tmpl := template.Must(template.New(packetCaptureTemplate).Funcs(template.FuncMap{
		"needDnsRules": func() bool {
			return i.mode == constants.Sidecar || isHostPU || i.isLegacyKernel
		},
		"isUIDProcess": func() bool {
			return cfg.UID != ""
		},
	}).Parse(packetCaptureTemplate))

	rules, err := extractRulesFromTemplate(tmpl, cfg)
	if err != nil {
		zap.L().Warn("unable to extract rules", zap.Error(err))
	}

	return rules
}
812924
func (plugin *kubenetNetworkPlugin) ensureMasqRule() error {
	if plugin.nonMasqueradeCIDR != "0.0.0.0/0" {
		if _, err := plugin.iptables.EnsureRule(utiliptables.Append, utiliptables.TableNAT, utiliptables.ChainPostrouting,
			"-m", "comment", "--comment", "kubenet: SNAT for outbound traffic from cluster",
			"-m", "addrtype", "!", "--dst-type", "LOCAL",
			"!", "-d", plugin.nonMasqueradeCIDR,
			"-j", "MASQUERADE"); err != nil {
			return fmt.Errorf("Failed to ensure that %s chain %s jumps to MASQUERADE: %v", utiliptables.TableNAT, utiliptables.ChainPostrouting, err)
		}
	}
	return nil
}
270753
func checkIfRuleExists(listChainOutput string, args ...string) bool {
	rule := strings.Join(args, " ")
	for _, line := range strings.Split(listChainOutput, "\n") {
		if strings.TrimSpace(line) == rule {
			return true
		}
	}
	return false
}
703905
func (s *BucketLifecycleConfiguration) SetRules(v []*LifecycleRule) *BucketLifecycleConfiguration {
	s.Rules = v
	return s
}
151900
func (s *WebACL) SetRules(v []*ActivatedRule) *WebACL {
	s.Rules = v
	return s
}