#!/usr/bin/env php
<?php

$iptables = json_encode(getIptables());

if (is_dir("/run")) {
	$out = "/run/iptables.out";
} else {
	$out = "/tmp/iptables.out";
}

if (file_exists($out)) {
	unlink($out);
}

file_put_contents($out, $iptables);
chmod($out, 0777);

function getIptables() {
	// Parse iptables-save output
	exec('/sbin/iptables-save 2>&1', $ipv4, $ret);
	exec('/sbin/ip6tables-save 2>&1', $ipv6, $ret);
	$conf = array(
		"ipv4" => parseIptablesOutput($ipv4),
		"ipv6" => parseIptablesOutput($ipv6),
		"timestamp" => time(),
	);
	return $conf;
}

function parseIptablesOutput($iptsave) {
	$table = "unknown";

	$conf = array();

	foreach ($iptsave as $line) {
		if (empty($line)) {
			continue;
		}
		$firstchar = $line[0];

		if ($firstchar == "*") {
			// It's a new table.
			$table = substr($line, 1);
			continue;
		}

		if ($firstchar == ":") {
			// It's a chain definition
			list($chain, $stuff) = explode(" ", $line);
			$chain = substr($chain, 1);
			$conf[$table][$chain] = array();
			continue;
		}

		// Skip lines we don't care about..
		if ($firstchar != "-") { // Everything we care about now starts with -A
			continue;
		}
		$linearr = explode(" ", $line);
		array_shift($linearr);
		$chain = array_shift($linearr);
		$conf[$table][$chain][] = join(" ", $linearr);
	}

	// Make sure we have SOMETHING there.
	if (!isset($conf['filter'])) {
		$conf['filter'] = array("INPUT" => array());
	}

	return $conf;
}

