<commit_before>/****************************************************************
 * Licensed to the Apache Software Foundation (ASF) under one   *
 * or more contributor license agreements.  See the NOTICE file *
 * distributed with this work for additional information        *
 * regarding copyright ownership.  The ASF licenses this file   *
 * to you 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.apache.james.util;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.ArrayList;
import java.util.Iterator;

import org.apache.james.services.DNSServer;

/**
 * Class which can be used to check if an ipAddress match a network
 */
public class NetMatcher
{
    private DNSServer dnsServer;
    
    private ArrayList networks;


    /**
     * Init the class with the given networks 
     *
     * @param nets a Collection which holds all networks
     */
    public void initInetNetworks(final Collection nets)
    {
        networks = new ArrayList();
        
        InetNetwork in = new InetNetwork(dnsServer);
        
        for (Iterator iter = nets.iterator(); iter.hasNext(); ) try
        {
            InetNetwork net = in.getFromString((String) iter.next());
            if (!networks.contains(net)) networks.add(net);
        }
        catch (java.net.UnknownHostException uhe)
        {
            log("Cannot resolve address: " + uhe.getMessage());
        }
        networks.trimToSize();
    }

    /**
     * Init the class with the given networks 
     *
     * @param nets a String[] which holds all networks
     */
    public void initInetNetworks(final String[] nets)
    {
        
        networks = new ArrayList();
        
        InetNetwork in = new InetNetwork(dnsServer);
        
        for (int i = 0; i < nets.length; i++) try
        {
            InetNetwork net = in.getFromString(nets[i]);
            if (!networks.contains(net)) networks.add(net);
        }
        catch (java.net.UnknownHostException uhe)
        {
            log("Cannot resolve address: " + uhe.getMessage());
        }
        networks.trimToSize();
    }

    /**
     * Return true if passed host match a network which was used to init the Netmatcher
     * 
     * @param hostIP the ipAddress or hostname to check
     * @return true if match the network
     */
    public boolean matchInetNetwork(final String hostIP)
    {
        InetAddress ip = null;

        try
        {
            ip = dnsServer.getByName(hostIP);
        }
        catch (java.net.UnknownHostException uhe)
        {
            log("Cannot resolve address for " + hostIP + ": " + uhe.getMessage());
        }

        boolean sameNet = false;

        if (ip != null) for (Iterator iter = networks.iterator(); (!sameNet) && iter.hasNext(); )
        {
            InetNetwork network = (InetNetwork) iter.next();
            sameNet = network.contains(ip);
        }
        return sameNet;
    }

    /**
     * @see #matchInetNetwork(String)
     */
    public boolean matchInetNetwork(final InetAddress ip)
    {
        boolean sameNet = false;

        for (Iterator iter = networks.iterator(); (!sameNet) && iter.hasNext(); )
        {
            InetNetwork network = (InetNetwork) iter.next();
            sameNet = network.contains(ip);
        }
        return sameNet;
    }

    /**
     * Create a new instance of Netmatcher
     * 
     * @param nets a String[] which holds all networks
     * @param dnsServer the DNSServer which will be used in this class
     */
    public NetMatcher(final String[] nets,DNSServer dnsServer)
    {
        this.dnsServer = dnsServer;
        initInetNetworks(nets);
    }

    /**
     * Create a new instance of Netmatcher
     * 
     * @param nets a Collection which holds all networks
     * @param dnsServer the DNSServer which will be used in this class
     */ 
    public NetMatcher(final Collection nets,DNSServer dnsServer)
    {
        this.dnsServer = dnsServer;
        initInetNetworks(nets);
    }

    /**
     * @see InetNetwork#toString()
     */
    public String toString() {
        return networks.toString();
    }

    /**
     * Can be overwritten for loggin
     * 
     * @param s the String to log
     */
    protected void log(String s) { }
}

class InetNetwork
{

    /*
     * Implements network masking, and is compatible with RFC 1518 and
     * RFC 1519, which describe CIDR: Classless Inter-Domain Routing.
     */

    private InetAddress network;
    private InetAddress netmask;
    private DNSServer dnsServer;
    
    /**
     * Constructor
     * 
     * @param dnsServer the DNSServer to use
     */
    InetNetwork(DNSServer dnsServer) {
        this.dnsServer = dnsServer;
    }

    /**
     * Constuctor
     * 
     * @param ip the InetAddress to init the class
     * @param netmask the InetAddress represent the netmask to init the class
     */
    public InetNetwork(InetAddress ip, InetAddress netmask)
    {
        network = maskIP(ip, netmask);
        this.netmask = netmask;
    }

    /**
     * Return true if the network contains the given name
     * 
     * @param name hostname or ipAddress
     * @return true if the network contains the given name
     * @throws java.net.UnknownHostException if the given name can not resolved
     */
    public boolean contains(final String name) throws java.net.UnknownHostException
    {
        return network.equals(maskIP(dnsServer.getByName(name), netmask));
    }

    /**
     * @see #contains(String)
     */
    public boolean contains(final InetAddress ip)
    {
        return network.equals(maskIP(ip, netmask));
    }

