<?php

include_once('/a/www/centrala/global.php');
include_once('generators/global.php');

function GetTrafficStatus()
{
  //echo('.');
  $Hosts = array();
  $Hosts = GetTrafficStatusTable($Hosts, 'FORWARD');
  $Hosts = GetTrafficStatusTable($Hosts, 'INPUT');
  $Hosts = GetTrafficStatusTable($Hosts, 'OUTPUT');
  return($Hosts);
}

function GetTrafficStatusTable($Hosts, $Table)
{
  $Output = array();
  exec('/sbin/iptables -t mangle -L '.$Table.' -v -x -n', $Output);
  array_shift($Output);
  array_shift($Output);
  //$Row = $Output[0];
  foreach($Output as $Row)
  {
    //echo($Row."\n");
    //for($I=0;$I<strlen($Row);$I++) echo(ord($Row{$I}).',');
 
    $Row = ' '.$Row;
    while(strpos($Row, '  ') !== false) $Row = str_replace('  ', ' ', $Row);  // Remove long spaces
    //  echo("\n\n");  
    //for($I=0;$I<strlen($Row);$I++) echo(ord($Row{$I}).',');
    $Parts = explode(" ", $Row);
    $Bytes = $Parts[2];
    $Target = $Parts[3];
    $SourceInf = $Parts[6];
    $DestinationInf = $Parts[7];
    $Source = $Parts[8];
    $Destination = $Parts[9];
//    print_r($Parts);

    //echo($Source.' '.$Destination."\n");
    if(((($Target == 'MARK') or ($Target == 'game-server')) and (($Destination != '0.0.0.0/0') or ($Source != '0.0.0.0/0'))) or ($Target == 'IMQ'))
    {
      if($DestinationInf == '*') 
      {
        $Direction = 'down';
	$HostIp = $Destination;
      } else 
      {
        $Direction = 'up';
	$HostIp = $Source;
      }
      if(!array_key_exists($HostIp, $Hosts)) $Hosts[$HostIp] = array('up' => 0, 'down' => 0);
      $Hosts[$HostIp][$Direction] = $Hosts[$HostIp][$Direction] + $Bytes; 
    }
    
    // Network ports statistic
    $SubTable = 'game-server'; 
    if($Target == $SubTable) 
    {
      //$Hosts[$HostIp]['ports'] = array();
      $Output2 = array();
      exec('/sbin/iptables -t mangle -L '.$SubTable.' -v -x -n', $Output2);
      array_shift($Output2);
      array_shift($Output2);
      //$Row = $Output2[0];
      foreach($Output2 as $Row)
      {
        $Row = ' '.$Row;
        while(strpos($Row, '  ') !== false) $Row = str_replace('  ', ' ', $Row);  // Remove long spaces
	//echo($Row."\n");
        $Parts = explode(" ", $Row);
        $Bytes = $Parts[2];
        $Target = $Parts[3];
        $SourceInf = $Parts[6];
        $DestinationInf = $Parts[7];
        $Source = $Parts[8];
        $Destination = $Parts[9];
        $Parameter1 = $Parts[10];
        $Parameter2 = $Parts[11];
	if(($Parameter1 == 'tcp') or ($Parameter1 == 'udp'))
	{
	  $Parts2 = explode(':', $Parameter2);
	  $Port = $Parts2[1];
	  if($DestinationInf == '*') 
	    $Hosts[$HostIp]['ports'][$Port]['down'] = $Bytes;
	  else $Hosts[$HostIp]['ports'][$Port]['up'] = $Bytes;
	}
      }    
      //print_r($Hosts[$HostIp]['ports']);
    }
   }
   return($Hosts); 
}

function AssignHostName(&$Host)
{
  global $DbHosts;
  if(!array_key_exists('hostname', $Host)) 
  { 
    if(array_key_exists($Host['IP'], $DbHosts)) $Host['hostname'] = $DbHosts[$Host['IP']]; 
    else $Host['hostname'] = '';
  }
}

// Preload db host list from database
$DbHosts = array();
$DbResult = $Database->select('hosts','*');
while($Row = $DbResult->fetch_array()) 
{
  if(($Row['vpn'] == 1) and ($Row['external_ip'] == '')) $DbHosts[ToVpnIp($Row)] = $Row['name'];
  if($Row['external_ip'] != '') $DbHosts[$Row['external_ip']] = $Row['name'];
  $DbHosts[$Row['IP']] = $Row['name'];
  
}
$DbHosts['0.0.0.0/0'] = 'total';

$Period = 10;
$LastHosts = GetTrafficStatus();
$LastSaveTime = time();
while(1)
{
  Sleep($Period);
  $Hosts = GetTrafficStatus();
  $Database->query('TRUNCATE TABLE known_hosts_ports');
  foreach($Hosts as $Index => $Item) 
  {
    //echo($Index."\n");
    $Item['total_up'] = $Item['up'];
    $Item['total_down'] = $Item['down'];
    $Item['up'] = ($Item['up'] - $LastHosts[$Index]['up']) / $Period;
    $Item['down'] = ($Item['down'] - $LastHosts[$Index]['down']) / $Period;
    //AssignHostName($Hosts[$Index]);
//    if($Item['modified'])
    {
      //DB_Query('UPDATE known_hosts SET traffic_total_up = traffic_total_up + '.$Item['up'].', traffic_total_down = traffic_total_down + '.$Item['down'].', traffic_avg_up='.$Item['up'].', traffic_avg_down='.$Item['down'].', hostname="'.$DbHosts[$Index].'" WHERE IP="'.$Index.'"');
      $Database->replace('known_hosts', array('IP' => $Index, 'hostname' => $DbHosts[$Index], 'traffic_avg_up' => $Item['up'], 'traffic_avg_down' => $Item['down'],
        'traffic_total_up' => $Item['total_up'], 'traffic_total_down' => $Item['total_down']));
      if(array_key_exists('ports', $Item))
      foreach($Item['ports'] as $PortNumber => $Port)
      {
        $Port['total_up'] = $Port['up'];
        $Port['total_down'] = $Port['down'];
        $Port['up'] = ($Port['up'] - $LastHosts[$Index]['ports'][$PortNumber]['up']) / $Period;
        $Port['down'] = ($Port['down'] - $LastHosts[$Index]['ports'][$PortNumber]['down']) / $Period;
        $Database->replace('known_hosts_ports', array('host' => $Index, 'port' => $PortNumber, 'up' => $Port['up'], 
	  'down' => $Port['down'], 'total_down' => $Port['total_down'], 'total_up' => $Port['total_up']));
      }
    }
    //echo($Index.': '.$Item."\n");
  }
  //echod("\n");
  $LastHosts = $Hosts;
  $LastSaveTime = time();
}

?>
