/*
 *  PHEX - The pure-java Gnutella-servent.
 *  Copyright (C) 2001 - 2004 Gregor Koukkoullis ( phex <at> kouk <dot> de )
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
package phex.utils;

import java.util.*;

import phex.common.ServiceManager;
import phex.host.*;

public final class IPUtils
{
    private static ArrayList privateIPs;
    static
    {
        privateIPs = new ArrayList();
        privateIPs.add( "10.*.*.*" );
        privateIPs.add( "172.16.*.*" );
        privateIPs.add( "172.17.*.*" );
        privateIPs.add( "172.18.*.*" );
        privateIPs.add( "172.19.*.*" );
        privateIPs.add( "172.20.*.*" );
        privateIPs.add( "172.21.*.*" );
        privateIPs.add( "172.22.*.*" );
        privateIPs.add( "172.23.*.*" );
        privateIPs.add( "172.24.*.*" );
        privateIPs.add( "172.25.*.*" );
        privateIPs.add( "172.26.*.*" );
        privateIPs.add( "172.27.*.*" );
        privateIPs.add( "172.28.*.*" );
        privateIPs.add( "172.29.*.*" );
        privateIPs.add( "172.30.*.*" );
        privateIPs.add( "172.31.*.*" );
        privateIPs.add( "192.168.*.*" );
    }

    private IPUtils()
    {
    }

    public static boolean isInvalidIP( String ip )
    {
        byte[] ipArr = HostAddress.parseIP( ip );
        if ( ipArr == null )
        {
            return true;
        }
        return isInvalidIP( ipArr );
    }

    /**
     * Performance optimized method compared to isInvalidIP( String )
     */
    public static boolean isInvalidIP( byte[] ip )
    {
        // BearShare seems to use ip with 0.0.0.0
        if ( ip[0] == (byte)0 && ip[1] == (byte)0 && ip[2] == (byte)0 &&
             ip[3] == (byte)0 )
        {
            return true;
        }
        if ( ip[0] >= 224 && ip[0] <= 239 )
        {
            return true;
        }
        return false;
    }

    public static boolean isPrivateIP( String ip )
        throws MalformedHostAddressException
    {
        Iterator iterator = privateIPs.iterator();
        return isIPInIterator( ip, iterator );
    }

    /**
     * Search for the address, ip and port, in the invalid lists
     *
     * @param hostAddress is the address of the host, ip and port to be searched for
     * @return true if the host ip or host port was found in the invalid list
     */
    public static boolean isPortInUserInvalidList( HostAddress hostAddress )
    {
        boolean portFound ;

        //check if the port is in the invalid list
        String port = String.valueOf( hostAddress.getPort() );
        portFound = ServiceManager.sCfg.filteredCatcherPorts.contains( port );
        //if the port or the ip was found the host is in the invalid list
        if ( portFound )
        {
            return true;
        }

        return false;
    }

    private static boolean isIPInIterator( String ip, Iterator iterator )
        throws MalformedHostAddressException
    {
        String[] ipParts = splitIP2Parts( ip );
        while ( iterator.hasNext() )
        {
            Object obj = iterator.next();
            String[] compParts;
            if ( obj instanceof String[] )
            {
                compParts = (String[]) obj;
            }
            else
            {
                compParts = splitIP2Parts( (String) obj );
            }

            int i;
            for (i = 0; i < 4; i++ )
            {
                if (compParts[i].equals("*"))
                {
                    continue;
                }
                if (!compParts[i].equals(ipParts[i]))
                {
                    break;
                }
            }
            if ( i == 4 )
            {
                return true;
            }
        }
        return false;
    }

    public static String[] splitIP2Parts(String ip)
        throws MalformedHostAddressException
    {
        int	i = ip.indexOf(":");
        if (i != -1)
        {
            ip = ip.substring(0, i);
        }
        StringTokenizer	tokens = new StringTokenizer(ip, ".");
        String[] parts = new String[4];

        try
        {
            parts[0] = tokens.nextToken();
            parts[1] = tokens.nextToken();
            parts[2] = tokens.nextToken();
            parts[3] = tokens.nextToken();
        }
        catch ( NoSuchElementException exp )
        {// this is a invalid IP
            throw new MalformedHostAddressException( "Invalid IP: '" + ip + "'.");
        }

        return parts;
    }


    /**
     * Converts the given bytes of an IP to a string representation.
     */
    public static String ip2string(byte[] ip)
    {
        StringBuffer buffer = new StringBuffer( 15 );
        // TODO This is better then the stuff in IOUtil... change it accordingly...
        buffer.append( ((int)ip[0]) & 0xFF );
        buffer.append( '.' );
        buffer.append( ((int)ip[1]) & 0xFF );
        buffer.append( '.' );
        buffer.append( ((int)ip[2]) & 0xFF );
        buffer.append( '.' );
        buffer.append( ((int)ip[3]) & 0xFF );
        return buffer.toString();
    }
}