    /**
     * Return String represention of this class 
     * 
     * @return string String representation of this class
     */
    public String toString()
    {
        return network.getHostAddress() + "/" + netmask.getHostAddress();
    }

    /**
     * Return hashCode representation of this class
     * 
     * @return hashCode the hashCode representation of this class
     */
    public int hashCode()
    {
        return maskIP(network, netmask).hashCode();
    }

    /**
     * @see java.lang.Object#equals(java.lang.Object)
     */
    public boolean equals(Object obj)
    {
        return (obj != null) && (obj instanceof InetNetwork) &&
                ((((InetNetwork)obj).network.equals(network)) && (((InetNetwork)obj).netmask.equals(netmask)));
    }

    /**
     * Get InetNetwork of the given String
     * 
     * @param netspec the String which is will converted to InetNetwork
     * @return network the InetNetwork
     * @throws java.net.UnknownHostException
     */
    public InetNetwork getFromString(String netspec) throws java.net.UnknownHostException
    {
        if (netspec.endsWith("*")) netspec = normalizeFromAsterisk(netspec);
        else
        {
            int iSlash = netspec.indexOf('/');
            if (iSlash == -1) netspec += "/255.255.255.255";
            else if (netspec.indexOf('.', iSlash) == -1) netspec = normalizeFromCIDR(netspec);
        }

        return new InetNetwork(dnsServer.getByName(netspec.substring(0, netspec.indexOf('/'))),
                               dnsServer.getByName(netspec.substring(netspec.indexOf('/') + 1)));
    }

    /**
     * Return InetAddress generated of the passed argements. Return Null if any errors accour
     * 
     * @param ip the byte[] represent the ip
     * @param mask the byte[] represent the netmask
     * @return inetAddress the InetAddress generated of the passed arguments. 
     */
    public static InetAddress maskIP(final byte[] ip, final byte[] mask)
    {
        try {
            return getByAddress(new byte[] {
		    (byte) (mask[0] & ip[0]),
		    (byte) (mask[1] & ip[1]),
		    (byte) (mask[2] & ip[2]),
		    (byte) (mask[3] & ip[3])
		});
	} catch (UnknownHostException e) {
            return null;
	}
    }

    /**
     * @see #maskIP(byte[], byte[])
     */
    public static InetAddress maskIP(final InetAddress ip, final InetAddress mask)<commit_msg>Fixing tabs<commit_after>/****************************************************************
 * Licensed to the Apache Software Foundation (ASF) under one   *
 * or more contributor license agreements.  See the NOTICE file *
 * distributed with this work for additional information        *
 * regarding copyright ownership.  The ASF licenses this file   *
 * to you 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.apache.james.util;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.ArrayList;
import java.util.Iterator;

import org.apache.james.services.DNSServer;

/**
 * Class which can be used to check if an ipAddress match a network
 */
public class NetMatcher
{
    private DNSServer dnsServer;
    
    private ArrayList networks;


    /**
     * Init the class with the given networks 
     *
     * @param nets a Collection which holds all networks
     */
    public void initInetNetworks(final Collection nets)
    {
        networks = new ArrayList();
        
        InetNetwork in = new InetNetwork(dnsServer);
        
        for (Iterator iter = nets.iterator(); iter.hasNext(); ) try
        {
            InetNetwork net = in.getFromString((String) iter.next());
            if (!networks.contains(net)) networks.add(net);
        }
        catch (java.net.UnknownHostException uhe)
        {
            log("Cannot resolve address: " + uhe.getMessage());
        }
        networks.trimToSize();
    }

    /**
     * Init the class with the given networks 
     *
     * @param nets a String[] which holds all networks
     */
    public void initInetNetworks(final String[] nets)
    {
        
        networks = new ArrayList();
        
        InetNetwork in = new InetNetwork(dnsServer);
        
        for (int i = 0; i < nets.length; i++) try
        {
            InetNetwork net = in.getFromString(nets[i]);
            if (!networks.contains(net)) networks.add(net);
        }
        catch (java.net.UnknownHostException uhe)
        {
            log("Cannot resolve address: " + uhe.getMessage());
        }
        networks.trimToSize();
    }

    /**
     * Return true if passed host match a network which was used to init the Netmatcher
     * 
     * @param hostIP the ipAddress or hostname to check
     * @return true if match the network
     */
    public boolean matchInetNetwork(final String hostIP)
    {
        InetAddress ip = null;

        try
        {
            ip = dnsServer.getByName(hostIP);
        }
        catch (java.net.UnknownHostException uhe)
        {
            log("Cannot resolve address for " + hostIP + ": " + uhe.getMessage());
        }

        boolean sameNet = false;

        if (ip != null) for (Iterator iter = networks.iterator(); (!sameNet) && iter.hasNext(); )
        {
            InetNetwork network = (InetNetwork) iter.next();
            sameNet = network.contains(ip);
        }
        return sameNet;
    }

