<?php

require_once("auth.inc");
require_once("util.inc");
require_once("functions.inc");
require_once("captiveportal.inc");

header("Expires: 0");
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Connection: close");

global $cpzone, $cpzoneid, $cpzoneprefix;

$cpzone = strtolower($_REQUEST['zone']);
$cpcfg = config_get_path("captiveportal/{$cpzone}", []);

if (empty($cpcfg)) {
	log_error("rfc8910.php - Submission to captiveportal with unknown parameter zone: " . htmlspecialchars($cpzone));
	portal_reply_page($redirurl, "error", gettext("Internal error"));
	ob_flush();
	return;
}

$cpzoneid = $cpcfg['zoneid'];
$clientip = $_SERVER['REMOTE_ADDR'];

if (is_array($cpcfg['allowedip'])) {
	foreach ($cpcfg['allowedip'] as $ipent) {
		if ($ipent['ip'] == $clientip) {
			if ($ipent['dir'] != 'to') {
				// 'clientip' is part of the 'allowedip' list
				ob_flush();
				return;
			}
		}
	}
}

$clientmac = pfSense_ip_to_mac($clientip);
if (!is_array($clientmac)) {
	if (!isset($cpcfg['nomacfilter']) || isset($cpcfg['passthrumacadd'])) {
		/* unable to find MAC address - shouldn't happen! - bail out */
		captiveportal_logportalauth("unauthenticated", "noclientmac", $clientip, "ERROR");
		echo "An error occurred.  Please check the system logs for more information.";
		log_error("Zone: {$cpzone} - Captive portal could not determine client's MAC address.  Disable MAC address filtering in captive portal if you do not need this functionality.");
		ob_flush();
		return;
	}
}
else if (is_array($cpcfg['passthrumac'])) {
	foreach ($cpcfg['passthrumac'] as $macent) {
		if ($macent['mac'] == $clientmac['macaddr']) {
			if ($macent['action'] == 'pass') {
				// 'clientmac' is part of the 'allowed MAC' list
				ob_flush();
				return;
			}
		}
	}
}

/* ---- RFC8910.php Custom Code for Kea DHCP, check MAC address instead of IP to verify a sesson ID exists
        Kea reclaims the IP quickly after the client disconnects, creating IP/MAC conflicts 
        when reallocated within the captive portal database of validated clients.  
        It is the MAC that it validated, not the IP as IP can change frequently
        This code matches the MAC in the database and assess if it is currently validated by the Portal
        so that The correct True/False string for DCHP 114 is sent.   
*/

//Check to see if that IP is associated with this device's MAC address in the captive portal database?
$ARPforIP = shell_exec("arp '$clientip'");
$clientmac = substr($ARPforIP, 17, 24);
if (preg_match('/([a-fA-F0-9]{2}[:|\-]?){6}/', "'{$clientmac}'", $matches)) {
    $clientmac = $matches[0];
}

/* read in client database and verify IP/MAC matches */
$query = "WHERE mac = '{$clientmac}'";
$cpdbmac = captiveportal_read_db($query);
foreach ($cpdbmac as $cpentrymac) {
              $cpsessionmac = $cpentrymac;
}

if (!empty($cpsessionmac)) {
  $sessionidmac = $cpsessionmac['sessionid'];
}      

/* ------- End Kea customized Code   */


$rfc8910_url = 'https://' . $_SERVER['HTTP_HOST'] . '/index.php?zone=' . $cpzone;

if (empty($sessionidmac)) {
/*	captiveportal_logportalauth("rfc8910", "EMPTY SESSION", $clientip, $cpzone); */
/*	$seconds_remaining = $cpcfg['timeout'] * 60; */
	$json_post  = array (
		"captive" => true,
		"user-portal-url" => "$rfc8910_url",
		"venue-info-url" => "$rfc8910_url"
);

echo json_encode($json_post, JSON_PRETTY_PRINT);

} else {
/*	captiveportal_logportalauth("rfc8910", "EXISTING SESSION", $clientip, $cpzone); */
/*	$seconds_remaining = (time()-$cpsession['allow_time'])+($cpcfg['timeout']*60); */
	$json_post  = array (
		"captive" => false,
		"user-portal-url" => "$rfc8910_url",
		"venue-info-url" => "$rfc8910_url"
);
echo json_encode($json_post, JSON_PRETTY_PRINT);

}
ob_flush();

return;
?>