#!/usr/local/bin/php -f
<?php

/*
 * cp_allow cpzone=.... ip=... username=... [mac=...] [attrs=...] ...
 * output on stdout: sessionid
 */

global $cpzone;

$ip = $username = $mac = $cpzone = null;
$attributes = Array();

array_shift($argv);
foreach ($argv as $arg) {
        list($name, $value) = explode('=', $arg, 2);
        switch($name) {
                case 'ip':
                        $ip=$value;
                        break;
                case 'username':
                        $username=$value;
                        break;
                case 'mac':
                        $mac=$value;
                        break;
                case 'nameid':
                        $nameid=$value;
                        break;
                case 'cpzone':
                        $cpzone=$value;
                        break;
                default:
                        $attributes[$name]=$value;
        }
}

// check IP format (ipv4 only)
if (! preg_match( '/^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:[.](?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$/', $ip)) { 
        exit(2);
}

if ( $mac == null ) {
        // search MAC in ARP cache
        require("util.inc");
        $mac=arp_get_mac_by_ip($ip);
}

// check MAC format
if (! preg_match( '/^([0-9A-F]{2}:){5}[0-9A-F]{2}$/i', $mac)) {
        exit(3);
}

// check if cpzone is defined
if ( $cpzone == null ) {
        exit(4);
}

require("captiveportal.inc");
@captiveportal_logportalauth( $username, $mac, $ip, "LOGIN", '(' . $nameid . ')' );
$pfsenseid = portal_allow( $ip, $mac, $username );
echo $pfsenseid;

?>
