// Creates an ip forwarding rule
179961
func (c *Client) CreateIpForwardingRule(p *CreateIpForwardingRuleParameter) (*IpForwardingRule, error) {
	obj, err := c.Request("createIpForwardingRule", convertParamToMap(p))
	if err != nil {
		return nil, err
	}
	return obj.(*IpForwardingRule), err
}
529609
func IP() (string, error) {
	ips := make(chan string, 1)
	errs := make(chan error, 1)
	for _, server := range ipServers {
		server := server
		go func() {
			resp, err := http.Get(server)
			if err != nil {
				errs <- err
				return
			}
			body, _ := ioutil.ReadAll(resp.Body)
			ipAddr := strings.TrimSpace(string(body))
			ip := net.ParseIP(ipAddr)
			if ip == nil {
				errs <- fmt.Errorf("invalid ip address: %s", ipAddr)
				return
			}
			ips <- ip.String()
		}()
	}
	var errors []error
	var resps []string
	respMap := make(map[string]int)
	for (len(resps) < 2 || len(respMap) > 1) && len(resps)+len(errors) < len(ipServers) {
		select {
		case resp := <-ips:
			resps = append(resps, resp)
			respMap[resp]++
		case err := <-errs:
			errors = append(errors, err)
		}
	}
	if len(resps) == 0 {
		return "", errors[0]
	}
	// pick best ip address
	var best string
	mostVotes := 0
	for addr, votes := range respMap {
		if votes > mostVotes {
			mostVotes = votes
			best = addr
		}
	}
	return best, nil
}
741965
func (s *FirewallService) NewCreateFirewallRuleParams(ipaddressid string, protocol string) *CreateFirewallRuleParams {
	p := &CreateFirewallRuleParams{}
	p.p = make(map[string]interface{})
	p.p["ipaddressid"] = ipaddressid
	p.p["protocol"] = protocol
	return p
}
93157
func (c *sshInstanceConfigurator) FindIngressRules() ([]network.IngressRule, error) {
	output, err := c.runCommand("sudo iptables -L INPUT -n")
	if err != nil {
		return nil, errors.Errorf("failed to list open ports: %s", output)
	}
	logger.Tracef("find open ports output: %s", output)
	return iptables.ParseIngressRules(strings.NewReader(output))
}
1114844
func (c *Client) UpdatePortForwardingRule(p *UpdatePortForwardingRuleParameter) (*PortForwardingRule, error) {
	obj, err := c.Request("updatePortForwardingRule", convertParamToMap(p))
	if err != nil {
		return nil, err
	}
	return obj.(*PortForwardingRule), err
}
275859
func NewIPAddressFunc(key Key, IPNets ...*net.IPNet) (Function, error) {
	if key != AWSSourceIP {
		return nil, fmt.Errorf("only %v key is allowed for %v condition", AWSSourceIP, ipAddress)
	}

	return &ipAddressFunc{key, IPNets}, nil
}
467791
func (p2p *P2P) ForwardRemote(ctx context.Context, proto protocol.ID, addr ma.Multiaddr, reportRemote bool) (Listener, error) {
	listener := &remoteListener{
		p2p: p2p,

		proto: proto,
		addr:  addr,

		reportRemote: reportRemote,
	}

	if err := p2p.ListenersP2P.Register(listener); err != nil {
		return nil, err
	}

	return listener, nil
}
287494
func (c *Context) Proxy() []string {
	if ips := c.Header("X-Forwarded-For"); ips != "" {
		return strings.Split(ips, ",")
	}
	return []string{}
}
576778
func (g *Cloud) GetRegionForwardingRule(name, region string) (*compute.ForwardingRule, error) {
	ctx, cancel := cloud.ContextWithCallTimeout()
	defer cancel()

	mc := newForwardingRuleMetricContext("get", region)
	v, err := g.c.ForwardingRules().Get(ctx, meta.RegionalKey(name, region))
	return v, mc.Observe(err)
}
487093
func HostIPToGateway(hostIP string) (string, error) {
	ip := strings.Split(hostIP, ".")
	if len(ip) != 4 {
		return "", errors.New("bad host IP")
	}

	return ip[0] + "." + ip[1] + ".255.254", nil
}
139630
func (ac *APIController) RuleCreate(rule *contivModel.Rule) error {
	log.Infof("Received RuleCreate: %+v", rule)
	var epg *contivModel.EndpointGroup
	epg = nil

	// verify parameter values
	if rule.Direction == "in" {
		if rule.ToNetwork != "" || rule.ToEndpointGroup != "" {
			return errors.New("can not specify 'to' parameters in incoming rule")
		}
		if rule.FromNetwork != "" && rule.FromIpAddress != "" {
			return errors.New("can not specify both from network and from ip address")
		}

		if rule.FromNetwork != "" && rule.FromEndpointGroup != "" {
			return errors.New("can not specify both from network and from EndpointGroup")
		}
	} else if rule.Direction == "out" {
		if rule.FromNetwork != "" || rule.FromEndpointGroup != "" || rule.FromIpAddress != "" {
			return errors.New("can not specify 'from' parameters in outgoing rule")
		}
		if rule.ToNetwork != "" && rule.ToIpAddress != "" {
			return errors.New("can not specify both to-network and to-ip address")
		}
		if rule.ToNetwork != "" && rule.ToEndpointGroup != "" {
			return errors.New("can not specify both to-network and to-EndpointGroup")
		}
	} else {
		return errors.New("invalid direction for the rule")
	}

	// Make sure endpoint groups and networks referred exists.
	if rule.FromEndpointGroup != "" {
		epgKey := rule.TenantName + ":" + rule.FromEndpointGroup
		// find the endpoint group
		epg = contivModel.FindEndpointGroup(epgKey)
		if epg == nil {
			log.Errorf("Error finding endpoint group %s", epgKey)
			return errors.New("endpoint group not found")
		}
	} else if rule.ToEndpointGroup != "" {
		epgKey := rule.TenantName + ":" + rule.ToEndpointGroup

		// find the endpoint group
		epg = contivModel.FindEndpointGroup(epgKey)
		if epg == nil {
			log.Errorf("Error finding endpoint group %s", epgKey)
			return errors.New("endpoint group not found")
		}
	} else if rule.FromNetwork != "" {
		netKey := rule.TenantName + ":" + rule.FromNetwork

		net := contivModel.FindNetwork(netKey)
		if net == nil {
			log.Errorf("Network %s not found", netKey)
			return errors.New("from Network not found")
		}
	} else if rule.ToNetwork != "" {
		netKey := rule.TenantName + ":" + rule.ToNetwork

		net := contivModel.FindNetwork(netKey)
		if net == nil {
			log.Errorf("Network %s not found", netKey)
			return errors.New("to Network not found")
		}
	}

	policyKey := GetpolicyKey(rule.TenantName, rule.PolicyName)

	// find the policy
	policy := contivModel.FindPolicy(policyKey)
	if policy == nil {
		log.Errorf("Error finding policy %s", policyKey)
		return core.Errorf("Policy not found")
	}

	if rule.Direction == "in" && rule.ToIpAddress != "" {
		// rules from k8s network policy
		// verify 'toIpAddress' is part of epg and subnet
		if len(policy.LinkSets.EndpointGroups) != 1 {
			errMsg := fmt.Errorf("failed to configure %s, %d endpoint groups linked to policy %s ",
				rule.ToIpAddress,
				len(policy.LinkSets.EndpointGroups),
				rule.PolicyName)
			log.Error(errMsg)
			return errMsg
		}
		epgKey := ""
		for key := range policy.LinkSets.EndpointGroups {
			epgKey = strings.Replace(key, rule.TenantName+":", "", 1) + ":" + rule.TenantName
		}

		stateDriver, err := utils.GetStateDriver()
		if err != nil {
			log.Errorf("failed to configure %s, %s", rule.ToIpAddress, err)
			return fmt.Errorf("failed to configure %s, unable to connect to key-value store",
				rule.ToIpAddress)
		}
		readEp := &mastercfg.CfgEndpointState{}
		readEp.StateDriver = stateDriver
		epCfgs, err := readEp.ReadAll()
		if err != nil {
			log.Errorf("failed to configure %s, %s", rule.ToIpAddress, err)
			return fmt.Errorf("failed to configure %s, unable to read endpoint state", rule.ToIpAddress)
		}

		// TODO: cache ip <--> epg for performance
		if func(epgName string) bool {
			for _, epCfg := range epCfgs {
				if ep, ok := epCfg.(*mastercfg.CfgEndpointState); ok {
					if ep.IPAddress == rule.ToIpAddress && ep.EndpointGroupKey == epgName {
						return true
					}
				}
			}
			return false
		}(epgKey) != true {
			errMsg := fmt.Errorf("failed to configure %s, ip address is not in epg %s",
				rule.ToIpAddress,
				epgKey)
			log.Error(errMsg)
			return errMsg
		}
	}

	// Trigger policyDB Update
	err := master.PolicyAddRule(policy, rule)
	if err != nil {
		log.Errorf("Error adding rule %s to policy %s. Err: %v", rule.Key, policy.Key, err)
		return err
	}

	// link the rule to policy
	modeldb.AddLinkSet(&rule.LinkSets.Policies, policy)
	modeldb.AddLinkSet(&policy.LinkSets.Rules, rule)
	err = policy.Write()
	if err != nil {
		return err
	}

	// link the rule to epg and vice versa
	if epg != nil {
		modeldb.AddLinkSet(&epg.LinkSets.MatchRules, rule)
		modeldb.AddLink(&rule.Links.MatchEndpointGroup, epg)
		err = epg.Write()
		if err != nil {
			return err
		}
	}

	// Update any affected app profiles
	pMap := getAffectedProfs(policy, epg)
	syncAppProfile(pMap)

	return nil
}
105983
func (n *NetworkServerAPI) CreateRoutingProfile(ctx context.Context, req *ns.CreateRoutingProfileRequest) (*ns.CreateRoutingProfileResponse, error) {
	if req.RoutingProfile == nil {
		return nil, grpc.Errorf(codes.InvalidArgument, "routing_profile must not be nil")
	}

	var rpID uuid.UUID
	copy(rpID[:], req.RoutingProfile.Id)

	rp := storage.RoutingProfile{
		ID:      rpID,
		ASID:    req.RoutingProfile.AsId,
		CACert:  req.RoutingProfile.CaCert,
		TLSCert: req.RoutingProfile.TlsCert,
		TLSKey:  req.RoutingProfile.TlsKey,
	}
	if err := storage.CreateRoutingProfile(storage.DB(), &rp); err != nil {
		return nil, errToRPCError(err)
	}

	return &ns.CreateRoutingProfileResponse{
		Id: rp.ID.Bytes(),
	}, nil
}
975659
func (c *Client) CreateIPv4(id string, reboot bool) error {
	values := url.Values{
		"SUBID":  {id},
		"reboot": {fmt.Sprintf("%t", reboot)},
	}

	if err := c.post(`server/create_ipv4`, values, nil); err != nil {
		return err
	}
	return nil
}
736529
func (b *BigIP) CreateRoute(name, dest, gateway string) error {
	config := &Route{
		Name:    name,
		Network: dest,
		Gateway: gateway,
	}

	return b.post(config, uriNet, uriRoute)
}
1318960
func createFirewallRuleAll(envName string, portRange network.IngressRule) string {
	ports := []string{}
	for p := portRange.FromPort; p <= portRange.ToPort; p++ {
		ports = append(ports, fmt.Sprintf("PORT %d", p))
	}
	var portList string
	if len(ports) > 1 {
		portList = fmt.Sprintf("( %s )", strings.Join(ports, " AND "))
	} else if len(ports) == 1 {
		portList = ports[0]
	}
	return fmt.Sprintf(firewallRuleAll, envName, strings.ToLower(portRange.Protocol), portList)
}
61579
func NewForwarder(cfg ForwarderConfig) (*Forwarder, error) {
	if err := cfg.CheckAndSetDefaults(); err != nil {
		return nil, trace.Wrap(err)
	}

	creds, err := getKubeCreds(cfg.KubeconfigPath)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	clusterSessions, err := ttlmap.New(defaults.ClientCacheSize)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	closeCtx, close := context.WithCancel(cfg.Context)
	fwd := &Forwarder{
		creds: *creds,
		Entry: log.WithFields(log.Fields{
			trace.Component: teleport.Component(teleport.ComponentKube),
		}),
		Router:          *httprouter.New(),
		ForwarderConfig: cfg,
		clusterSessions: clusterSessions,
		activeRequests:  make(map[string]context.Context),
		ctx:             closeCtx,
		close:           close,
	}

	fwd.POST("/api/:ver/namespaces/:podNamespace/pods/:podName/exec", fwd.withAuth(fwd.exec))
	fwd.GET("/api/:ver/namespaces/:podNamespace/pods/:podName/exec", fwd.withAuth(fwd.exec))

	fwd.POST("/api/:ver/namespaces/:podNamespace/pods/:podName/attach", fwd.withAuth(fwd.exec))
	fwd.GET("/api/:ver/namespaces/:podNamespace/pods/:podName/attach", fwd.withAuth(fwd.exec))

	fwd.POST("/api/:ver/namespaces/:podNamespace/pods/:podName/portforward", fwd.withAuth(fwd.portForward))
	fwd.GET("/api/:ver/namespaces/:podNamespace/pods/:podName/portforward", fwd.withAuth(fwd.portForward))

	fwd.NotFound = fwd.withAuthStd(fwd.catchAll)

	if cfg.ClusterOverride != "" {
		fwd.Debugf("Cluster override is set, forwarder will send all requests to remote cluster %v.", cfg.ClusterOverride)
	}
	return fwd, nil
}
779436
func NewForward(ctx context.Context, next http.Handler, config config.ForwardAuth, name string) (http.Handler, error) {
	middlewares.GetLogger(ctx, name, forwardedTypeName).Debug("Creating middleware")

	fa := &forwardAuth{
		address:             config.Address,
		authResponseHeaders: config.AuthResponseHeaders,
		next:                next,
		name:                name,
		trustForwardHeader:  config.TrustForwardHeader,
	}

	if config.TLS != nil {
		tlsConfig, err := config.TLS.CreateTLSConfig()
		if err != nil {
			return nil, err
		}

		fa.tlsConfig = tlsConfig
	}

	return fa, nil
}