// CreateFirewallRules creates new firewall rules.
//
// API reference: https://developers.cloudflare.com/firewall/api/cf-firewall-rules/post/
965367
func (api *API) CreateFirewallRules(zoneID string, firewallRules []FirewallRule) ([]FirewallRule, error) {
	uri := fmt.Sprintf("/zones/%s/firewall/rules", zoneID)

	res, err := api.makeRequest("POST", uri, firewallRules)
	if err != nil {
		return []FirewallRule{}, errors.Wrap(err, errMakeRequestError)
	}

	var firewallRulesDetailResponse FirewallRulesDetailResponse
	err = json.Unmarshal(res, &firewallRulesDetailResponse)
	if err != nil {
		return []FirewallRule{}, errors.Wrap(err, errUnmarshalError)
	}

	return firewallRulesDetailResponse.Result, nil
}
24062
func (c *Client) DeleteFirewallRule(fwRuleID string) error {
	req := request{
		method:         client.DELETE,
		url:            makeURL(apiFirewallRules, fwRuleID),
		expectedStatus: http.StatusNoContent,
	}
	if _, err := c.sendRequest(req); err != nil {
		return errors.Newf(err, "failed to delete firewall rule with id %s", fwRuleID)
	}
	return nil
}
981408
func (c *Client) DeleteFirewallRule(p *DeleteFirewallRuleParameter) (*Result, error) {
	obj, err := c.Request("deleteFirewallRule", convertParamToMap(p))
	if err != nil {
		return nil, err
	}
	return obj.(*Result), err
}
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
}
1043156
func (api *API) AddFirewallPolicyServerIps(fp_id string, ip_ids []string) (*FirewallPolicy, error) {
	result := new(FirewallPolicy)
	request := serverIps{
		ServerIps: ip_ids,
	}

	url := createUrl(api, firewallPolicyPathSegment, fp_id, "server_ips")
	err := api.Client.Post(url, &request, &result, http.StatusAccepted)
	if err != nil {
		return nil, err
	}
	result.api = api
	return result, nil
}
238094
func (c *Client) GetFirewallRules(groupID string) ([]FirewallRule, error) {
	var ruleMap map[string]FirewallRule
	ipTypes := []string{"v4", "v6"}
	for _, ipType := range ipTypes {
		args := fmt.Sprintf("direction=in&FIREWALLGROUPID=%s&ip_type=%s",
			groupID, ipType)
		if err := c.get(`firewall/rule_list?`+args, &ruleMap); err != nil {
			return nil, err
		}
	}

	var ruleList []FirewallRule
	for _, r := range ruleMap {
		ruleList = append(ruleList, r)
	}
	sort.Sort(firewallRules(ruleList))
	return ruleList, nil
}
1340287
func (f Firewall) convertFromSecRules(rules ...response.SecRule) (map[string][]network.IngressRule, error) {
	applications, err := f.getAllApplicationsAsMap()
	if err != nil {
		return nil, errors.Trace(err)
	}

	iplists, err := f.getAllIPListsAsMap()
	if err != nil {
		return nil, errors.Trace(err)
	}

	ret := map[string][]network.IngressRule{}
	for _, val := range rules {
		app := val.Application
		srcList := strings.TrimPrefix(val.Src_list, "seciplist:")
		dstList := strings.TrimPrefix(val.Dst_list, "seclist:")
		portRange := f.convertApplicationToPortRange(applications[app])
		if _, ok := ret[dstList]; !ok {
			ret[dstList] = []network.IngressRule{
				{
					PortRange:   portRange,
					SourceCIDRs: iplists[srcList].Secipentries,
				},
			}
		} else {
			toAdd := network.IngressRule{
				PortRange:   portRange,
				SourceCIDRs: iplists[srcList].Secipentries,
			}
			ret[dstList] = append(ret[dstList], toAdd)
		}
	}
	return ret, nil
}
580609
func (s *FirewallService) DeleteEgressFirewallRule(p *DeleteEgressFirewallRuleParams) (*DeleteEgressFirewallRuleResponse, error) {
	resp, err := s.cs.newRequest("deleteEgressFirewallRule", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r DeleteEgressFirewallRuleResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	// If we have a async client, we need to wait for the async result
	if s.cs.async {
		b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
		if err != nil {
			if err == AsyncTimeoutErr {
				return &r, err
			}
			return nil, err
		}

		b, err = convertFirewallServiceResponse(b)
		if err != nil {
			return nil, err
		}

		if err := json.Unmarshal(b, &r); err != nil {
			return nil, err
		}
	}

	return &r, nil
}
864757
func (gce Connection) IngressRules(fwname string) ([]network.IngressRule, error) {
	ruleset, err := gce.firewallRules(fwname)
	if err != nil {
		return nil, errors.Trace(err)
	}
	return ruleset.toIngressRules()
}
1056063
func (gce Connection) firewallRules(fwname string) (ruleSet, error) {
	firewalls, err := gce.raw.GetFirewalls(gce.projectID, fwname)
	if errors.IsNotFound(err) {
		return make(ruleSet), nil
	}
	if err != nil {
		return nil, errors.Annotate(err, "while getting firewall rules from GCE")
	}

	return newRuleSetFromFirewalls(firewalls...)
}
1253515
func (d *Deployer) setFirewall(ctx context.Context, computeService *compute.Service) error {
	defaultNet, err := computeService.Networks.Get(d.Conf.Project, "default").Do()
	if err != nil {
		return fmt.Errorf("error getting default network: %v", err)
	}

	needRules := map[string]compute.Firewall{
		"default-allow-http": {
			Name:         "default-allow-http",
			SourceRanges: []string{"0.0.0.0/0"},
			SourceTags:   []string{"http-server"},
			Allowed:      []*compute.FirewallAllowed{{IPProtocol: "tcp", Ports: []string{"80"}}},
			Network:      defaultNet.SelfLink,
		},
		"default-allow-https": {
			Name:         "default-allow-https",
			SourceRanges: []string{"0.0.0.0/0"},
			SourceTags:   []string{"https-server"},
			Allowed:      []*compute.FirewallAllowed{{IPProtocol: "tcp", Ports: []string{"443"}}},
			Network:      defaultNet.SelfLink,
		},
	}

	rules, err := computeService.Firewalls.List(d.Conf.Project).Do()
	if err != nil {
		return fmt.Errorf("error listing rules: %v", err)
	}
	for _, it := range rules.Items {
		delete(needRules, it.Name)
	}
	if len(needRules) == 0 {
		return nil
	}

	if Verbose {
		d.Printf("Need to create rules: %v", needRules)
	}
	var wg syncutil.Group
	for name, rule := range needRules {
		select {
		case <-ctx.Done():
			return ctx.Err()
		default:
		}
		name, rule := name, rule
		wg.Go(func() error {
			if Verbose {
				d.Printf("Creating rule %s", name)
			}
			r, err := computeService.Firewalls.Insert(d.Conf.Project, &rule).Do()
			if err != nil {
				return fmt.Errorf("error creating rule %s: %v", name, err)
			}
			if Verbose {
				d.Printf("Created rule %s: %+v", name, r)
			}
			return nil
		})
	}
	return wg.Err()
}
1240493
func (o *VirtualFirewallPolicy) CreateVirtualFirewallRule(child *VirtualFirewallRule) *bambou.Error {

	return bambou.CurrentSession().CreateChild(o, child)
}
215110
func (opts RuleCreateOpts) ToRuleCreateMap() (map[string]interface{}, error) {
	b, err := BuildRequest(opts, "firewall_rule")
	if err != nil {
		return nil, err
	}

	if m := b["firewall_rule"].(map[string]interface{}); m["protocol"] == "any" {
		m["protocol"] = nil
	}

	return b, nil
}
1149270
func (c *Client) CreateFirewallRule(p *CreateFirewallRuleParameter) (*FirewallRule, error) {
	obj, err := c.Request("createFirewallRule", convertParamToMap(p))
	if err != nil {
		return nil, err
	}
	return obj.(*FirewallRule), err
}
497597
func (r Network_Firewall_Update_Request) GetRules() (resp []datatypes.Network_Firewall_Update_Request_Rule, err error) {
	err = r.Session.DoRequest("SoftLayer_Network_Firewall_Update_Request", "getRules", nil, &r.Options, &resp)
	return
}
622007
func (c *CloudAPI) ListMachineFirewallRules(machineID string) ([]*cloudapi.FirewallRule, error) {
	if err := c.ProcessFunctionHook(c, machineID); err != nil {
		return nil, err
	}

	fwRules := []*cloudapi.FirewallRule{}
	for _, r := range c.firewallRules {
		vm := "vm " + machineID
		if strings.Contains(r.Rule, vm) {
			fwRules = append(fwRules, r)
		}
	}

	return fwRules, nil
}
216173
func (f Firewall) getAllSecurityRules(aclName string) ([]response.SecurityRule, error) {
	rules, err := f.client.AllSecurityRules(nil)
	if err != nil {
		return nil, err
	}
	if aclName == "" {
		return rules.Result, nil
	}
	var ret []response.SecurityRule
	for _, val := range rules.Result {
		if val.Acl == aclName {
			ret = append(ret, val)
		}
	}
	return ret, nil
}