<?php

    /* Test:
    if (empty($_GET['check'])  ) {
    	#$_GET['check']='98.210.23.201';
    	#$_GET['check']='10.10.10.10';
    	$_GET['check']='178.187.1.1';
    }
    */

    $output = array();
    $output['errorNumber'] = 0;
    $output['errorType']   = false;
    $output['errorText']   = '';
    $output['isBlocked']   = false;


    $decIP = ip2dec( trim( $_GET['check'] ) );

    if ( false === $decIP ) {
        $output['errorNumber'] = 1;
		$output['errorText']   = "Keine IPv4-Addresse: " . $_GET['check'];
		$output['errorType']   = "FATAL";
		header( 'Status: 500' );
        echo json_encode( $output );
		exit;
    }

    if (! is_file( '/tmp/fwlist.txt' ) ) {
		$dummy = `/opt/fwlist > /tmp/fwlist.txt`;
    }

    $ips = file( '/tmp/fwlist.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
    foreach ( $ips as $ip ) {
	$ip = trim ( $ip );
        if ( $ip ) {
            if ( false === strpos( $ip, '/' ) ) {
                $firstIP = ip2dec( $ip );
                $lastIP  = $firstIP;
                $netMask = 32;
            } else {
                list($firstIP, $netMask ) = explode( '/', $ip );
                $firstIP = ip2dec( $firstIP );
                $lastIP  = $firstIP + pow( 2, 32 - $netMask );

            }

            if ( $decIP >= $firstIP && $decIP <= $lastIP ) {
                $output['isBlocked'] = true;
                break;
            }
        }
    }
    header( 'Content-Type: application/json' );
    echo json_encode( $output );
    exit;


function ip2dec( $ip ) {
    return sprintf( '%u', ip2long( $ip ) );
}