<commit_before>/**
 * Copyright (C) 2012-2013 Dell, Inc
 * See annotations for authorship information
 *
 * ====================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ====================================================================
 */

package org.dasein.cloud.google.network;

import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.services.compute.Compute;
import com.google.api.services.compute.model.*;
import com.google.api.services.compute.model.Firewall.Allowed;

import org.apache.http.conn.util.InetAddressUtils;
import org.apache.log4j.Logger;
import org.dasein.cloud.*;
import org.dasein.cloud.google.Google;
import org.dasein.cloud.google.GoogleException;
import org.dasein.cloud.google.GoogleMethod;
import org.dasein.cloud.google.GoogleOperationType;
import org.dasein.cloud.google.capabilities.GCEFirewallCapabilities;
import org.dasein.cloud.network.*;
import org.dasein.cloud.network.Firewall;
import org.dasein.cloud.util.APITrace;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import java.io.IOException;
import java.util.*;

/**
 * Implements the firewall services supported in the Google API.
 * @author <NAME>
 * @version 2014.05 refactor
 * @since 2014.03
 */
public class FirewallSupport extends AbstractFirewallSupport{
    static private final Logger logger = Google.getLogger(org.dasein.cloud.network.FirewallSupport.class);

    private Google provider = null;

    FirewallSupport(Google provider) {
        super(provider);
        this.provider = provider;
    }