    /**
     * @see #matchInetNetwork(String)
     */
    public boolean matchInetNetwork(final InetAddress ip)
    {
        boolean sameNet = false;

        for (Iterator iter = networks.iterator(); (!sameNet) && iter.hasNext(); )
        {
            InetNetwork network = (InetNetwork) iter.next();
            sameNet = network.contains(ip);
        }
        return sameNet;
    }

    /**
     * Create a new instance of Netmatcher
     * 
     * @param nets a String[] which holds all networks
     * @param dnsServer the DNSServer which will be used in this class
     */
    public NetMatcher(final String[] nets,DNSServer dnsServer)
    {
        this.dnsServer = dnsServer;
        initInetNetworks(nets);
    }

    /**
     * Create a new instance of Netmatcher
     * 
     * @param nets a Collection which holds all networks
     * @param dnsServer the DNSServer which will be used in this class
     */ 
    public NetMatcher(final Collection nets,DNSServer dnsServer)
    {
        this.dnsServer = dnsServer;
        initInetNetworks(nets);
    }

    /**
     * @see InetNetwork#toString()
     */
    public String toString() {
        return networks.toString();
    }

    /**
     * Can be overwritten for loggin
     * 
     * @param s the String to log
     */
    protected void log(String s) { }
}

class InetNetwork
{

    /*
     * Implements network masking, and is compatible with RFC 1518 and
     * RFC 1519, which describe CIDR: Classless Inter-Domain Routing.
     */

    private InetAddress network;
    private InetAddress netmask;
    private DNSServer dnsServer;
    
    /**
     * Constructor
     * 
     * @param dnsServer the DNSServer to use
     */
    InetNetwork(DNSServer dnsServer) {
        this.dnsServer = dnsServer;
    }

    /**
     * Constuctor
     * 
     * @param ip the InetAddress to init the class
     * @param netmask the InetAddress represent the netmask to init the class
     */
    public InetNetwork(InetAddress ip, InetAddress netmask)
    {
        network = maskIP(ip, netmask);
        this.netmask = netmask;
    }

    /**
     * Return true if the network contains the given name
     * 
     * @param name hostname or ipAddress
     * @return true if the network contains the given name
     * @throws java.net.UnknownHostException if the given name can not resolved
     */
    public boolean contains(final String name) throws java.net.UnknownHostException
    {
        return network.equals(maskIP(dnsServer.getByName(name), netmask));
    }

    /**
     * @see #contains(String)
     */
    public boolean contains(final InetAddress ip)
    {
        return network.equals(maskIP(ip, netmask));
    }

    /**
     * Return String represention of this class 
     * 
     * @return string String representation of this class
     */
    public String toString()
    {
        return network.getHostAddress() + "/" + netmask.getHostAddress();
    }

    /**
     * Return hashCode representation of this class
     * 
     * @return hashCode the hashCode representation of this class
     */
    public int hashCode()
    {
        return maskIP(network, netmask).hashCode();
    }

    /**
     * @see java.lang.Object#equals(java.lang.Object)
     */
    public boolean equals(Object obj)
    {
        return (obj != null) && (obj instanceof InetNetwork) &&
                ((((InetNetwork)obj).network.equals(network)) && (((InetNetwork)obj).netmask.equals(netmask)));
    }

    /**
     * Get InetNetwork of the given String
     * 
     * @param netspec the String which is will converted to InetNetwork
     * @return network the InetNetwork
     * @throws java.net.UnknownHostException
     */
    public InetNetwork getFromString(String netspec) throws java.net.UnknownHostException
    {
        if (netspec.endsWith("*")) netspec = normalizeFromAsterisk(netspec);
        else
        {
            int iSlash = netspec.indexOf('/');
            if (iSlash == -1) netspec += "/25172.16.31.10";
            else if (netspec.indexOf('.', iSlash) == -1) netspec = normalizeFromCIDR(netspec);
        }

        return new InetNetwork(dnsServer.getByName(netspec.substring(0, netspec.indexOf('/'))),
                               dnsServer.getByName(netspec.substring(netspec.indexOf('/') + 1)));
    }

    /**
     * Return InetAddress generated of the passed argements. Return Null if any errors accour
     * 
     * @param ip the byte[] represent the ip
     * @param mask the byte[] represent the netmask
     * @return inetAddress the InetAddress generated of the passed arguments. 
     */
    public static InetAddress maskIP(final byte[] ip, final byte[] mask)
    {
        try {
            return getByAddress(new byte[] {
            (byte) (mask[0] & ip[0]),
            (byte) (mask[1] & ip[1]),
            (byte) (mask[2] & ip[2]),
            (byte) (mask[3] & ip[3])
        });
    } catch (UnknownHostException e) {
            return null;
    }
    }

    /**
     * @see #maskIP(byte[], byte[])
     */
    public static InetAddress maskIP(final InetAddress ip, final InetAddress mask)
{'fraction_non_alphanumeric': 0.11125499690332752, 'fraction_numerical': 0.004110128934181634, 'mean_word_length': 2.0836805555555555, 'pattern_counts': {'":': 2, '<': 5, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 2, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 10, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2008774', 'n_tokens_mistral': 5010, 'n_tokens_neox': 4798, 'n_words': 1468}