// This function creates multiple policies with rules for the given listener.
17884
func (r Network_LBaaS_L7Policy) AddL7Policies(listenerUuid *string, policiesRules []datatypes.Network_LBaaS_PolicyRule) (resp datatypes.Network_LBaaS_LoadBalancer, err error) {
	params := []interface{}{
		listenerUuid,
		policiesRules,
	}
	err = r.Session.DoRequest("SoftLayer_Network_LBaaS_L7Policy", "addL7Policies", params, &r.Options, &resp)
	return
}
1121317
func ListenAll() ([]net.Listener, error) {
	targets, err := parseListenTargets(GetPortsSpecification())
	if err != nil {
		return nil, err
	}

	ret := make([]net.Listener, len(targets))
	for i, target := range targets {
		ret[i], err = target.Listen()
		if err != nil {
			// Close everything up to this listener
			for x := 0; x < i; x++ {
				ret[x].Close()
			}
			return nil, err
		}
	}
	return ret, nil
}
294450
func (client *Client) CreateRules(args *CreateRulesArgs) error {
	response := CreateRulesResponse{}
	err := client.Invoke("CreateRules", args, &response)
	if err != nil {
		return err
	}
	return err
}
168599
func (s *Server) Listeners() ([]Loop, error) {
	loops := []Loop{}
	for _, addr := range s.addrs {
		parsedURL, err := parseURL(addr, s.cert != nil)
		if err != nil {
			return nil, err
		}
		var loop Loop
		var listener httpListener
		switch parsedURL.Scheme {
		case "unix":
			loop, listener, err = s.getListenerForUNIXSocket(parsedURL)
		case "http":
			loop, listener, err = s.getListenerForHTTPServer(parsedURL)
		case "https":
			loop, listener, err = s.getListenerForHTTPSServer(parsedURL)
		default:
			err = fmt.Errorf("invalid url scheme %q", parsedURL.Scheme)
		}
		if err != nil {
			return nil, err
		}
		s.httpListeners = append(s.httpListeners, listener)
		loops = append(loops, loop)
	}

	if s.insecureAddr != "" {
		parsedURL, err := parseURL(s.insecureAddr, false)
		if err != nil {
			return nil, err
		}
		loop, httpListener, err := s.getListenerForHTTPServer(parsedURL)
		if err != nil {
			return nil, err
		}
		s.httpListeners = append(s.httpListeners, httpListener)
		loops = append(loops, loop)
	}

	return loops, nil
}
1102007
func createListener() (eventListener, error) {
	listener := &netlinkListener{}
	err := listener.bind()
	return listener, err
}
164720
func PolicyDeleteRepr(deleted int, labels []string, revision uint64) (string, error) {
	notification := PolicyUpdateNotification{
		Labels:    labels,
		Revision:  revision,
		RuleCount: deleted,
	}
	repr, err := json.Marshal(notification)

	return string(repr), err
}
88290
func (n *Network) Listener(l net.Listener) net.Listener {
	return &listener{Listener: l, network: n}
}
976219
func (e *Enforcer) Enforce(rvals ...interface{}) bool {
	if !e.enabled {
		return true
	}

	functions := make(map[string]govaluate.ExpressionFunction)
	for key, function := range e.fm {
		functions[key] = function
	}
	if _, ok := e.model["g"]; ok {
		for key, ast := range e.model["g"] {
			rm := ast.RM
			functions[key] = util.GenerateGFunction(rm)
		}
	}

	expString := e.model["m"]["m"].Value
	expression, err := govaluate.NewEvaluableExpressionWithFunctions(expString, functions)
	if err != nil {
		panic(err)
	}

	var policyEffects []effect.Effect
	var matcherResults []float64
	if policyLen := len(e.model["p"]["p"].Policy); policyLen != 0 {
		policyEffects = make([]effect.Effect, policyLen)
		matcherResults = make([]float64, policyLen)
		if len(e.model["r"]["r"].Tokens) != len(rvals) {
			panic(
				fmt.Sprintf(
					"Invalid Request Definition size: expected %d got %d rvals: %v",
					len(e.model["r"]["r"].Tokens),
					len(rvals),
					rvals))
		}
		for i, pvals := range e.model["p"]["p"].Policy {
			// log.LogPrint("Policy Rule: ", pvals)
			if len(e.model["p"]["p"].Tokens) != len(pvals) {
				panic(
					fmt.Sprintf(
						"Invalid Policy Rule size: expected %d got %d pvals: %v",
						len(e.model["p"]["p"].Tokens),
						len(pvals),
						pvals))
			}
			parameters := make(map[string]interface{}, 8)
			for j, token := range e.model["r"]["r"].Tokens {
				parameters[token] = rvals[j]
			}
			for j, token := range e.model["p"]["p"].Tokens {
				parameters[token] = pvals[j]
			}

			result, err := expression.Evaluate(parameters)
			// log.LogPrint("Result: ", result)

			if err != nil {
				policyEffects[i] = effect.Indeterminate
				panic(err)
			}

			switch result := result.(type) {
			case bool:
				if !result {
					policyEffects[i] = effect.Indeterminate
					continue
				}
			case float64:
				if result == 0 {
					policyEffects[i] = effect.Indeterminate
					continue
				} else {
					matcherResults[i] = result
				}
			default:
				panic(errors.New("matcher result should be bool, int or float"))
			}

			if eft, ok := parameters["p_eft"]; ok {
				if eft == "allow" {
					policyEffects[i] = effect.Allow
				} else if eft == "deny" {
					policyEffects[i] = effect.Deny
				} else {
					policyEffects[i] = effect.Indeterminate
				}
			} else {
				policyEffects[i] = effect.Allow
			}

			if e.model["e"]["e"].Value == "priority(p_eft) || deny" {
				break
			}

		}
	} else {
		policyEffects = make([]effect.Effect, 1)
		matcherResults = make([]float64, 1)

		parameters := make(map[string]interface{}, 8)
		for j, token := range e.model["r"]["r"].Tokens {
			parameters[token] = rvals[j]
		}
		for _, token := range e.model["p"]["p"].Tokens {
			parameters[token] = ""
		}

		result, err := expression.Evaluate(parameters)
		// log.LogPrint("Result: ", result)

		if err != nil {
			policyEffects[0] = effect.Indeterminate
			panic(err)
		}

		if result.(bool) {
			policyEffects[0] = effect.Allow
		} else {
			policyEffects[0] = effect.Indeterminate
		}
	}

	// log.LogPrint("Rule Results: ", policyEffects)

	result, err := e.eft.MergeEffects(e.model["e"]["e"].Value, policyEffects, matcherResults)
	if err != nil {
		panic(err)
	}

	// Log request.
	if log.GetLogger().IsEnabled() {
		reqStr := "Request: "
		for i, rval := range rvals {
			if i != len(rvals)-1 {
				reqStr += fmt.Sprintf("%v, ", rval)
			} else {
				reqStr += fmt.Sprintf("%v", rval)
			}
		}
		reqStr += fmt.Sprintf(" ---> %t", result)
		log.LogPrint(reqStr)
	}

	return result
}
743602
func (s *Swarm) addListener(nl net.Listener) (*Listener, error) {
	if nl == nil {
		return nil, errors.New("nil listener")
	}

	s.listenerLock.Lock()
	defer s.listenerLock.Unlock()

	// first, check if we already have it...
	for l := range s.listeners {
		if l.netList == nl {
			return l, nil
		}
	}

	l := newListener(nl, s)
	s.listeners[l] = struct{}{}
	go l.accept()
	return l, nil
}
813499
func (pl PolicyList) RulesFor(user user.Info, namespace string) ([]authorizer.ResourceRuleInfo, []authorizer.NonResourceRuleInfo, bool, error) {
	var (
		resourceRules    []authorizer.ResourceRuleInfo
		nonResourceRules []authorizer.NonResourceRuleInfo
	)

	for _, p := range pl {
		if subjectMatches(*p, user) {
			if p.Spec.Namespace == "*" || p.Spec.Namespace == namespace {
				if len(p.Spec.Resource) > 0 {
					r := authorizer.DefaultResourceRuleInfo{
						Verbs:     getVerbs(p.Spec.Readonly),
						APIGroups: []string{p.Spec.APIGroup},
						Resources: []string{p.Spec.Resource},
					}
					var resourceRule authorizer.ResourceRuleInfo = &r
					resourceRules = append(resourceRules, resourceRule)
				}
				if len(p.Spec.NonResourcePath) > 0 {
					r := authorizer.DefaultNonResourceRuleInfo{
						Verbs:           getVerbs(p.Spec.Readonly),
						NonResourceURLs: []string{p.Spec.NonResourcePath},
					}
					var nonResourceRule authorizer.NonResourceRuleInfo = &r
					nonResourceRules = append(nonResourceRules, nonResourceRule)
				}
			}
		}
	}
	return resourceRules, nonResourceRules, false, nil
}
597074
func (d *Daemon) PolicyDelete(labels labels.LabelArray) (newRev uint64, err error) {

	p := &PolicyDeleteEvent{
		labels: labels,
		d:      d,
	}
	policyDeleteEvent := eventqueue.NewEvent(p)
	resChan := d.policy.RepositoryChangeQueue.Enqueue(policyDeleteEvent)

	res, ok := <-resChan
	if ok {
		ress := res.(*PolicyDeleteResult)
		return ress.newRev, ress.err
	}
	return 0, fmt.Errorf("policy deletion event cancelled")
}
425641
func NewTLSListener(inner net.Listener, config *tls.Config) net.Listener {
	l := new(TLSListener)
	l.Listener = inner
	l.config = config
	return l
}
1042005
func (abp *attrPolicyBuilder) Globally() *Policy {

	for _, attr := range abp.attrNames {
		if _, ok := abp.p.globalAttrs[attr]; !ok {
			abp.p.globalAttrs[attr] = attrPolicy{}
		}

		ap := attrPolicy{}
		if abp.regexp != nil {
			ap.regexp = abp.regexp
		}

		abp.p.globalAttrs[attr] = ap
	}

	return abp.p
}
1066230
func NewPolicyFromSource(id string, revision uint64, rules string, syntax SyntaxVersion, sentinel sentinel.Evaluator) (*Policy, error) {
	if rules == "" {
		// Hot path for empty source
		return &Policy{ID: id, Revision: revision}, nil
	}

	var policy *Policy
	var err error
	switch syntax {
	case SyntaxLegacy:
		policy, err = parseLegacy(rules, sentinel)
	case SyntaxCurrent:
		policy, err = parseCurrent(rules, sentinel)
	default:
		return nil, fmt.Errorf("Invalid rules version: %d", syntax)
	}

	if err == nil {
		policy.ID = id
		policy.Revision = revision
	}
	return policy, err
}
436494
func (cli *OpsGenieClient) Policy() (*OpsGeniePolicyClient, error) {
	cli.makeHTTPTransportSettings()

	policyClient := new(OpsGeniePolicyClient)
	policyClient.SetOpsGenieClient(*cli)

	if cli.opsGenieAPIURL == "" {
		policyClient.SetOpsGenieAPIUrl(endpointURL)
	}

	return policyClient, nil
}
281945
func (d *DockerDiscovery) Listeners() []ChangeListener {
	var listeners []ChangeListener

	for _, cntnr := range d.services {
		container, err := d.inspectContainer(cntnr)
		if err != nil {
			continue
		}

		listener := d.listenerForContainer(container)
		if listener != nil {
			listeners = append(listeners, *listener)
		}
	}

	return listeners
}
271342
func MergePolicies(policies []*Policy) *Policy {
	// maps are used here so that we can lookup each policy by
	// the segment that the rule applies to during the policy
	// merge. Otherwise we could do a linear search through a slice
	// and replace it inline
	aclPolicy := ""
	agentPolicies := make(map[string]*AgentPolicy)
	agentPrefixPolicies := make(map[string]*AgentPolicy)
	eventPolicies := make(map[string]*EventPolicy)
	eventPrefixPolicies := make(map[string]*EventPolicy)
	keyringPolicy := ""
	keyPolicies := make(map[string]*KeyPolicy)
	keyPrefixPolicies := make(map[string]*KeyPolicy)
	nodePolicies := make(map[string]*NodePolicy)
	nodePrefixPolicies := make(map[string]*NodePolicy)
	operatorPolicy := ""
	preparedQueryPolicies := make(map[string]*PreparedQueryPolicy)
	preparedQueryPrefixPolicies := make(map[string]*PreparedQueryPolicy)
	servicePolicies := make(map[string]*ServicePolicy)
	servicePrefixPolicies := make(map[string]*ServicePolicy)
	sessionPolicies := make(map[string]*SessionPolicy)
	sessionPrefixPolicies := make(map[string]*SessionPolicy)

	// Parse all the individual rule sets
	for _, policy := range policies {
		if takesPrecedenceOver(policy.ACL, aclPolicy) {
			aclPolicy = policy.ACL
		}

		for _, ap := range policy.Agents {
			update := true
			if permission, found := agentPolicies[ap.Node]; found {
				update = takesPrecedenceOver(ap.Policy, permission.Policy)
			}

			if update {

				agentPolicies[ap.Node] = ap
			}
		}

		for _, ap := range policy.AgentPrefixes {
			update := true
			if permission, found := agentPrefixPolicies[ap.Node]; found {
				update = takesPrecedenceOver(ap.Policy, permission.Policy)
			}

			if update {
				agentPrefixPolicies[ap.Node] = ap
			}
		}

		for _, ep := range policy.Events {
			update := true
			if permission, found := eventPolicies[ep.Event]; found {
				update = takesPrecedenceOver(ep.Policy, permission.Policy)
			}

			if update {
				eventPolicies[ep.Event] = ep
			}
		}

		for _, ep := range policy.EventPrefixes {
			update := true
			if permission, found := eventPrefixPolicies[ep.Event]; found {
				update = takesPrecedenceOver(ep.Policy, permission.Policy)
			}

			if update {
				eventPrefixPolicies[ep.Event] = ep
			}
		}

		if takesPrecedenceOver(policy.Keyring, keyringPolicy) {
			keyringPolicy = policy.Keyring
		}

		for _, kp := range policy.Keys {
			update := true
			if permission, found := keyPolicies[kp.Prefix]; found {
				update = takesPrecedenceOver(kp.Policy, permission.Policy)
			}

			if update {
				keyPolicies[kp.Prefix] = kp
			}
		}

		for _, kp := range policy.KeyPrefixes {
			update := true
			if permission, found := keyPrefixPolicies[kp.Prefix]; found {
				update = takesPrecedenceOver(kp.Policy, permission.Policy)
			}

			if update {
				keyPrefixPolicies[kp.Prefix] = kp
			}
		}

		for _, np := range policy.Nodes {
			update := true
			if permission, found := nodePolicies[np.Name]; found {
				update = takesPrecedenceOver(np.Policy, permission.Policy)
			}

			if update {
				nodePolicies[np.Name] = np
			}
		}

		for _, np := range policy.NodePrefixes {
			update := true
			if permission, found := nodePrefixPolicies[np.Name]; found {
				update = takesPrecedenceOver(np.Policy, permission.Policy)
			}

			if update {
				nodePrefixPolicies[np.Name] = np
			}
		}

		if takesPrecedenceOver(policy.Operator, operatorPolicy) {
			operatorPolicy = policy.Operator
		}

		for _, qp := range policy.PreparedQueries {
			update := true
			if permission, found := preparedQueryPolicies[qp.Prefix]; found {
				update = takesPrecedenceOver(qp.Policy, permission.Policy)
			}

			if update {
				preparedQueryPolicies[qp.Prefix] = qp
			}
		}

		for _, qp := range policy.PreparedQueryPrefixes {
			update := true
			if permission, found := preparedQueryPrefixPolicies[qp.Prefix]; found {
				update = takesPrecedenceOver(qp.Policy, permission.Policy)
			}

			if update {
				preparedQueryPrefixPolicies[qp.Prefix] = qp
			}
		}

		for _, sp := range policy.Services {
			existing, found := servicePolicies[sp.Name]

			if !found {
				servicePolicies[sp.Name] = sp
				continue
			}

			if takesPrecedenceOver(sp.Policy, existing.Policy) {
				existing.Policy = sp.Policy
				existing.Sentinel = sp.Sentinel
			}

			if takesPrecedenceOver(sp.Intentions, existing.Intentions) {
				existing.Intentions = sp.Intentions
			}
		}

		for _, sp := range policy.ServicePrefixes {
			existing, found := servicePrefixPolicies[sp.Name]

			if !found {
				servicePrefixPolicies[sp.Name] = sp
				continue
			}

			if takesPrecedenceOver(sp.Policy, existing.Policy) {
				existing.Policy = sp.Policy
				existing.Sentinel = sp.Sentinel
			}

			if takesPrecedenceOver(sp.Intentions, existing.Intentions) {
				existing.Intentions = sp.Intentions
			}
		}

		for _, sp := range policy.Sessions {
			update := true
			if permission, found := sessionPolicies[sp.Node]; found {
				update = takesPrecedenceOver(sp.Policy, permission.Policy)
			}

			if update {
				sessionPolicies[sp.Node] = sp
			}
		}

		for _, sp := range policy.SessionPrefixes {
			update := true
			if permission, found := sessionPrefixPolicies[sp.Node]; found {
				update = takesPrecedenceOver(sp.Policy, permission.Policy)
			}

			if update {
				sessionPrefixPolicies[sp.Node] = sp
			}
		}
	}

	merged := &Policy{ACL: aclPolicy, Keyring: keyringPolicy, Operator: operatorPolicy}

	// All the for loop appends are ugly but Go doesn't have a way to get
	// a slice of all values within a map so this is necessary

	for _, policy := range agentPolicies {
		merged.Agents = append(merged.Agents, policy)
	}

	for _, policy := range agentPrefixPolicies {
		merged.AgentPrefixes = append(merged.AgentPrefixes, policy)
	}

	for _, policy := range eventPolicies {
		merged.Events = append(merged.Events, policy)
	}

	for _, policy := range eventPrefixPolicies {
		merged.EventPrefixes = append(merged.EventPrefixes, policy)
	}

	for _, policy := range keyPolicies {
		merged.Keys = append(merged.Keys, policy)
	}

	for _, policy := range keyPrefixPolicies {
		merged.KeyPrefixes = append(merged.KeyPrefixes, policy)
	}

	for _, policy := range nodePolicies {
		merged.Nodes = append(merged.Nodes, policy)
	}

	for _, policy := range nodePrefixPolicies {
		merged.NodePrefixes = append(merged.NodePrefixes, policy)
	}

	for _, policy := range preparedQueryPolicies {
		merged.PreparedQueries = append(merged.PreparedQueries, policy)
	}

	for _, policy := range preparedQueryPrefixPolicies {
		merged.PreparedQueryPrefixes = append(merged.PreparedQueryPrefixes, policy)
	}

	for _, policy := range servicePolicies {
		merged.Services = append(merged.Services, policy)
	}

	for _, policy := range servicePrefixPolicies {
		merged.ServicePrefixes = append(merged.ServicePrefixes, policy)
	}

	for _, policy := range sessionPolicies {
		merged.Sessions = append(merged.Sessions, policy)
	}

	for _, policy := range sessionPrefixPolicies {
		merged.SessionPrefixes = append(merged.SessionPrefixes, policy)
	}

	merged.ID = fmt.Sprintf("%x", multiPolicyID(policies))

	return merged
}