    @Override
    public @Nonnull String authorize(@Nonnull String firewallId, @Nonnull Direction direction, @Nonnull Permission permission, @Nonnull RuleTarget sourceEndpoint, @Nonnull Protocol protocol, @Nonnull RuleTarget destinationEndpoint, int beginPort, int endPort, int precedence) throws CloudException, InternalException {
        APITrace.begin(provider, "Firewall.authorize");
        try{
            if( Permission.DENY.equals(permission) ) {
                throw new OperationNotSupportedException("GCE does not support DENY rules");
            }
            if( direction.equals(Direction.EGRESS) ){
                throw new OperationNotSupportedException("GCE does not support EGRESS rules");
            }
            Compute gce = provider.getGoogleCompute();
            com.google.api.services.compute.model.Firewall googleFirewall = new com.google.api.services.compute.model.Firewall();

            Random r = new Random();
            char c = (char)(r.nextInt(26) + 'a');
            googleFirewall.setName(c + UUID.randomUUID().toString());
            googleFirewall.setDescription(sourceEndpoint.getCidr() + ":" + protocol.name() + ":" + beginPort + "-" + endPort);

            VLAN vlan = provider.getNetworkServices().getVlanSupport().getVlan(firewallId.split("fw-")[1]);
            googleFirewall.setNetwork(vlan.getTag("contentLink"));

            String portString = "";
            if(beginPort == endPort)portString = beginPort + "";
            else{
                portString = beginPort + "-" + endPort;
            }
            ArrayList<Allowed> allowedRules = new ArrayList<Allowed>();
            Allowed allowed = new Allowed();
            allowed.setIPProtocol(protocol.name());
            allowed.setPorts(Collections.singletonList(portString));
            allowedRules.add(allowed);
            googleFirewall.setAllowed(allowedRules);

            if(sourceEndpoint.getRuleTargetType().equals(RuleTargetType.VLAN) || sourceEndpoint.getRuleTargetType().equals(RuleTargetType.GLOBAL)){
                throw new OperationNotSupportedException("GCE does not support VLAN or GLOBAL as valid source types");
            }
            if(sourceEndpoint.getRuleTargetType().equals(RuleTargetType.VM)){
                googleFirewall.setSourceTags(Collections.singletonList(sourceEndpoint.getProviderVirtualMachineId()));
            }
            else if(sourceEndpoint.getRuleTargetType().equals(RuleTargetType.CIDR)){
                googleFirewall.setSourceRanges(Collections.singletonList(sourceEndpoint.getCidr()));
            }

            if(destinationEndpoint.getRuleTargetType().equals(RuleTargetType.VM)){
                googleFirewall.setTargetTags(Collections.singletonList(destinationEndpoint.getProviderVirtualMachineId()));
            }
            else if(!destinationEndpoint.getRuleTargetType().equals(RuleTargetType.VLAN)){
                throw new OperationNotSupportedException("GCE only supports either specific VMs or the whole network as a valid destination type");
            }

            try{
                Operation job = gce.firewalls().insert(provider.getContext().getAccountNumber(), googleFirewall).execute();
                GoogleMethod method = new GoogleMethod(provider);
                return method.getOperationTarget(provider.getContext(), job, GoogleOperationType.GLOBAL_OPERATION, "", "", false);
    	    } catch (IOException ex) {
                logger.error(ex.getMessage());
    			if (ex.getClass() == GoogleJsonResponseException.class) {
    				GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex;
    				throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage());
    			} else
    				throw new CloudException("An error occurred creating a new rule on " + firewallId + ": " + ex.getMessage());
    		}<commit_msg>Support for creating ICMP rules requires 0.0.0.0/0 as a CIDR<commit_after>/**
 * Copyright (C) 2012-2013 Dell, Inc
 * See annotations for authorship information
 *
 * ====================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ====================================================================
 */

package org.dasein.cloud.google.network;

import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.services.compute.Compute;
import com.google.api.services.compute.model.*;
import com.google.api.services.compute.model.Firewall.Allowed;

import org.apache.http.conn.util.InetAddressUtils;
import org.apache.log4j.Logger;
import org.dasein.cloud.*;
import org.dasein.cloud.google.Google;
import org.dasein.cloud.google.GoogleException;
import org.dasein.cloud.google.GoogleMethod;
import org.dasein.cloud.google.GoogleOperationType;
import org.dasein.cloud.google.capabilities.GCEFirewallCapabilities;
import org.dasein.cloud.network.*;
import org.dasein.cloud.network.Firewall;
import org.dasein.cloud.util.APITrace;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import java.io.IOException;
import java.util.*;

/**
 * Implements the firewall services supported in the Google API.
 * @author <NAME>
 * @version 2014.05 refactor
 * @since 2014.03
 */
public class FirewallSupport extends AbstractFirewallSupport{
    static private final Logger logger = Google.getLogger(org.dasein.cloud.network.FirewallSupport.class);

    private Google provider = null;

    FirewallSupport(Google provider) {
        super(provider);
        this.provider = provider;
    }

    @Override
    public @Nonnull String authorize(@Nonnull String firewallId, @Nonnull Direction direction, @Nonnull Permission permission, @Nonnull RuleTarget sourceEndpoint, @Nonnull Protocol protocol, @Nonnull RuleTarget destinationEndpoint, int beginPort, int endPort, int precedence) throws CloudException, InternalException {
        APITrace.begin(provider, "Firewall.authorize");
        try{
            if( Permission.DENY.equals(permission) ) {
                throw new OperationNotSupportedException("GCE does not support DENY rules");
            }
            if( direction.equals(Direction.EGRESS) ){
                throw new OperationNotSupportedException("GCE does not support EGRESS rules");
            }
            Compute gce = provider.getGoogleCompute();
            com.google.api.services.compute.model.Firewall googleFirewall = new com.google.api.services.compute.model.Firewall();

            Random r = new Random();
            char c = (char)(r.nextInt(26) + 'a');
            googleFirewall.setName(c + UUID.randomUUID().toString());
            if(protocol == Protocol.ICMP)
                googleFirewall.setDescription(sourceEndpoint.getCidr() + ":" + protocol.name()); //  + ":" + beginPort + "-" + endPort);
            else
                googleFirewall.setDescription(sourceEndpoint.getCidr() + ":" + protocol.name() + ":" + beginPort + "-" + endPort);
            VLAN vlan = provider.getNetworkServices().getVlanSupport().getVlan(firewallId.split("fw-")[1]);
            googleFirewall.setNetwork(vlan.getTag("contentLink"));

            String portString = "";
            if(beginPort == endPort)portString = beginPort + "";
            else{
                portString = beginPort + "-" + endPort;
            }
            ArrayList<Allowed> allowedRules = new ArrayList<Allowed>();
            Allowed allowed = new Allowed();
            allowed.setIPProtocol(protocol.name());
            if(protocol != Protocol.ICMP)
                allowed.setPorts(Collections.singletonList(portString));
            allowedRules.add(allowed);
            googleFirewall.setAllowed(allowedRules);

            if(sourceEndpoint.getRuleTargetType().equals(RuleTargetType.VLAN) || sourceEndpoint.getRuleTargetType().equals(RuleTargetType.GLOBAL)){
                throw new OperationNotSupportedException("GCE does not support VLAN or GLOBAL as valid source types");
            }
            if(sourceEndpoint.getRuleTargetType().equals(RuleTargetType.VM)){
                googleFirewall.setSourceTags(Collections.singletonList(sourceEndpoint.getProviderVirtualMachineId()));
            }
            else if(sourceEndpoint.getRuleTargetType().equals(RuleTargetType.CIDR)){
                googleFirewall.setSourceRanges(Collections.singletonList(sourceEndpoint.getCidr()));
            }

            if(destinationEndpoint.getRuleTargetType().equals(RuleTargetType.VM)){
                googleFirewall.setTargetTags(Collections.singletonList(destinationEndpoint.getProviderVirtualMachineId()));
            }
            else if((!destinationEndpoint.getRuleTargetType().equals(RuleTargetType.VLAN)) && (protocol != Protocol.ICMP)){
                throw new OperationNotSupportedException("GCE only supports either specific VMs or the whole network as a valid destination type");
            }

            try{
                Operation job = gce.firewalls().insert(provider.getContext().getAccountNumber(), googleFirewall).execute();
                GoogleMethod method = new GoogleMethod(provider);
                return method.getOperationTarget(provider.getContext(), job, GoogleOperationType.GLOBAL_OPERATION, "", "", false);
    	    } catch (IOException ex) {
                logger.error(ex.getMessage());
    			if (ex.getClass() == GoogleJsonResponseException.class) {
    				GoogleJsonResponseException gjre = (GoogleJsonResponseException)ex;
    				throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage());
    			} else
    				throw new CloudException("An error occurred creating a new rule on " + firewallId + ": " + ex.getMessage());
    		}
{'fraction_non_alphanumeric': 0.12490922294843863, 'fraction_numerical': 0.004922133462438473, 'mean_word_length': 3.3733239237826393, 'pattern_counts': {'":': 8, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 1, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5629087', 'n_tokens_mistral': 3256, 'n_tokens_neox': 3140, 'n_words': 718}