Ignore:
Timestamp:
Jan 8, 2016, 11:00:11 PM (9 years ago)
Author:
chronos
Message:
  • Modified: Network configure actions now can be executed through cmd.php interface using "php cmd.php config <action>".
Location:
trunk/Modules/NetworkConfigRouterOS
Files:
10 edited

Legend:

Unmodified
Added
Removed
  • trunk/Modules/NetworkConfigRouterOS/Generators/DHCP.php

    r738 r781  
    11<?php
    22
    3 if(isset($_SERVER['REMOTE_ADDR'])) die();
    4 include_once(dirname(__FILE__).'/../../../Application/System.php');
    5 $System = new System();
    6 $System->ShowPage = false;
    7 $System->Run();
    8 $Path = array('ip', 'dhcp-server', 'lease');
    93
    10 $Routerboard = new Routerboard();
    11 $Routerboard->UserName = $Config['MainRouter']['UserName'];
    12 $Routerboard->Timeout = $Config['MainRouter']['ConnectTimeout'];
    13 $Routerboard->Debug = true;
     4class ConfigRouterOSDHCP extends NetworkConfigItem
     5{
     6  function Run()
     7  {
     8    $Path = array('ip', 'dhcp-server', 'lease');
    149
    15 $DbResult = $System->Database->query('SELECT * FROM `NetworkSubnet` WHERE `Configure`=1');
    16 while($Subnet = $DbResult->fetch_assoc())
    17 {
    18   echo($Subnet['DHCP']);
    19   $Routerboard->HostName = $Subnet['DHCP'];
    20   $Items = array();
    21   $Server = 'dhcp'.$Subnet['Id'];
    22   $DbResult2 = $System->Database->query('SELECT NetworkInterface.*, NetworkDevice.Name AS DeviceName FROM `NetworkInterface` '.
    23     ' LEFT JOIN NetworkDevice ON NetworkDevice.Id = NetworkInterface.Device WHERE '.
    24     ' CompareNetworkPrefix(INET_ATON(LocalIP), INET_ATON("'.$Subnet['AddressRange'].'"), '.$Subnet['Mask'].') AND (`MAC` != "00:00:00:00:00:00") ORDER BY `LocalIP`');
    25   while($Interface = $DbResult2->fetch_assoc())
    26   {
    27     $Name = $Interface['DeviceName'];
    28     if($Interface['Name'] != '') $Name .= '-'.$Interface['Name'];
    29     $Items[] = array('mac-address' => $Interface['MAC'], 'address' => $Interface['LocalIP'], 'server' => $Server, 'comment' => $Name);
     10    $Routerboard = new Routerboard();
     11    $Routerboard->UserName = $this->System->Config['MainRouter']['UserName'];
     12    $Routerboard->Timeout = $this->System->Config['MainRouter']['ConnectTimeout'];
     13    $Routerboard->Debug = true;
     14
     15    $DbResult = $this->Database->query('SELECT * FROM `NetworkSubnet` WHERE `Configure`=1');
     16    while($Subnet = $DbResult->fetch_assoc())
     17    {
     18      echo($Subnet['DHCP']);
     19      $Routerboard->HostName = $Subnet['DHCP'];
     20      $Items = array();
     21      $Server = 'dhcp'.$Subnet['Id'];
     22      $DbResult2 = $this->Database->query('SELECT NetworkInterface.*, NetworkDevice.Name AS DeviceName FROM `NetworkInterface` '.
     23          ' LEFT JOIN NetworkDevice ON NetworkDevice.Id = NetworkInterface.Device WHERE '.
     24          ' CompareNetworkPrefix(INET_ATON(LocalIP), INET_ATON("'.$Subnet['AddressRange'].'"), '.$Subnet['Mask'].') AND (`MAC` != "00:00:00:00:00:00") ORDER BY `LocalIP`');
     25      while($Interface = $DbResult2->fetch_assoc())
     26      {
     27        $Name = $Interface['DeviceName'];
     28        if($Interface['Name'] != '') $Name .= '-'.$Interface['Name'];
     29        $Items[] = array('mac-address' => $Interface['MAC'], 'address' => $Interface['LocalIP'], 'server' => $Server, 'comment' => $Name);
     30      }
     31
     32      print_r($Routerboard->ListUpdate($Path, array('mac-address', 'address', 'server', 'comment'), $Items, array('server' => $Server, 'dynamic' => 'no')));
     33      echo("\n");
     34    }
    3035  }
     36}
    3137
    32   print_r($Routerboard->ListUpdate($Path, array('mac-address', 'address', 'server', 'comment'), $Items, array('server' => $Server, 'dynamic' => 'no')));
    33   echo("\n");
    34 }
  • trunk/Modules/NetworkConfigRouterOS/Generators/DNS.php

    r777 r781  
    11<?php
    22
    3 if(isset($_SERVER['REMOTE_ADDR'])) die();
    4 include_once(dirname(__FILE__).'/../../../Application/System.php');
    5 $System = new System();
    6 $System->ShowPage = false;
    7 $System->Run();
    8 $Path = array('ip', 'dns', 'static');
     3class ConfigRouterOSDNS extends NetworkConfigItem
     4{
     5  function Run()
     6  {
     7    $Path = array('ip', 'dns', 'static');
    98
    10 $Routerboard = new Routerboard($Config['MainRouter']['HostName']);
    11 $Routerboard->UserName = $Config['MainRouter']['UserName'];
    12 $Routerboard->Timeout = $Config['MainRouter']['ConnectTimeout'];
    13 $Routerboard->Debug = true;
     9    $Routerboard = new Routerboard($this->System->Config['MainRouter']['HostName']);
     10    $Routerboard->UserName = $this->System->Config['MainRouter']['UserName'];
     11    $Routerboard->Timeout = $this->System->Config['MainRouter']['ConnectTimeout'];
     12    $Routerboard->Debug = true;
    1413
    15 $DbResult = $System->Database->query('SELECT * FROM `NetworkDomain`');
    16 while($Domain = $DbResult->fetch_assoc())
    17 {
    18   $DomainName = $Domain['Name'];
     14    $DbResult = $this->Database->query('SELECT * FROM `NetworkDomain`');
     15    while($Domain = $DbResult->fetch_assoc())
     16    {
     17      $DomainName = $Domain['Name'];
    1918
    20   // Get full domain name from parent items
    21   $CurrentDomain = $Domain;
    22   while($CurrentDomain['Parent'] > 0)
    23   {
    24     $DbResult2 = $System->Database->query('SELECT * FROM `NetworkDomain` WHERE `Id`='.$CurrentDomain['Parent']);
    25     $CurrentDomain = $DbResult2->fetch_assoc();
    26     $DomainName .= '.'.$CurrentDomain['Name'];
    27   }
     19      // Get full domain name from parent items
     20      $CurrentDomain = $Domain;
     21      while($CurrentDomain['Parent'] > 0)
     22      {
     23        $DbResult2 = $this->Database->query('SELECT * FROM `NetworkDomain` WHERE `Id`='.$CurrentDomain['Parent']);
     24        $CurrentDomain = $DbResult2->fetch_assoc();
     25        $DomainName .= '.'.$CurrentDomain['Name'];
     26      }
    2827
    29   $Items = array();
     28      $Items = array();
    3029
    31   // Devices, Interfaces
    32   $DbResult2 = $System->Database->query('SELECT `NetworkInterface`.*, `NetworkDevice`.`Name` AS `DeviceName` FROM `NetworkInterface` '.
    33     'JOIN `NetworkDevice` ON `NetworkInterface`.`Device`=`NetworkDevice`.`Id` '.
    34     'WHERE (`NetworkDevice`.`Used`=1)');
    35   while($Interface = $DbResult2->fetch_assoc())
    36   {
    37     $Name = $Interface['DeviceName'];
    38     if($Interface['Name'] != '') $Name .= '-'.$Interface['Name'];
    39     $NameFull = $Name.'.'.$DomainName;
    40     $NameExtFull = $Name.'-ext.'.$DomainName;
    41     if($Interface['LocalIP'] != '')
    42       $Items[] = array('name' => $NameFull, 'address' => $Interface['LocalIP']);
    43     if($Interface['IPv6'] != '')
    44       $Items[] = array('name' => $NameFull, 'address' => $Interface['IPv6']);
    45     if($Interface['ExternalIP'] != '')
    46       $Items[] = array('name' => $NameExtFull, 'address' => $Interface['ExternalIP']);
    47   }
     30      // Devices, Interfaces
     31      $DbResult2 = $this->Database->query('SELECT `NetworkInterface`.*, `NetworkDevice`.`Name` AS `DeviceName` FROM `NetworkInterface` '.
     32          'JOIN `NetworkDevice` ON `NetworkInterface`.`Device`=`NetworkDevice`.`Id` '.
     33          'WHERE (`NetworkDevice`.`Used`=1)');
     34      while($Interface = $DbResult2->fetch_assoc())
     35      {
     36        $Name = $Interface['DeviceName'];
     37        if($Interface['Name'] != '') $Name .= '-'.$Interface['Name'];
     38        $NameFull = $Name.'.'.$DomainName;
     39        $NameExtFull = $Name.'-ext.'.$DomainName;
     40        if($Interface['LocalIP'] != '')
     41          $Items[] = array('name' => $NameFull, 'address' => $Interface['LocalIP']);
     42        if($Interface['IPv6'] != '')
     43          $Items[] = array('name' => $NameFull, 'address' => $Interface['IPv6']);
     44        if($Interface['ExternalIP'] != '')
     45          $Items[] = array('name' => $NameExtFull, 'address' => $Interface['ExternalIP']);
     46      }
    4847
    49   // Domain aliases
    50   $DbResult2 = $System->Database->query('SELECT `NetworkDomainAlias`.*, `NetworkInterface`.`LocalIP` AS `LocalIP`, '.
    51     '`NetworkInterface`.`IPv6` AS `IPv6`, `NetworkInterface`.`ExternalIP` AS `ExternalIP` FROM `NetworkDomainAlias` '.
    52     'JOIN `NetworkDevice` ON SUBSTR(`NetworkDomainAlias`.`Target`, 1, LENGTH(`NetworkDevice`.`Name` ))=`NetworkDevice`.`Name` '.
    53     'JOIN `NetworkInterface` ON `NetworkInterface`.`Device`=`NetworkDevice`.`Id` '.
    54     'WHERE (`NetworkDevice`.`Used`=1) AND '.
    55     '(CONCAT_WS("-", `NetworkDevice`.`Name`, NULLIF(`NetworkInterface`.`Name`, "")) = `NetworkDomainAlias`.`Target`)');
    56   while($Alias = $DbResult2->fetch_assoc())
    57   {
    58     $Name = $Alias['Name'];
    59     $NameFull = $Name.'.'.$DomainName;
    60     $NameExtFull = $Name.'-ext.'.$DomainName;
    61     if($Alias['LocalIP'] != '')
    62       $Items[] = array('name' => $NameFull, 'address' => $Alias['LocalIP']);
    63     if($Alias['IPv6'] != '')
    64       $Items[] = array('name' => $NameFull, 'address' => $Alias['IPv6']);
    65     if($Alias['ExternalIP'] != '')
    66       $Items[] = array('name' => $NameExtFull, 'address' => $Alias['ExternalIP']);
    67   }
     48      // Domain aliases
     49      $DbResult2 = $this->Database->query('SELECT `NetworkDomainAlias`.*, `NetworkInterface`.`LocalIP` AS `LocalIP`, '.
     50          '`NetworkInterface`.`IPv6` AS `IPv6`, `NetworkInterface`.`ExternalIP` AS `ExternalIP` FROM `NetworkDomainAlias` '.
     51          'JOIN `NetworkDevice` ON SUBSTR(`NetworkDomainAlias`.`Target`, 1, LENGTH(`NetworkDevice`.`Name` ))=`NetworkDevice`.`Name` '.
     52          'JOIN `NetworkInterface` ON `NetworkInterface`.`Device`=`NetworkDevice`.`Id` '.
     53          'WHERE (`NetworkDevice`.`Used`=1) AND '.
     54          '(CONCAT_WS("-", `NetworkDevice`.`Name`, NULLIF(`NetworkInterface`.`Name`, "")) = `NetworkDomainAlias`.`Target`)');
     55      while($Alias = $DbResult2->fetch_assoc())
     56      {
     57        $Name = $Alias['Name'];
     58        $NameFull = $Name.'.'.$DomainName;
     59        $NameExtFull = $Name.'-ext.'.$DomainName;
     60        if($Alias['LocalIP'] != '')
     61          $Items[] = array('name' => $NameFull, 'address' => $Alias['LocalIP']);
     62        if($Alias['IPv6'] != '')
     63          $Items[] = array('name' => $NameFull, 'address' => $Alias['IPv6']);
     64        if($Alias['ExternalIP'] != '')
     65          $Items[] = array('name' => $NameExtFull, 'address' => $Alias['ExternalIP']);
     66      }
    6867
    69   $DbResult2 = $System->Database->query('SELECT * FROM `NetworkDomainServer` WHERE `Domain`='.$Domain['Id']);
    70   while($Server = $DbResult2->fetch_assoc())
    71   {
    72     $Routerboard->HostName = $Server['Address'];
    73     $Routerboard->ListUpdate($Path, array('name', 'address'), $Items);
     68      $DbResult2 = $this->Database->query('SELECT * FROM `NetworkDomainServer` WHERE `Domain`='.$Domain['Id']);
     69      while($Server = $DbResult2->fetch_assoc())
     70      {
     71        $Routerboard->HostName = $Server['Address'];
     72        $Routerboard->ListUpdate($Path, array('name', 'address'), $Items);
     73      }
     74    }
    7475  }
    7576}
  • trunk/Modules/NetworkConfigRouterOS/Generators/FirewallFilter.php

    r738 r781  
    11<?php
    22
    3 if(isset($_SERVER['REMOTE_ADDR'])) die();
    4 include_once(dirname(__FILE__).'/../../../Application/System.php');
    5 $System = new System();
    6 $System->ShowPage = false;
    7 $System->Run();
    8 $Path = array('ip', 'firewall', 'filter');
     3class ConfigRouterOSFirewallFilter extends NetworkConfigItem
     4{
     5  function Run()
     6  {
     7    $Path = array('ip', 'firewall', 'filter');
    98
    10 $Routerboard = new Routerboard($Config['MainRouter']['HostName']);
    11 $Routerboard->UserName = $Config['MainRouter']['UserName'];
    12 $Routerboard->Timeout = $Config['MainRouter']['ConnectTimeout'];
    13 $Routerboard->Debug = true;
     9    $Routerboard = new Routerboard($this->SystemConfig['MainRouter']['HostName']);
     10    $Routerboard->UserName = $this->SystemConfig['MainRouter']['UserName'];
     11    $Routerboard->Timeout = $this->SystemConfig['MainRouter']['ConnectTimeout'];
     12    $Routerboard->Debug = true;
    1413
    15 $InetInterface = $Config['MainRouter']['InetInterface'];
    16 $LocalInterface = $Config['MainRouter']['LocalInterface'];
     14    $InetInterface = $this->SystemConfig['MainRouter']['InetInterface'];
     15    $LocalInterface = $this->SystemConfig['MainRouter']['LocalInterface'];
    1716
    18 $Items = array();
     17    $Items = array();
    1918
    2019
    21 // Total inet traffic measuring
    22 $Items[] = array('chain' => 'forward', 'out-interface' => $InetInterface, 'action' => 'passthrough', 'comment' => 'total-out');
    23 $Items[] = array('chain' => 'forward', 'in-interface' => $InetInterface, 'action' => 'passthrough', 'comment' => 'total-in');
     20    // Total inet traffic measuring
     21    $Items[] = array('chain' => 'forward', 'out-interface' => $InetInterface, 'action' => 'passthrough', 'comment' => 'total-out');
     22    $Items[] = array('chain' => 'forward', 'in-interface' => $InetInterface, 'action' => 'passthrough', 'comment' => 'total-in');
    2423
    25 // Inet traffic groups
    26 //$Items[] = array('chain' => 'forward', 'out-interface' => $InetInterface, 'action' => 'jump', 'jump-target' => 'inet-out', 'comment' => 'inet-out');
    27 //$Items[] = array('chain' => 'forward', 'in-interface' => $InetInterface, 'action' => 'jump', 'jump-target' => 'inet-in', 'comment' => 'inet-in');
     24    // Inet traffic groups
     25    //$Items[] = array('chain' => 'forward', 'out-interface' => $InetInterface, 'action' => 'jump', 'jump-target' => 'inet-out', 'comment' => 'inet-out');
     26    //$Items[] = array('chain' => 'forward', 'in-interface' => $InetInterface, 'action' => 'jump', 'jump-target' => 'inet-in', 'comment' => 'inet-in');
    2827
    29 // Input to router
    30 $Items[] = array('chain' => 'input', 'in-interface' => $InetInterface, 'protocol' => 'icmp', 'action' => 'accept', 'comment' => 'local-ping');
    31 $Items[] = array('chain' => 'input', 'in-interface' => $InetInterface, 'src-address' => '216.66.80.30', 'action' => 'accept', 'comment' => 'ipv6-tunnel');
    32 $Items[] = array('chain' => 'input', 'in-interface' => $InetInterface, 'action' => 'drop', 'comment' => 'drop-rest-input');
     28    // Input to router
     29    $Items[] = array('chain' => 'input', 'in-interface' => $InetInterface, 'protocol' => 'icmp', 'action' => 'accept', 'comment' => 'local-ping');
     30    $Items[] = array('chain' => 'input', 'in-interface' => $InetInterface, 'src-address' => '216.66.80.30', 'action' => 'accept', 'comment' => 'ipv6-tunnel');
     31    $Items[] = array('chain' => 'input', 'in-interface' => $InetInterface, 'action' => 'drop', 'comment' => 'drop-rest-input');
    3332
    34 // Allowed SMTP servers
    35 $Items[] = array('chain' => 'forward', 'out-interface' => $InetInterface, 'protocol' => 'tcp', 'dst-port' => 25, 'src-address' => '10.145.64.8', 'action' => 'accept', 'comment' => 'smtp.zdechov.net');
    36 $Items[] = array('chain' => 'forward', 'out-interface' => $InetInterface, 'protocol' => 'tcp', 'dst-port' => 25, 'dst-address' => '212.111.0.12', 'action' => 'accept', 'comment' => 'smtp.inext.cz');
    37 $Items[] = array('chain' => 'forward', 'out-interface' => $InetInterface, 'protocol' => 'tcp', 'dst-port' => 25, 'dst-address' => '93.89.98.3', 'action' => 'accept', 'comment' => 'smtp.sychrovnet.cz');
    38 $Items[] = array('chain' => 'forward', 'out-interface' => $InetInterface, 'protocol' => 'tcp', 'dst-port' => 25, 'dst-address' => '77.75.72.43', 'action' => 'accept', 'comment' => 'smtp.seznam.cz');
    39 $Items[] = array('chain' => 'forward', 'out-interface' => $InetInterface, 'protocol' => 'tcp', 'dst-port' => 25, 'dst-address' => '82.119.226.113', 'action' => 'accept', 'comment' => 'smtp.svarko.cz');
    40 $Items[] = array('chain' => 'forward', 'out-interface' => $InetInterface, 'protocol' => 'tcp', 'dst-port' => 25, 'action' => 'drop', 'comment' => 'drop-rest-smtp');
     33    // Allowed SMTP servers
     34    $Items[] = array('chain' => 'forward', 'out-interface' => $InetInterface, 'protocol' => 'tcp', 'dst-port' => 25, 'src-address' => '10.145.64.8', 'action' => 'accept', 'comment' => 'smtp.zdechov.net');
     35    $Items[] = array('chain' => 'forward', 'out-interface' => $InetInterface, 'protocol' => 'tcp', 'dst-port' => 25, 'dst-address' => '212.111.0.12', 'action' => 'accept', 'comment' => 'smtp.inext.cz');
     36    $Items[] = array('chain' => 'forward', 'out-interface' => $InetInterface, 'protocol' => 'tcp', 'dst-port' => 25, 'dst-address' => '93.89.98.3', 'action' => 'accept', 'comment' => 'smtp.sychrovnet.cz');
     37    $Items[] = array('chain' => 'forward', 'out-interface' => $InetInterface, 'protocol' => 'tcp', 'dst-port' => 25, 'dst-address' => '77.75.72.43', 'action' => 'accept', 'comment' => 'smtp.seznam.cz');
     38    $Items[] = array('chain' => 'forward', 'out-interface' => $InetInterface, 'protocol' => 'tcp', 'dst-port' => 25, 'dst-address' => '82.119.226.113', 'action' => 'accept', 'comment' => 'smtp.svarko.cz');
     39    $Items[] = array('chain' => 'forward', 'out-interface' => $InetInterface, 'protocol' => 'tcp', 'dst-port' => 25, 'action' => 'drop', 'comment' => 'drop-rest-smtp');
    4140
    4241
    4342
    4443
    45 // Insert blocked addresses
    46 $DbResult = $System->Database->query('SELECT Member.*, Subject.Name FROM Member JOIN Subject ON Member.Subject = Subject.Id WHERE Member.Blocked=1');
    47 while($Member = $DbResult->fetch_assoc())
    48 {
    49   echo($Member['Name'].': ');
    50   // Hosts
    51   $DbResult2 = $System->Database->query('SELECT NetworkInterface.*, NetworkDevice.Name AS DeviceName FROM NetworkInterface LEFT JOIN NetworkDevice ON NetworkDevice.Id = NetworkInterface.Device WHERE (NetworkInterface.ExternalIP <> "") AND (NetworkDevice.Member = '.$Member['Id'].') AND (NetworkInterface.LocalIP != NetworkInterface.ExternalIP) ORDER BY id DESC');
    52   while($Interface = $DbResult2->fetch_assoc())
    53   {
    54     $Name = $Interface['DeviceName'];
    55     if($Interface['Name'] != '') $Name .= '-'.$Interface['Name'];
    56     $Name = RouterOSIdent($Name);
    57     echo($Name.'('.$Interface['LocalIP'].'), ');
    58     $Items[] = array('chain' => 'forward', 'out-interface' => $InetInterface, 'src-address' => $Interface['LocalIP'], 'action' => 'drop', 'comment' => $Name.'-out-drop');
    59     $Items[] = array('chain' => 'forward', 'in-interface' => $InetInterface, 'dst-address' => $Interface['LocalIP'], 'action' => 'drop', 'comment' => $Name.'-in-drop');
     44    // Insert blocked addresses
     45    $DbResult = $this->Database->query('SELECT Member.*, Subject.Name FROM Member JOIN Subject ON Member.Subject = Subject.Id WHERE Member.Blocked=1');
     46    while($Member = $DbResult->fetch_assoc())
     47    {
     48      echo($Member['Name'].': ');
     49      // Hosts
     50      $DbResult2 = $this->Database->query('SELECT NetworkInterface.*, NetworkDevice.Name AS DeviceName FROM NetworkInterface LEFT JOIN NetworkDevice ON NetworkDevice.Id = NetworkInterface.Device WHERE (NetworkInterface.ExternalIP <> "") AND (NetworkDevice.Member = '.$Member['Id'].') AND (NetworkInterface.LocalIP != NetworkInterface.ExternalIP) ORDER BY id DESC');
     51      while($Interface = $DbResult2->fetch_assoc())
     52      {
     53        $Name = $Interface['DeviceName'];
     54        if($Interface['Name'] != '') $Name .= '-'.$Interface['Name'];
     55        $Name = RouterOSIdent($Name);
     56        echo($Name.'('.$Interface['LocalIP'].'), ');
     57        $Items[] = array('chain' => 'forward', 'out-interface' => $InetInterface, 'src-address' => $Interface['LocalIP'], 'action' => 'drop', 'comment' => $Name.'-out-drop');
     58        $Items[] = array('chain' => 'forward', 'in-interface' => $InetInterface, 'dst-address' => $Interface['LocalIP'], 'action' => 'drop', 'comment' => $Name.'-in-drop');
     59      }
     60
     61      // Subnets
     62      $DbResult2 = $this->Database->select('NetworkSubnet', '*', 'Member='.$Member['Id']);
     63      while($Subnet = $DbResult2->fetch_assoc())
     64      {
     65        $Subnet['Name'] = RouterOSIdent('subnet-'.$Subnet['Name']);
     66        echo($Subnet['Name'].'('.$Subnet['AddressRange'].'/'.$Subnet['Mask'].'), ');
     67        $NewAddress = new NetworkAddressIPv4();
     68        $NewAddress->AddressFromString($Subnet['ExtAddressRange']);
     69        $NewAddress->Prefix = $Subnet['ExtMask'];
     70        $Range = $NewAddress->GetRange();
     71        if($Subnet['ExtMask'] != 32) $Range = $Range['From']->AddressToString().'-'.$Range['To']->AddressToString();
     72        else $Range = $Range['From']->AddressToString();
     73        if($Subnet['Mask'] == 32) $Src = $Subnet['AddressRange'];
     74        else $Src = $Subnet['AddressRange'].'/'.$Subnet['Mask'];
     75        $Items[] = array('chain' => 'forward', 'out-interface' => $InetInterface, 'src-address' => $Src, 'action' => 'drop','comment' => $Subnet['Name'].'-out-drop');
     76
     77        $NewAddress = new NetworkAddressIPv4();
     78        $NewAddress->AddressFromString($Subnet['AddressRange']);
     79        $NewAddress->Prefix = $Subnet['Mask'];
     80        $Range = $NewAddress->GetRange();
     81        if($Subnet['Mask'] != 32) $Range = $Range['From']->AddressToString().'-'.$Range['To']->AddressToString();
     82        else $Range = $Range['From']->AddressToString();
     83        if($Subnet['ExtMask'] == 32) $Dest = $Subnet['ExtAddressRange'];
     84        else $Dest = $Subnet['ExtAddressRange'].'/'.$Subnet['ExtMask'];
     85        $Items[] = array('chain' => 'forward', 'in-interface' => $InetInterface, 'dst-address' => $Dest, 'action' => 'drop', 'comment' => $Subnet['Name'].'-in-drop');
     86      }
     87      echo("\n");
     88    }
     89
     90    //print_r($Items);
     91    $Routerboard->ListUpdate($Path, array('chain', 'dst-address', 'in-interface', 'src-address', 'out-interface', 'dst-port', 'protocol', 'action', 'comment', 'jump-target', 'src-port'), $Items);
     92
    6093  }
    61 
    62   // Subnets
    63   $DbResult2 = $System->Database->select('NetworkSubnet', '*', 'Member='.$Member['Id']);
    64   while($Subnet = $DbResult2->fetch_assoc())
    65   {
    66     $Subnet['Name'] = RouterOSIdent('subnet-'.$Subnet['Name']);
    67     echo($Subnet['Name'].'('.$Subnet['AddressRange'].'/'.$Subnet['Mask'].'), ');
    68       $NewAddress = new NetworkAddressIPv4();
    69       $NewAddress->AddressFromString($Subnet['ExtAddressRange']);
    70       $NewAddress->Prefix = $Subnet['ExtMask'];
    71       $Range = $NewAddress->GetRange();
    72       if($Subnet['ExtMask'] != 32) $Range = $Range['From']->AddressToString().'-'.$Range['To']->AddressToString();
    73         else $Range = $Range['From']->AddressToString();
    74       if($Subnet['Mask'] == 32) $Src = $Subnet['AddressRange'];
    75         else $Src = $Subnet['AddressRange'].'/'.$Subnet['Mask'];
    76       $Items[] = array('chain' => 'forward', 'out-interface' => $InetInterface, 'src-address' => $Src, 'action' => 'drop','comment' => $Subnet['Name'].'-out-drop');
    77 
    78       $NewAddress = new NetworkAddressIPv4();
    79       $NewAddress->AddressFromString($Subnet['AddressRange']);
    80       $NewAddress->Prefix = $Subnet['Mask'];
    81       $Range = $NewAddress->GetRange();
    82       if($Subnet['Mask'] != 32) $Range = $Range['From']->AddressToString().'-'.$Range['To']->AddressToString();
    83         else $Range = $Range['From']->AddressToString();
    84       if($Subnet['ExtMask'] == 32) $Dest = $Subnet['ExtAddressRange'];
    85         else $Dest = $Subnet['ExtAddressRange'].'/'.$Subnet['ExtMask'];
    86       $Items[] = array('chain' => 'forward', 'in-interface' => $InetInterface, 'dst-address' => $Dest, 'action' => 'drop', 'comment' => $Subnet['Name'].'-in-drop');
    87   }
    88   echo("\n");
    8994}
    90 
    91 //print_r($Items);
    92 $Routerboard->ListUpdate($Path, array('chain', 'dst-address', 'in-interface', 'src-address', 'out-interface', 'dst-port', 'protocol', 'action', 'comment', 'jump-target', 'src-port'), $Items);
  • trunk/Modules/NetworkConfigRouterOS/Generators/FirewallMangle.php

    r766 r781  
    11<?php
    2 if(isset($_SERVER['REMOTE_ADDR'])) die();
    32
    4 $Enabled = 1;
    5 $ClassesEnabled = 1;
    6 $SessionDisable = true;
    7 include_once(dirname(__FILE__).'/../../../Application/System.php');
    8 $System = new System();
    9 $System->ShowPage = false;
    10 $System->Run();
    11 $PathFirewall = array('ip', 'firewall', 'mangle');
     3class ConfigRouterOSFirewallMangle extends NetworkConfigItem
     4{
     5  function Run()
     6  {
     7    $PathFirewall = array('ip', 'firewall', 'mangle');
    128
    13 $Routerboard = new Routerboard();
    14 $Routerboard->UserName = $Config['MainRouter']['UserName'];
    15 $Routerboard->Timeout = $Config['MainRouter']['ConnectTimeout'];
    16 $Routerboard->HostName = $Config['MainRouter']['HostName'];
    17 $Routerboard->Debug = true;
     9    $Routerboard = new Routerboard();
     10    $Routerboard->UserName = $this->System->Config['MainRouter']['UserName'];
     11    $Routerboard->Timeout = $this->System->Config['MainRouter']['ConnectTimeout'];
     12    $Routerboard->HostName = $this->System->Config['MainRouter']['HostName'];
     13    $Routerboard->Debug = true;
    1814
    19 $InetInterface = $Config['MainRouter']['InetInterface'];
     15    $InetInterface = $Config['MainRouter']['InetInterface'];
    2016
    2117
    22 // Generate address tree
    23 $AddressTree = array('Address' => new NetworkAddressIPv4(), 'Name' => 'main', 'Items' => array(), 'ForceMark' => false);
     18    // Generate address tree
     19    $AddressTree = array('Address' => new NetworkAddressIPv4(), 'Name' => 'main', 'Items' => array(), 'ForceMark' => false);
    2420
    25 // Divide rules by subnet number
    26 $DbResult = $System->Database->query('SELECT `Id`, `Name`, `AddressRange`, `Mask` FROM `NetworkSubnet` WHERE `Member` IS NULL');
    27 while($Subnet = $DbResult->fetch_assoc())
    28 {
    29   $NewAddress = new NetworkAddressIPv4();
    30   $NewAddress->AddressFromString($Subnet['AddressRange']);
    31   $NewAddress->Prefix = $Subnet['Mask'];
    32   InsertToAddressTree($AddressTree, $NewAddress, 'subnet-'.RouterOSIdent($Subnet['Name']));
    33 }
     21    // Divide rules by subnet number
     22    $DbResult = $this->System->Database->query('SELECT `Id`, `Name`, `AddressRange`, `Mask` FROM `NetworkSubnet` WHERE `Member` IS NULL');
     23    while($Subnet = $DbResult->fetch_assoc())
     24    {
     25      $NewAddress = new NetworkAddressIPv4();
     26      $NewAddress->AddressFromString($Subnet['AddressRange']);
     27      $NewAddress->Prefix = $Subnet['Mask'];
     28      InsertToAddressTree($AddressTree, $NewAddress, 'subnet-'.RouterOSIdent($Subnet['Name']));
     29    }
    3430
    35 // Process users
    36 $DbResult = $System->Database->query('SELECT `Member`.*, `Subject`.`Name` FROM `Member` '.
    37   'LEFT JOIN `Subject` ON `Subject`.`Id` = `Member`.`Subject` '.
    38   'WHERE `Member`.`Blocked` = 0');
    39 while($Member = $DbResult->fetch_assoc())
    40 {
    41   $Member['Name'] = RouterOSIdent($Member['Name'].'-'.$Member['Id'] );
    42   echo('Uživatel '.$Member['Name'].': ');
     31    // Process users
     32    $DbResult = $this->System->Database->query('SELECT `Member`.*, `Subject`.`Name` FROM `Member` '.
     33        'LEFT JOIN `Subject` ON `Subject`.`Id` = `Member`.`Subject` '.
     34        'WHERE `Member`.`Blocked` = 0');
     35    while($Member = $DbResult->fetch_assoc())
     36    {
     37      $Member['Name'] = RouterOSIdent($Member['Name'].'-'.$Member['Id'] );
     38      echo('Uživatel '.$Member['Name'].': ');
    4339
    44   $DbResult2 = $System->Database->select('NetworkDevice', '*', '`Used` = 1 AND `Member` = '.$Member['Id']);
    45   while($Device = $DbResult2->fetch_assoc())
    46   {
    47     $DbResult3 = $System->Database->select('NetworkInterface', '*', '`Device` = '.$Device['Id'].' AND `LocalIP` != ""');
    48     while($Interface = $DbResult3->fetch_assoc())
     40      $DbResult2 = $this->System->Database->select('NetworkDevice', '*', '`Used` = 1 AND `Member` = '.$Member['Id']);
     41      while($Device = $DbResult2->fetch_assoc())
     42      {
     43        $DbResult3 = $this->Database->select('NetworkInterface', '*', '`Device` = '.$Device['Id'].' AND `LocalIP` != ""');
     44        while($Interface = $DbResult3->fetch_assoc())
     45        {
     46          $Name = $Device['Name'];
     47          if($Interface['Name'] != '') $Name .= '-'.$Interface['Name'];
     48          $Name = RouterOSIdent($Name);
     49          echo($Name.', ');
     50          $NewAddress = new NetworkAddressIPv4();
     51          $NewAddress->AddressFromString($Interface['LocalIP']);
     52          $NewAddress->Prefix = 32;
     53          InsertToAddressTree($AddressTree, $NewAddress, $Name);
     54        }
     55      }
     56
     57      $DbResult2 = $this->Database->select('NetworkSubnet', '*', '`Member`='.$Member['Id']);
     58      while($Subnet = $DbResult2->fetch_assoc())
     59      {
     60        $Subnet['Name'] = RouterOSIdent('subnet-'.$Subnet['Name']);
     61        echo($Subnet['Name'].', ');
     62        $NewAddress = new NetworkAddressIPv4();
     63        $NewAddress->AddressFromString($Subnet['AddressRange']);
     64        $NewAddress->Prefix = $Subnet['Mask'];
     65        if($Subnet['Member'] != 0) $ForceMark = true;
     66        else $ForceMark = false;
     67        echo($ForceMark.', ');
     68        InsertToAddressTree($AddressTree, $NewAddress, $Subnet['Name'], false, $ForceMark);
     69      }
     70      echo("\n");
     71    }
     72
     73    ShowSubnetNode($AddressTree);
     74
     75    function ProcessNode($Node)
    4976    {
    50       $Name = $Device['Name'];
    51       if($Interface['Name'] != '') $Name .= '-'.$Interface['Name'];
    52       $Name = RouterOSIdent($Name);
    53       echo($Name.', ');
    54       $NewAddress = new NetworkAddressIPv4();
    55       $NewAddress->AddressFromString($Interface['LocalIP']);
    56       $NewAddress->Prefix = 32;
    57       InsertToAddressTree($AddressTree, $NewAddress, $Name);
     77      global $InetInterface, $ItemsFirewall;
     78
     79      foreach($Node['Items'] as $Index => $Item)
     80      {
     81        if(count($Item['Items']) == 0)
     82        {
     83          // Hosts
     84          $ParentSubnetId = GetSubgroupByRange($Node['Address']->AddressToString().'/'.$Node['Address']->Prefix);
     85          $Address = $Item['Address']->AddressToString();
     86          if($Item['Address']->Prefix != 32) $Address .= '/'.$Item['Address']->Prefix;
     87
     88          $PacketMark = GetMarkByComment($Item['Name'].'-out');
     89          $ItemsFirewall[] = array('chain' => 'inet-'.$ParentSubnetId.'-out', 'src-address' => $Address, 'out-interface' =>  $InetInterface, 'action' => 'mark-packet', 'new-packet-mark' => $PacketMark, 'passthrough' => 'no', 'comment' => $Item['Name'].'-out');
     90          $PacketMark = GetMarkByComment($Item['Name'].'-in');
     91          $ItemsFirewall[] = array('chain' => 'inet-'.$ParentSubnetId.'-in', 'dst-address' => $Address, 'in-interface' => $InetInterface, 'action' => 'mark-packet', 'new-packet-mark' => $PacketMark, 'passthrough' => 'no', 'comment' => $Item['Name'].'-in');
     92        } else
     93        {
     94          // Subnets
     95          $ParentSubnetId = GetSubgroupByRange($Node['Address']->AddressToString().'/'.$Node['Address']->Prefix);
     96          $SubnetId = GetSubgroupByRange($Item['Address']->AddressToString().'/'.$Item['Address']->Prefix);
     97          $PacketMark = GetMarkByComment($Item['Name'].'-out');
     98
     99          $Address = $Item['Address']->AddressToString();
     100          if($Item['Address']->Prefix != 32) $Address .= '/'.$Item['Address']->Prefix;
     101
     102          $ItemsFirewall[] = array('chain' => 'inet-'.$ParentSubnetId.'-out', 'src-address' => $Address, 'out-interface' => $InetInterface, 'action' => 'jump', 'jump-target' => 'inet-'.$SubnetId.'-out', 'comment' => $Item['Name'].'-out');
     103          $ItemsFirewall[] = array('chain' => 'inet-'.$ParentSubnetId.'-in', 'dst-address' => $Address, 'in-interface' => $InetInterface, 'action' => 'jump', 'jump-target' => 'inet-'.$SubnetId.'-in', 'comment' => $Item['Name'].'-in');
     104
     105          ProcessNode($Item);
     106        }
     107      }
     108      if($Node['ForceMark'] == true)
     109      {
     110        // Mark member subnets
     111        $ParentSubnetId = GetSubgroupByRange($Node['Address']->AddressToString().'/'.$Node['Address']->Prefix);
     112
     113        $PacketMark = GetMarkByComment($Node['Name'].'-out');
     114        $ItemsFirewall[] = array('chain' => 'inet-'.$ParentSubnetId.'-out', 'src-address' => '', 'out-interface' =>  $InetInterface, 'action' => 'mark-packet', 'new-packet-mark' => $PacketMark, 'passthrough' => 'no', 'comment' => $Node['Name'].'-all-out');
     115        $PacketMark = GetMarkByComment($Node['Name'].'-in');
     116        $ItemsFirewall[] = array('chain' => 'inet-'.$ParentSubnetId.'-in', 'dst-address' => '', 'in-interface' => $InetInterface, 'action' => 'mark-packet', 'new-packet-mark' => $PacketMark, 'passthrough' => 'no', 'comment' => $Node['Name'].'-all-in');
     117      }
    58118    }
    59   }
    60119
    61   $DbResult2 = $System->Database->select('NetworkSubnet', '*', '`Member`='.$Member['Id']);
    62   while($Subnet = $DbResult2->fetch_assoc())
    63   {
    64     $Subnet['Name'] = RouterOSIdent('subnet-'.$Subnet['Name']);
    65     echo($Subnet['Name'].', ');
    66     $NewAddress = new NetworkAddressIPv4();
    67     $NewAddress->AddressFromString($Subnet['AddressRange']);
    68     $NewAddress->Prefix = $Subnet['Mask'];
    69     if($Subnet['Member'] != 0) $ForceMark = true;
    70       else $ForceMark = false;
    71     echo($ForceMark.', ');
    72     InsertToAddressTree($AddressTree, $NewAddress, $Subnet['Name'], false, $ForceMark);
    73   }
    74   echo("\n");
    75 }
     120    // Generate firewall rules
     121    $ItemsFirewall = array();
    76122
    77 ShowSubnetNode($AddressTree);
     123    // Root of tree and main limit
     124    $ItemsFirewall[] = array('chain' => 'forward', 'out-interface' => $InetInterface, 'dst-address' => '!77.92.221.0/24', 'action' => 'jump', 'jump-target' => 'inet-1-out', 'comment' => 'main-out');
     125    $ItemsFirewall[] = array('chain' => 'forward', 'in-interface' => $InetInterface, 'src-address' => '!77.92.221.0/24', 'action' => 'jump', 'jump-target' => 'inet-1-in', 'comment' => 'main-in');
    78126
    79 function ProcessNode($Node)
    80 {
    81   global $InetInterface, $ItemsFirewall;
     127    ProcessNode($AddressTree);
    82128
    83   foreach($Node['Items'] as $Index => $Item)
    84   {
    85     if(count($Item['Items']) == 0)
    86     {
    87       // Hosts
    88       $ParentSubnetId = GetSubgroupByRange($Node['Address']->AddressToString().'/'.$Node['Address']->Prefix);
    89       $Address = $Item['Address']->AddressToString();
    90       if($Item['Address']->Prefix != 32) $Address .= '/'.$Item['Address']->Prefix;
     129    // Limited free internet
     130    $PacketMark = GetMarkByComment('free-out');
     131    $ItemsFirewall[] = array('chain' => 'inet-1-out', 'out-interface' => $InetInterface,
     132        'action' => 'mark-packet', 'new-packet-mark' => $PacketMark, 'comment' => 'free-out', 'passthrough' => 'yes');
     133    $PacketMark = GetMarkByComment('free-in');
     134    $ItemsFirewall[] = array('chain' => 'inet-1-in', 'in-interface' => $InetInterface,
     135        'action' => 'mark-packet', 'new-packet-mark' => $PacketMark, 'comment' => 'free-in', 'passthrough' => 'no');
     136    // Unregistred clients add to address list
     137    $ItemsFirewall[] = array('chain' => 'inet-1-out', 'out-interface' => $InetInterface, 'src-address' => '10.145.0.0/16',
     138        'action' => 'add-src-to-address-list', 'address-list' => 'unregistred', 'address-list-timeout' => '1d',
     139        'comment' => 'unregistred-clients');
    91140
    92       $PacketMark = GetMarkByComment($Item['Name'].'-out');
    93       $ItemsFirewall[] = array('chain' => 'inet-'.$ParentSubnetId.'-out', 'src-address' => $Address, 'out-interface' =>  $InetInterface, 'action' => 'mark-packet', 'new-packet-mark' => $PacketMark, 'passthrough' => 'no', 'comment' => $Item['Name'].'-out');
    94       $PacketMark = GetMarkByComment($Item['Name'].'-in');
    95       $ItemsFirewall[] = array('chain' => 'inet-'.$ParentSubnetId.'-in', 'dst-address' => $Address, 'in-interface' => $InetInterface, 'action' => 'mark-packet', 'new-packet-mark' => $PacketMark, 'passthrough' => 'no', 'comment' => $Item['Name'].'-in');
    96     } else
    97     {
    98       // Subnets
    99       $ParentSubnetId = GetSubgroupByRange($Node['Address']->AddressToString().'/'.$Node['Address']->Prefix);
    100       $SubnetId = GetSubgroupByRange($Item['Address']->AddressToString().'/'.$Item['Address']->Prefix);
    101       $PacketMark = GetMarkByComment($Item['Name'].'-out');
    102 
    103       $Address = $Item['Address']->AddressToString();
    104       if($Item['Address']->Prefix != 32) $Address .= '/'.$Item['Address']->Prefix;
    105 
    106       $ItemsFirewall[] = array('chain' => 'inet-'.$ParentSubnetId.'-out', 'src-address' => $Address, 'out-interface' => $InetInterface, 'action' => 'jump', 'jump-target' => 'inet-'.$SubnetId.'-out', 'comment' => $Item['Name'].'-out');
    107       $ItemsFirewall[] = array('chain' => 'inet-'.$ParentSubnetId.'-in', 'dst-address' => $Address, 'in-interface' => $InetInterface, 'action' => 'jump', 'jump-target' => 'inet-'.$SubnetId.'-in', 'comment' => $Item['Name'].'-in');
    108 
    109       ProcessNode($Item);
    110     }
    111   }
    112   if($Node['ForceMark'] == true)
    113   {
    114     // Mark member subnets
    115     $ParentSubnetId = GetSubgroupByRange($Node['Address']->AddressToString().'/'.$Node['Address']->Prefix);
    116 
    117     $PacketMark = GetMarkByComment($Node['Name'].'-out');
    118     $ItemsFirewall[] = array('chain' => 'inet-'.$ParentSubnetId.'-out', 'src-address' => '', 'out-interface' =>  $InetInterface, 'action' => 'mark-packet', 'new-packet-mark' => $PacketMark, 'passthrough' => 'no', 'comment' => $Node['Name'].'-all-out');
    119     $PacketMark = GetMarkByComment($Node['Name'].'-in');
    120     $ItemsFirewall[] = array('chain' => 'inet-'.$ParentSubnetId.'-in', 'dst-address' => '', 'in-interface' => $InetInterface, 'action' => 'mark-packet', 'new-packet-mark' => $PacketMark, 'passthrough' => 'no', 'comment' => $Node['Name'].'-all-in');
     141    //print_r($ItemsFirewall);
     142    $Routerboard->ListUpdate($PathFirewall, array('chain', 'dst-address', 'in-interface', 'action', 'new-packet-mark', 'passthrough', 'comment', 'out-interface', 'src-address', 'jump-target'), $ItemsFirewall, array(), true);
    121143  }
    122144}
    123 
    124 // Generate firewall rules
    125 $ItemsFirewall = array();
    126 
    127 // Root of tree and main limit
    128 $ItemsFirewall[] = array('chain' => 'forward', 'out-interface' => $InetInterface, 'dst-address' => '!77.92.221.0/24', 'action' => 'jump', 'jump-target' => 'inet-1-out', 'comment' => 'main-out');
    129 $ItemsFirewall[] = array('chain' => 'forward', 'in-interface' => $InetInterface, 'src-address' => '!77.92.221.0/24', 'action' => 'jump', 'jump-target' => 'inet-1-in', 'comment' => 'main-in');
    130 
    131 ProcessNode($AddressTree);
    132 
    133 // Limited free internet
    134 $PacketMark = GetMarkByComment('free-out');
    135 $ItemsFirewall[] = array('chain' => 'inet-1-out', 'out-interface' => $InetInterface,
    136   'action' => 'mark-packet', 'new-packet-mark' => $PacketMark, 'comment' => 'free-out', 'passthrough' => 'yes');
    137 $PacketMark = GetMarkByComment('free-in');
    138 $ItemsFirewall[] = array('chain' => 'inet-1-in', 'in-interface' => $InetInterface,
    139   'action' => 'mark-packet', 'new-packet-mark' => $PacketMark, 'comment' => 'free-in', 'passthrough' => 'no');
    140 // Unregistred clients add to address list
    141 $ItemsFirewall[] = array('chain' => 'inet-1-out', 'out-interface' => $InetInterface, 'src-address' => '10.145.0.0/16',
    142   'action' => 'add-src-to-address-list', 'address-list' => 'unregistred', 'address-list-timeout' => '1d',
    143   'comment' => 'unregistred-clients');
    144 
    145 //print_r($ItemsFirewall);
    146 $Routerboard->ListUpdate($PathFirewall, array('chain', 'dst-address', 'in-interface', 'action', 'new-packet-mark', 'passthrough', 'comment', 'out-interface', 'src-address', 'jump-target'), $ItemsFirewall, array(), true);
  • trunk/Modules/NetworkConfigRouterOS/Generators/FirewallNAT.php

    r778 r781  
    11<?php
    22
    3 if(isset($_SERVER['REMOTE_ADDR'])) die();
    4 include_once(dirname(__FILE__).'/../../../Application/System.php');
    5 $System = new System();
    6 $System->ShowPage = false;
    7 $System->Run();
    8 $Path = array('ip', 'firewall', 'nat');
     3class ConfigRouterOSFirewallNAT extends NetworkConfigItem
     4{
     5  function Run()
     6  {
     7    $Path = array('ip', 'firewall', 'nat');
    98
    10 $Routerboard = new Routerboard($Config['MainRouter']['HostName']);
    11 $Routerboard->UserName = $Config['MainRouter']['UserName'];
    12 $Routerboard->Timeout = $Config['MainRouter']['ConnectTimeout'];
    13 $Routerboard->Debug = true;
     9    $Routerboard = new Routerboard($this->System->Config['MainRouter']['HostName']);
     10    $Routerboard->UserName = $this->System->Config['MainRouter']['UserName'];
     11    $Routerboard->Timeout = $this->System->Config['MainRouter']['ConnectTimeout'];
     12    $Routerboard->Debug = true;
    1413
    15 $InetInterface = $Config['MainRouter']['InetInterface'];
    16 $LocalInterface = $Config['MainRouter']['LocalInterface'];
    17 $IPCentrala = '10.145.64.8';
     14    $InetInterface = $this->System->Config['MainRouter']['InetInterface'];
     15    $LocalInterface = $this->System->Config['MainRouter']['LocalInterface'];
     16    $IPCentrala = '10.145.64.8';
    1817
    19 $Items = array();
     18    $Items = array();
    2019
    21 /*
    22 // NTP redirect
    23 $Items[] = array('chain' => 'srcnat', 'src-address' => '10.145.66.1', 'protocol' => 'udp', 'src-port' => 123, 'action' => 'src-nat', 'to-addresses' => '10.145.64.1', 'comment' => 'NTP_redirect_4');
    24 $Items[] = array('chain' => 'srcnat', 'src-address' => '10.145.66.161', 'protocol' => 'udp', 'src-port' => 123, 'action' => 'src-nat', 'to-addresses' => '10.145.64.1', 'comment' => 'NTP_redirect_5');
    25 $Items[] = array('chain' => 'srcnat', 'src-address' => '10.145.66.193', 'protocol' => 'udp', 'src-port' => 123, 'action' => 'src-nat', 'to-addresses' => '10.145.64.1', 'comment' => 'NTP_redirect_1');
    26 $Items[] = array('chain' => 'srcnat', 'src-address' => '10.145.66.225', 'protocol' => 'udp', 'src-port' => 123, 'action' => 'src-nat', 'to-addresses' => '10.145.64.1', 'comment' => 'NTP_redirect_2');
    27 $Items[] = array('chain' => 'srcnat', 'src-address' => '10.145.66.250', 'protocol' => 'udp', 'src-port' => 123, 'action' => 'src-nat', 'to-addresses' => '10.145.64.1', 'comment' => 'NTP_redirect_3');
    28 $Items[] = array('chain' => 'srcnat', 'src-address' => '10.145.66.253', 'protocol' => 'udp', 'src-port' => 123, 'action' => 'src-nat', 'to-addresses' => '10.145.64.1', 'comment' => 'NTP_redirect_6');
    29 */
     20    /*
     21     // NTP redirect
     22     $Items[] = array('chain' => 'srcnat', 'src-address' => '10.145.66.1', 'protocol' => 'udp', 'src-port' => 123, 'action' => 'src-nat', 'to-addresses' => '10.145.64.1', 'comment' => 'NTP_redirect_4');
     23     $Items[] = array('chain' => 'srcnat', 'src-address' => '10.145.66.161', 'protocol' => 'udp', 'src-port' => 123, 'action' => 'src-nat', 'to-addresses' => '10.145.64.1', 'comment' => 'NTP_redirect_5');
     24     $Items[] = array('chain' => 'srcnat', 'src-address' => '10.145.66.193', 'protocol' => 'udp', 'src-port' => 123, 'action' => 'src-nat', 'to-addresses' => '10.145.64.1', 'comment' => 'NTP_redirect_1');
     25     $Items[] = array('chain' => 'srcnat', 'src-address' => '10.145.66.225', 'protocol' => 'udp', 'src-port' => 123, 'action' => 'src-nat', 'to-addresses' => '10.145.64.1', 'comment' => 'NTP_redirect_2');
     26     $Items[] = array('chain' => 'srcnat', 'src-address' => '10.145.66.250', 'protocol' => 'udp', 'src-port' => 123, 'action' => 'src-nat', 'to-addresses' => '10.145.64.1', 'comment' => 'NTP_redirect_3');
     27     $Items[] = array('chain' => 'srcnat', 'src-address' => '10.145.66.253', 'protocol' => 'udp', 'src-port' => 123, 'action' => 'src-nat', 'to-addresses' => '10.145.64.1', 'comment' => 'NTP_redirect_6');
     28     */
    3029
    31 // Chain for inet interface
    32 $Items[] = array('chain' => 'srcnat', 'out-interface' => $InetInterface, 'action' => 'jump', 'jump-target' => 'inet-out', 'comment' => 'inet-out');
    33 $Items[] = array('chain' => 'dstnat', 'in-interface' => $InetInterface, 'action' => 'jump', 'jump-target' => 'inet-in', 'comment' => 'inet-in');
     30    // Chain for inet interface
     31    $Items[] = array('chain' => 'srcnat', 'out-interface' => $InetInterface, 'action' => 'jump', 'jump-target' => 'inet-out', 'comment' => 'inet-out');
     32    $Items[] = array('chain' => 'dstnat', 'in-interface' => $InetInterface, 'action' => 'jump', 'jump-target' => 'inet-in', 'comment' => 'inet-in');
    3433
    35 // Skip local subnet
    36 //$Items[] = array('chain' => 'inet-out', 'dst-address' => '172.16.1.1/30', 'action' => 'accept', 'comment' => 'Local_subnet');
    37 //$Items[] = array('chain' => 'inet-in', 'dst-address' => '172.16.1.1/30', 'action' => 'accept', 'comment' => 'Local_subnet');
     34    // Skip local subnet
     35    //$Items[] = array('chain' => 'inet-out', 'dst-address' => '172.16.1.1/30', 'action' => 'accept', 'comment' => 'Local_subnet');
     36    //$Items[] = array('chain' => 'inet-in', 'dst-address' => '172.16.1.1/30', 'action' => 'accept', 'comment' => 'Local_subnet');
    3837
    39 $DbResult = $System->Database->query('SELECT `Member`.*, `Subject`.`Name` FROM `Member` '.
    40   'LEFT JOIN `Subject` ON `Subject`.`Id` = `Member`.`Subject` '.
    41   'WHERE `Member`.`Blocked` = 0');
    42 while($Member = $DbResult->fetch_assoc())
    43 {
    44   echo($Member['Name'].': ');
    45   // Hosts
    46   $DbResult2 = $System->Database->query('SELECT `NetworkInterface`.*, `NetworkDevice`.`Name` AS `DeviceName`, `NetworkDevice`.`InboundNATPriority` FROM `NetworkInterface`'.
    47   ' LEFT JOIN `NetworkDevice` ON `NetworkDevice`.`Id` = `NetworkInterface`.`Device` WHERE (`NetworkInterface`.`ExternalIP` <> "")'.
    48   ' AND (`NetworkInterface`.`LocalIP` <> "")'.
    49   ' AND (`NetworkDevice`.`Member` = '.$Member['Id'].') AND (`NetworkInterface`.`LocalIP` != `NetworkInterface`.`ExternalIP`) ORDER BY `id` DESC');
    50   while($Interface = $DbResult2->fetch_assoc())
    51   {
    52     $Name = $Interface['DeviceName'];
    53     if($Interface['Name'] != '') $Name .= '-'.$Interface['Name'];
    54     $Name = RouterOSIdent($Name);
    55     echo($Name.'('.$Interface['LocalIP'].'), ');
    56     if($Member['Blocked'] == 0)
     38    $DbResult = $this->Database->query('SELECT `Member`.*, `Subject`.`Name` FROM `Member` '.
     39        'LEFT JOIN `Subject` ON `Subject`.`Id` = `Member`.`Subject` '.
     40        'WHERE `Member`.`Blocked` = 0');
     41    while($Member = $DbResult->fetch_assoc())
    5742    {
    58       $Items[] = array('chain' => 'inet-out', 'src-address' => $Interface['LocalIP'], 'action' => 'src-nat',  'to-addresses' => $Interface['ExternalIP'], 'comment' => $Name.'-out');
    59       if($Interface['InboundNATPriority'] > 0)
    60         $Items[] = array('chain' => 'inet-in', 'dst-address' => $Interface['ExternalIP'], 'action' => 'dst-nat', 'to-addresses' => $Interface['LocalIP'], 'comment' => $Name.'-in');
    61     } else
    62     {
    63       $Items[] = array('chain' => 'dstnat', 'src-address' => $Interface['LocalIP'], 'protocol' => 'tcp', 'dst-port' => 80, 'action' => 'dst-nat',  'to-addresses' => $IPCentrala, 'to-ports' => 81, 'comment' => $Name.'-out');
     43      echo($Member['Name'].': ');
     44      // Hosts
     45      $DbResult2 = $this->Database->query('SELECT `NetworkInterface`.*, `NetworkDevice`.`Name` AS `DeviceName`, `NetworkDevice`.`InboundNATPriority` FROM `NetworkInterface`'.
     46          ' LEFT JOIN `NetworkDevice` ON `NetworkDevice`.`Id` = `NetworkInterface`.`Device` WHERE (`NetworkInterface`.`ExternalIP` <> "")'.
     47          ' AND (`NetworkInterface`.`LocalIP` <> "")'.
     48          ' AND (`NetworkDevice`.`Member` = '.$Member['Id'].') AND (`NetworkInterface`.`LocalIP` != `NetworkInterface`.`ExternalIP`) ORDER BY `id` DESC');
     49      while($Interface = $DbResult2->fetch_assoc())
     50      {
     51        $Name = $Interface['DeviceName'];
     52        if($Interface['Name'] != '') $Name .= '-'.$Interface['Name'];
     53        $Name = RouterOSIdent($Name);
     54        echo($Name.'('.$Interface['LocalIP'].'), ');
     55        if($Member['Blocked'] == 0)
     56        {
     57          $Items[] = array('chain' => 'inet-out', 'src-address' => $Interface['LocalIP'], 'action' => 'src-nat',  'to-addresses' => $Interface['ExternalIP'], 'comment' => $Name.'-out');
     58          if($Interface['InboundNATPriority'] > 0)
     59            $Items[] = array('chain' => 'inet-in', 'dst-address' => $Interface['ExternalIP'], 'action' => 'dst-nat', 'to-addresses' => $Interface['LocalIP'], 'comment' => $Name.'-in');
     60        } else
     61        {
     62          $Items[] = array('chain' => 'dstnat', 'src-address' => $Interface['LocalIP'], 'protocol' => 'tcp', 'dst-port' => 80, 'action' => 'dst-nat',  'to-addresses' => $IPCentrala, 'to-ports' => 81, 'comment' => $Name.'-out');
     63        }
     64      }
     65
     66      // Subnets
     67      $DbResult2 = $this->Database->select('NetworkSubnet', '*', '`Member`='.$Member['Id']);
     68      while($Subnet = $DbResult2->fetch_assoc())
     69      {
     70        $Subnet['Name'] = RouterOSIdent('subnet-'.$Subnet['Name']);
     71        echo($Subnet['Name'].'('.$Subnet['AddressRange'].'/'.$Subnet['Mask'].'), ');
     72        if($Member['Blocked'] == 0)
     73        {
     74          $NewAddress = new NetworkAddressIPv4();
     75          $NewAddress->AddressFromString($Subnet['ExtAddressRange']);
     76          $NewAddress->Prefix = $Subnet['ExtMask'];
     77          $Range = $NewAddress->GetRange();
     78          if($Subnet['ExtMask'] != 32) $Range = $Range['From']->AddressToString().'-'.$Range['To']->AddressToString();
     79          else $Range = $Range['From']->AddressToString();
     80          if($Subnet['Mask'] == 32) $Src = $Subnet['AddressRange'];
     81          else $Src = $Subnet['AddressRange'].'/'.$Subnet['Mask'];
     82          $Items[] = array('chain' => 'inet-out', 'src-address' => $Src, 'action' => 'src-nat', 'to-addresses' => $Range, 'comment' => $Subnet['Name'].'-out');
     83
     84          $NewAddress = new NetworkAddressIPv4();
     85          $NewAddress->AddressFromString($Subnet['AddressRange']);
     86          $NewAddress->Prefix = $Subnet['Mask'];
     87          $Range = $NewAddress->GetRange();
     88          if($Subnet['Mask'] != 32) $Range = $Range['From']->AddressToString().'-'.$Range['To']->AddressToString();
     89          else $Range = $Range['From']->AddressToString();
     90          if($Subnet['ExtMask'] == 32) $Dest = $Subnet['ExtAddressRange'];
     91          else $Dest = $Subnet['ExtAddressRange'].'/'.$Subnet['ExtMask'];
     92          $Items[] = array('chain' => 'inet-in', 'dst-address' => $Dest, 'action' => 'dst-nat', 'to-addresses' => $Range, 'comment' => $Subnet['Name'].'-in');
     93        } else
     94        {
     95          if($Subnet['Mask'] == 32) $Src = $Subnet['AddressRange'];
     96          else $Src = $Subnet['AddressRange'].'/'.$Subnet['Mask'];
     97          $Items[] = array('chain' => 'dstnat', 'src-address' => $Src, 'protocol' => 'tcp', 'dst-port' => 80, 'action' => 'dst-nat',  'to-addresses' => $IPCentrala, 'to-ports' => 81, 'comment' => $Subnet['Name'].'-out');
     98        }
     99      }
     100      echo("\n");
    64101    }
     102
     103    // Redirect DNS port
     104    $Items[] = array('chain' => 'dstnat', 'dst-address' => '212.111.4.174', 'protocol' => 'tcp', 'dst-port' => 53, 'in-interface' => $InetInterface, 'action' => 'dst-nat', 'to-addresses' => '10.145.64.8', 'to-ports' => 53, 'comment' => 'DNS_redirection_TCP');
     105    $Items[] = array('chain' => 'dstnat', 'dst-address' => '212.111.4.174', 'protocol' => 'udp', 'dst-port' => 53, 'in-interface' => $InetInterface, 'action' => 'dst-nat', 'to-addresses' => '10.145.64.8', 'to-ports' => 53, 'comment' => 'DNS_redirection_UDP');
     106
     107    // Chain for local interface
     108    $Items[] = array('chain' => 'srcnat', 'out-interface' => $LocalInterface, 'action' => 'jump', 'jump-target' => 'local-out', 'comment' => 'local-out');
     109    $Items[] = array('chain' => 'dstnat', 'in-interface' => $LocalInterface, 'action' => 'jump', 'jump-target' => 'local-in', 'comment' => 'local-in');
     110
     111    // Accept free-access clients
     112    $Items[] = array('chain' => 'dstnat', 'dst-address' => '!10.145.0.0/16',
     113        'src-address-list' => 'free-access', 'in-interface' => $LocalInterface,
     114        'action' => 'accept', 'comment' => 'Free_access');
     115    // Redirect unregistred clients to free access activation page
     116    $Items[] = array('chain' => 'dstnat', 'dst-address' => '!10.145.0.0/16',
     117        'src-address-list' => 'unregistred', 'in-interface' => $LocalInterface, 'protocol' => 'tcp',
     118        'action' => 'dst-nat', 'to-addresses' => '10.145.64.70', 'to-ports' => 8080, 'comment' => 'Redirect_unregistred');
     119
     120    // Masquerade hosts without public ip
     121    $Items[] = array('chain' => 'inet-out', 'src-address'=> '!212.111.4.174', 'action' => 'src-nat', 'to-addresses' => '77.92.221.188', 'comment' => 'Default_NAT');
     122
     123    /*
     124     // Route public addresses localy
     125     $DbResult = $this->Database->query('SELECT Member.*, Subject.Name FROM Member JOIN Subject ON Member.Subject = Subject.Id');
     126     while($Member = $DbResult->fetch_assoc())
     127     {
     128     echo($Member['Name'].': ');
     129     // Hosts
     130     $DbResult2 = $this->Database->query('SELECT NetworkInterface.*, NetworkDevice.Name AS DeviceName FROM NetworkInterface LEFT JOIN NetworkDevice ON NetworkDevice.Id = NetworkInterface.Device WHERE (NetworkInterface.ExternalIP <> "") AND (NetworkDevice.Member = '.$Member['Id'].') AND (NetworkInterface.LocalIP != NetworkInterface.ExternalIP) ORDER BY id DESC');
     131     while($Interface = $DbResult2->fetch_assoc())
     132     {
     133     $Name = $Interface['DeviceName'];
     134     if($Interface['Name'] != '') $Name .= '-'.$Interface['Name'];
     135     $Name = RouterOSIdent($Name);
     136     echo($Name.'('.$Interface['LocalIP'].'), ');
     137     $Items[] = array('chain' => 'local-in', 'dst-address' => $Interface['ExternalIP'], 'action' => 'dst-nat', 'to-addresses' => $Interface['LocalIP'], 'comment' => $Name.'-in-local');
     138     }
     139     echo("\n");
     140     }
     141
     142     // Map returned local traffic to virtual subnet
     143     $Items[] = array('chain' => 'local-out', 'src-address' => '10.145.0.0/16', 'dst-address' => '10.145.0.0/16', 'action' => 'netmap',  'to-addresses' => '10.45.0.0-10.45.255.255', 'comment' => 'map-local');
     144     */
     145
     146    //print_r($Items);
     147    $Routerboard->ListUpdate($Path, array('chain', 'dst-address', 'in-interface', 'src-address', 'out-interface', 'to-ports', 'dst-port', 'protocol', 'action', 'to-addresses', 'comment', 'jump-target', 'src-port'), $Items);
    65148  }
    66 
    67   // Subnets
    68   $DbResult2 = $System->Database->select('NetworkSubnet', '*', '`Member`='.$Member['Id']);
    69   while($Subnet = $DbResult2->fetch_assoc())
    70   {
    71     $Subnet['Name'] = RouterOSIdent('subnet-'.$Subnet['Name']);
    72     echo($Subnet['Name'].'('.$Subnet['AddressRange'].'/'.$Subnet['Mask'].'), ');
    73     if($Member['Blocked'] == 0)
    74     {
    75       $NewAddress = new NetworkAddressIPv4();
    76       $NewAddress->AddressFromString($Subnet['ExtAddressRange']);
    77       $NewAddress->Prefix = $Subnet['ExtMask'];
    78       $Range = $NewAddress->GetRange();
    79       if($Subnet['ExtMask'] != 32) $Range = $Range['From']->AddressToString().'-'.$Range['To']->AddressToString();
    80         else $Range = $Range['From']->AddressToString();
    81       if($Subnet['Mask'] == 32) $Src = $Subnet['AddressRange'];
    82         else $Src = $Subnet['AddressRange'].'/'.$Subnet['Mask'];
    83       $Items[] = array('chain' => 'inet-out', 'src-address' => $Src, 'action' => 'src-nat', 'to-addresses' => $Range, 'comment' => $Subnet['Name'].'-out');
    84 
    85       $NewAddress = new NetworkAddressIPv4();
    86       $NewAddress->AddressFromString($Subnet['AddressRange']);
    87       $NewAddress->Prefix = $Subnet['Mask'];
    88       $Range = $NewAddress->GetRange();
    89       if($Subnet['Mask'] != 32) $Range = $Range['From']->AddressToString().'-'.$Range['To']->AddressToString();
    90         else $Range = $Range['From']->AddressToString();
    91       if($Subnet['ExtMask'] == 32) $Dest = $Subnet['ExtAddressRange'];
    92         else $Dest = $Subnet['ExtAddressRange'].'/'.$Subnet['ExtMask'];
    93       $Items[] = array('chain' => 'inet-in', 'dst-address' => $Dest, 'action' => 'dst-nat', 'to-addresses' => $Range, 'comment' => $Subnet['Name'].'-in');
    94     } else
    95     {
    96       if($Subnet['Mask'] == 32) $Src = $Subnet['AddressRange'];
    97         else $Src = $Subnet['AddressRange'].'/'.$Subnet['Mask'];
    98       $Items[] = array('chain' => 'dstnat', 'src-address' => $Src, 'protocol' => 'tcp', 'dst-port' => 80, 'action' => 'dst-nat',  'to-addresses' => $IPCentrala, 'to-ports' => 81, 'comment' => $Subnet['Name'].'-out');
    99     }
    100   }
    101   echo("\n");
    102149}
    103 
    104 // Redirect DNS port
    105 $Items[] = array('chain' => 'dstnat', 'dst-address' => '212.111.4.174', 'protocol' => 'tcp', 'dst-port' => 53, 'in-interface' => $InetInterface, 'action' => 'dst-nat', 'to-addresses' => '10.145.64.8', 'to-ports' => 53, 'comment' => 'DNS_redirection_TCP');
    106 $Items[] = array('chain' => 'dstnat', 'dst-address' => '212.111.4.174', 'protocol' => 'udp', 'dst-port' => 53, 'in-interface' => $InetInterface, 'action' => 'dst-nat', 'to-addresses' => '10.145.64.8', 'to-ports' => 53, 'comment' => 'DNS_redirection_UDP');
    107 
    108 // Chain for local interface
    109 $Items[] = array('chain' => 'srcnat', 'out-interface' => $LocalInterface, 'action' => 'jump', 'jump-target' => 'local-out', 'comment' => 'local-out');
    110 $Items[] = array('chain' => 'dstnat', 'in-interface' => $LocalInterface, 'action' => 'jump', 'jump-target' => 'local-in', 'comment' => 'local-in');
    111 
    112 // Accept free-access clients
    113 $Items[] = array('chain' => 'dstnat', 'dst-address' => '!10.145.0.0/16',
    114   'src-address-list' => 'free-access', 'in-interface' => $LocalInterface,
    115   'action' => 'accept', 'comment' => 'Free_access');
    116 // Redirect unregistred clients to free access activation page
    117 $Items[] = array('chain' => 'dstnat', 'dst-address' => '!10.145.0.0/16',
    118   'src-address-list' => 'unregistred', 'in-interface' => $LocalInterface, 'protocol' => 'tcp',
    119   'action' => 'dst-nat', 'to-addresses' => '10.145.64.70', 'to-ports' => 8080, 'comment' => 'Redirect_unregistred');
    120 
    121 // Masquerade hosts without public ip
    122 $Items[] = array('chain' => 'inet-out', 'src-address'=> '!212.111.4.174', 'action' => 'src-nat', 'to-addresses' => '77.92.221.188', 'comment' => 'Default_NAT');
    123 
    124 /*
    125 // Route public addresses localy
    126 $DbResult = $System->Database->query('SELECT Member.*, Subject.Name FROM Member JOIN Subject ON Member.Subject = Subject.Id');
    127 while($Member = $DbResult->fetch_assoc())
    128 {
    129   echo($Member['Name'].': ');
    130   // Hosts
    131   $DbResult2 = $System->Database->query('SELECT NetworkInterface.*, NetworkDevice.Name AS DeviceName FROM NetworkInterface LEFT JOIN NetworkDevice ON NetworkDevice.Id = NetworkInterface.Device WHERE (NetworkInterface.ExternalIP <> "") AND (NetworkDevice.Member = '.$Member['Id'].') AND (NetworkInterface.LocalIP != NetworkInterface.ExternalIP) ORDER BY id DESC');
    132   while($Interface = $DbResult2->fetch_assoc())
    133   {
    134     $Name = $Interface['DeviceName'];
    135     if($Interface['Name'] != '') $Name .= '-'.$Interface['Name'];
    136     $Name = RouterOSIdent($Name);
    137     echo($Name.'('.$Interface['LocalIP'].'), ');
    138     $Items[] = array('chain' => 'local-in', 'dst-address' => $Interface['ExternalIP'], 'action' => 'dst-nat', 'to-addresses' => $Interface['LocalIP'], 'comment' => $Name.'-in-local');
    139   }
    140   echo("\n");
    141 }
    142 
    143 // Map returned local traffic to virtual subnet
    144 $Items[] = array('chain' => 'local-out', 'src-address' => '10.145.0.0/16', 'dst-address' => '10.145.0.0/16', 'action' => 'netmap',  'to-addresses' => '10.45.0.0-10.45.255.255', 'comment' => 'map-local');
    145 */
    146 
    147 //print_r($Items);
    148 $Routerboard->ListUpdate($Path, array('chain', 'dst-address', 'in-interface', 'src-address', 'out-interface', 'to-ports', 'dst-port', 'protocol', 'action', 'to-addresses', 'comment', 'jump-target', 'src-port'), $Items);
  • trunk/Modules/NetworkConfigRouterOS/Generators/Netwatch.php

    r738 r781  
    11<?php
    22
    3 if(isset($_SERVER['REMOTE_ADDR'])) die();
    4 include_once(dirname(__FILE__).'/../../../Application/System.php');
    5 $System = new System();
    6 $System->ShowPage = false;
    7 $System->Run();
    8 $Path = array('tool', 'netwatch');
     3class ConfigRouterOSNetwatch extends NetworkConfigItem
     4{
     5  function Run()
     6  {
     7    $Path = array('tool', 'netwatch');
    98
    10 $Routerboard = new Routerboard();
    11 $Routerboard->UserName = $Config['MainRouter']['UserName'];
    12 $Routerboard->Timeout = $Config['MainRouter']['ConnectTimeout'];
    13 $Routerboard->Debug = true;
     9    $Routerboard = new Routerboard();
     10    $Routerboard->UserName = $this->System->Config['MainRouter']['UserName'];
     11    $Routerboard->Timeout = $this->System->Config['MainRouter']['ConnectTimeout'];
     12    $Routerboard->Debug = true;
    1413
    15 $DbResult3 = $System->Database->query('SELECT DISTINCT (`DHCP`) FROM `NetworkSubnet` WHERE `Configure` = 1'); // WHERE `Member` = 0');
    16 while($Router = $DbResult3->fetch_assoc())
    17 {
    18   echo($Router['DHCP']."\n");
    19   $Routerboard->HostName = $Router['DHCP'];
    20   $Items = array();
    21   $DbResult = $System->Database->query('SELECT * FROM `NetworkSubnet` WHERE (`Configure` = 1) AND (`DHCP`="'.$Router['DHCP'].'")');
    22   while($Subnet = $DbResult->fetch_assoc())
    23   {
    24     $I = explode('.', $Subnet['AddressRange']);
    25     $I = $I[2];
    26     $DbResult2 = $System->Database->query('SELECT `NetworkInterface`.*, `NetworkDevice`.`Name` AS `DeviceName` FROM `NetworkInterface`'.
    27     ' LEFT JOIN `NetworkDevice` ON `NetworkDevice`.`Id` = `NetworkInterface`.`Device` WHERE CompareNetworkPrefix(INET_ATON(`LocalIP`), INET_ATON("'.$Subnet['AddressRange'].'"), '.$Subnet['Mask'].')'.
    28     ' AND (`NetworkDevice`.`Used` = 1) ORDER BY `NetworkInterface`.`LocalIP`');
    29     while($Interface = $DbResult2->fetch_assoc())
     14    $DbResult3 = $this->Database->query('SELECT DISTINCT (`DHCP`) FROM `NetworkSubnet` WHERE `Configure` = 1'); // WHERE `Member` = 0');
     15    while($Router = $DbResult3->fetch_assoc())
    3016    {
    31       $Name = $Interface['DeviceName'];
    32       if($Interface['Name'] != '') $Name .= '-'.$Interface['Name'];
    33       echo($Name.', ');
    34       $Items[] = array('host' => $Interface['LocalIP'], 'interval' => '00:01:00', 'comment' => $Name);
     17      echo($Router['DHCP']."\n");
     18      $Routerboard->HostName = $Router['DHCP'];
     19      $Items = array();
     20      $DbResult = $this->Database->query('SELECT * FROM `NetworkSubnet` WHERE (`Configure` = 1) AND (`DHCP`="'.$Router['DHCP'].'")');
     21      while($Subnet = $DbResult->fetch_assoc())
     22      {
     23        $I = explode('.', $Subnet['AddressRange']);
     24        $I = $I[2];
     25        $DbResult2 = $this->Database->query('SELECT `NetworkInterface`.*, `NetworkDevice`.`Name` AS `DeviceName` FROM `NetworkInterface`'.
     26            ' LEFT JOIN `NetworkDevice` ON `NetworkDevice`.`Id` = `NetworkInterface`.`Device` WHERE CompareNetworkPrefix(INET_ATON(`LocalIP`), INET_ATON("'.$Subnet['AddressRange'].'"), '.$Subnet['Mask'].')'.
     27            ' AND (`NetworkDevice`.`Used` = 1) ORDER BY `NetworkInterface`.`LocalIP`');
     28        while($Interface = $DbResult2->fetch_assoc())
     29        {
     30          $Name = $Interface['DeviceName'];
     31          if($Interface['Name'] != '') $Name .= '-'.$Interface['Name'];
     32          echo($Name.', ');
     33          $Items[] = array('host' => $Interface['LocalIP'], 'interval' => '00:01:00', 'comment' => $Name);
     34        }
     35      }
     36      $Routerboard->ListUpdate($Path, array('host', 'interval', 'comment'), $Items);
     37      echo("\n");
    3538    }
    3639  }
    37   $Routerboard->ListUpdate($Path, array('host', 'interval', 'comment'), $Items);
    38   echo("\n");
    3940}
  • trunk/Modules/NetworkConfigRouterOS/Generators/NetwatchImport.php

    r738 r781  
    11<?php
    22
    3 if(isset($_SERVER['REMOTE_ADDR'])) die();
    4 include_once(dirname(__FILE__).'/../../../Application/System.php');
    5 $System = new System();
    6 $System->ShowPage = false;
    7 $System->Run();
     3class ConfigRouterOSNetwatchImport extends NetworkConfigItem
     4{
     5  function NetwatchImport()
     6  {
     7    $StartTime = time();
    88
    9 function NetwatchImport()
    10 {
    11   global $System, $Config;
     9    // Load all interfaces to memory
     10    $Interfaces = array();
     11    $DbResult = $this->Database->select('NetworkInterface', '`Id`, `LocalIP` AS `IP`, `Online`, 0 AS `NewOnline`');
     12    while($DbRow = $DbResult->fetch_assoc())
     13      $Interfaces[$DbRow['IP']] = $DbRow;
    1214
    13   $StartTime = time();
     15      // Load netwatch status from all DHCP routers
     16      $DbResult3 = $this->Database->query('SELECT `DHCP`, `AddressRange`, `Mask` FROM `NetworkSubnet` '.
     17          'WHERE (`Configure` = 1) AND (`Member` IS NULL) GROUP BY DHCP');
     18      while($Subnet = $DbResult3->fetch_assoc())
     19      {
     20        echo($Subnet['AddressRange'].'/'.$Subnet['Mask'].' on router '.$Subnet['DHCP']."\n");
     21        $Routerboard = new RouterosAPI();
     22        $Routerboard->Connect($Subnet['DHCP'], $this->System->Config['API']['UserName'],
     23          $this->System->Config['API']['Password']);
     24        if(!$Routerboard->Connected) continue;
     25        $Routerboard->Write('/tool/netwatch/getall', false);
     26        $Routerboard->Write('=.proplist=host,status');
     27        $Read = $Routerboard->Read(false);
     28        $List = $Routerboard->ParseResponse($Read);
     29        foreach($List as $Properties)
     30        {
     31          $IP = $Properties['host'];
     32          if($Properties['status'] == 'up') $Online = 1;
     33          else $Online = 0;
    1434
    15   // Load all interfaces to memory
    16   $Interfaces = array();
    17   $DbResult = $System->Database->select('NetworkInterface', '`Id`, `LocalIP` AS `IP`, `Online`, 0 AS `NewOnline`');
    18   while($DbRow = $DbResult->fetch_assoc())
    19     $Interfaces[$DbRow['IP']] = $DbRow;
     35          if($Online)
     36          {
     37            if(array_key_exists($IP, $Interfaces))
     38              $Interfaces[$IP]['NewOnline'] = 1;
     39              else echo('IP '.$IP.' not found.'."\n");
     40          }
     41        }
     42      }
    2043
    21   // Load netwatch status from all DHCP routers
    22   $DbResult3 = $System->Database->query('SELECT `DHCP`, `AddressRange`, `Mask` FROM `NetworkSubnet` '.
    23     'WHERE (`Configure` = 1) AND (`Member` IS NULL) GROUP BY DHCP');
    24   while($Subnet = $DbResult3->fetch_assoc())
    25   {
    26     echo($Subnet['AddressRange'].'/'.$Subnet['Mask'].' on router '.$Subnet['DHCP']."\n");
    27     $Routerboard = new RouterosAPI();
    28     $Routerboard->Connect($Subnet['DHCP'], $Config['API']['UserName'], $Config['API']['Password']);
    29     if(!$Routerboard->Connected) continue;
    30     $Routerboard->Write('/tool/netwatch/getall', false);
    31     $Routerboard->Write('=.proplist=host,status');
    32     $Read = $Routerboard->Read(false);
    33     $List = $Routerboard->ParseResponse($Read);
    34     foreach($List as $Properties)
    35     {
    36       $IP = $Properties['host'];
    37       if($Properties['status'] == 'up') $Online = 1;
    38         else $Online = 0;
     44      foreach($Interfaces as $Index => $Interface)
     45      {
     46        // Update last online time if still online
     47        if($Interface['NewOnline'])
     48          $DbResult = $this->Database->update('NetworkInterface', '`Id` = "'.$Interface['Id'].'"',
     49              array('LastOnline' => TimeToMysqlDateTime($StartTime)));
    3950
    40       if($Online)
     51          if($Interface['Online'] != $Interface['NewOnline'])
     52          {
     53            // Online state changed
     54            $DbResult = $this->Database->query('INSERT INTO `NetworkInterfaceUpDown` (`Interface`,
     55        `State`, `Time`, `Duration`) VALUES ('.$Interface['Id'].', '.$Interface['NewOnline'].', "'.
     56                TimeToMysqlDateTime($StartTime).'", NULL)');
     57            // Update previous record duration in UpDown table
     58            $System->Database->query('UPDATE `NetworkInterfaceUpDown` AS `TM` SET `Duration` = TIMESTAMPDIFF(SECOND, '.
     59                '`TM`.`Time`, (SELECT `Time` FROM (SELECT * FROM `NetworkInterfaceUpDown`) AS `TA` WHERE (`TA`.`Time` > `TM`.`Time`) '.
     60                'AND (`TA`.`Interface`=`TM`.`Interface`) ORDER BY `TA`.`Time` ASC LIMIT 1)) '.
     61                'WHERE (`TM`.`Duration` IS NULL) AND (`TM`.`Interface` ='.$Interface['Id'].')');
     62            $System->Database->update('NetworkInterface', '`Id` = "'.$Interface['Id'].'"',
     63                array('Online' => $Interface['NewOnline']));
     64          }
     65      }
     66
     67      // Set offline all interfaces which were not updated as online
     68      $DbResult = $this->Database->select('NetworkInterface', '*', '(`Online` = 1) AND '.
     69          '(`LastOnline` < "'.TimeToMysqlDateTime($StartTime).'")');
     70      while($DbRow = $DbResult->fetch_assoc())
    4171      {
    42         if(array_key_exists($IP, $Interfaces))
    43           $Interfaces[$IP]['NewOnline'] = 1;
    44           else echo('IP '.$IP.' not found.'."\n");
     72        echo('IP '.$DbRow['LocalIP'].' online but time not updated.'."\n");
    4573      }
    46     }
     74      $DbResult = $this->Database->select('NetworkInterface', '*', '(`Online` = 0) AND '.
     75          '(`LastOnline` >= "'.TimeToMysqlDateTime($StartTime).'")');
     76      while($DbRow = $DbResult->fetch_assoc())
     77      {
     78        echo('IP '.$DbRow['LocalIP'].' not online but time updated.'."\n");
     79      }
     80
     81      // Update device online state
     82      $DbResult = $this->Database->select('NetworkInterface', '`Device`, SUM(`Online`) AS `SumOnline`', '`Online` = 1 GROUP BY `Device`');
     83      while($Device = $DbResult->fetch_assoc())
     84      {
     85        if($Device['SumOnline'] > 0)
     86          $System->Database->update('NetworkDevice', 'Id='.$Device['Device'], array('LastOnline' => TimeToMysqlDateTime($StartTime), 'Online' => 1));
     87      }
     88      $DbResult = $this->Database->update('NetworkDevice', '`LastOnline` < "'.TimeToMysqlDateTime($StartTime).'"', array('Online' => 0));
     89
     90      // Update interface online statistics
     91      $DbResult = $this->Database->select('NetworkInterface', 'Id', '`Online` = 1');
     92      while($Interface = $DbResult->fetch_assoc())
     93      {
     94        $DbResult2 = $this->Database->select('NetworkInterfaceStat', '*', '(`NetworkInterface`="'.$Interface['Id'].'") AND (`Time` = DATE_FORMAT(NOW(), "%Y-%m-%d %H:00:00"))');
     95        if($DbResult2->num_rows == 0) $System->Database->query('REPLACE INTO `NetworkInterfaceStat` (`NetworkInterface`, `Time`, `PingCount`) VALUES ("'.$Interface['Id'].'", DATE_FORMAT(NOW(), "%Y-%m-%d %H:00:00"), 1)');
     96        else $this->Database->query('UPDATE `NetworkInterfaceStat` SET `PingCount` = `PingCount` + 1 WHERE (`NetworkInterface`="'.$Interface['Id'].'") AND (`Time` = DATE_FORMAT(NOW(), "%Y-%m-%d %H:00:00"))');
     97      }
    4798  }
    4899
    49   foreach($Interfaces as $Index => $Interface)
     100  function Run()
    50101  {
    51     // Update last online time if still online
    52     if($Interface['NewOnline'])
    53       $DbResult = $System->Database->update('NetworkInterface', '`Id` = "'.$Interface['Id'].'"',
    54         array('LastOnline' => TimeToMysqlDateTime($StartTime)));
    55 
    56     if($Interface['Online'] != $Interface['NewOnline'])
    57     {
    58       // Online state changed
    59       $DbResult = $System->Database->query('INSERT INTO `NetworkInterfaceUpDown` (`Interface`,
    60         `State`, `Time`, `Duration`) VALUES ('.$Interface['Id'].', '.$Interface['NewOnline'].', "'.
    61          TimeToMysqlDateTime($StartTime).'", NULL)');
    62       // Update previous record duration in UpDown table
    63       $System->Database->query('UPDATE `NetworkInterfaceUpDown` AS `TM` SET `Duration` = TIMESTAMPDIFF(SECOND, '.
    64       '`TM`.`Time`, (SELECT `Time` FROM (SELECT * FROM `NetworkInterfaceUpDown`) AS `TA` WHERE (`TA`.`Time` > `TM`.`Time`) '.
    65       'AND (`TA`.`Interface`=`TM`.`Interface`) ORDER BY `TA`.`Time` ASC LIMIT 1)) '.
    66       'WHERE (`TM`.`Duration` IS NULL) AND (`TM`.`Interface` ='.$Interface['Id'].')');
    67       $System->Database->update('NetworkInterface', '`Id` = "'.$Interface['Id'].'"',
    68         array('Online' => $Interface['NewOnline']));
    69     }
    70   }
    71 
    72   // Set offline all interfaces which were not updated as online
    73   $DbResult = $System->Database->select('NetworkInterface', '*', '(`Online` = 1) AND '.
    74     '(`LastOnline` < "'.TimeToMysqlDateTime($StartTime).'")');
    75   while($DbRow = $DbResult->fetch_assoc())
    76   {
    77     echo('IP '.$DbRow['LocalIP'].' online but time not updated.'."\n");
    78   }
    79   $DbResult = $System->Database->select('NetworkInterface', '*', '(`Online` = 0) AND '.
    80     '(`LastOnline` >= "'.TimeToMysqlDateTime($StartTime).'")');
    81   while($DbRow = $DbResult->fetch_assoc())
    82   {
    83     echo('IP '.$DbRow['LocalIP'].' not online but time updated.'."\n");
    84   }
    85 
    86   // Update device online state
    87   $DbResult = $System->Database->select('NetworkInterface', '`Device`, SUM(`Online`) AS `SumOnline`', '`Online` = 1 GROUP BY `Device`');
    88   while($Device = $DbResult->fetch_assoc())
    89   {
    90     if($Device['SumOnline'] > 0)
    91       $System->Database->update('NetworkDevice', 'Id='.$Device['Device'], array('LastOnline' => TimeToMysqlDateTime($StartTime), 'Online' => 1));
    92   }
    93   $DbResult = $System->Database->update('NetworkDevice', '`LastOnline` < "'.TimeToMysqlDateTime($StartTime).'"', array('Online' => 0));
    94 
    95   // Update interface online statistics
    96   $DbResult = $System->Database->select('NetworkInterface', 'Id', '`Online` = 1');
    97   while($Interface = $DbResult->fetch_assoc())
    98   {
    99     $DbResult2 = $System->Database->select('NetworkInterfaceStat', '*', '(`NetworkInterface`="'.$Interface['Id'].'") AND (`Time` = DATE_FORMAT(NOW(), "%Y-%m-%d %H:00:00"))');
    100     if($DbResult2->num_rows == 0) $System->Database->query('REPLACE INTO `NetworkInterfaceStat` (`NetworkInterface`, `Time`, `PingCount`) VALUES ("'.$Interface['Id'].'", DATE_FORMAT(NOW(), "%Y-%m-%d %H:00:00"), 1)');
    101       else $System->Database->query('UPDATE `NetworkInterfaceStat` SET `PingCount` = `PingCount` + 1 WHERE (`NetworkInterface`="'.$Interface['Id'].'") AND (`Time` = DATE_FORMAT(NOW(), "%Y-%m-%d %H:00:00"))');
     102    RepeatFunction(60, array($this, 'NetwatchImport'));
    102103  }
    103104}
    104 
    105 RepeatFunction(60, 'NetwatchImport');
  • trunk/Modules/NetworkConfigRouterOS/Generators/Queue.php

    r738 r781  
    11<?php
    2 if(isset($_SERVER['REMOTE_ADDR'])) die();
    32
    4 $Enabled = 1;
    5 $ClassesEnabled = 1;
    6 $SessionDisable = true;
    7 include_once(dirname(__FILE__).'/../../../Application/System.php');
    8 $System = new System();
    9 $System->ShowPage = false;
    10 $System->Run();
    11 $PathQueue = array('queue', 'tree');
     3class ConfigRouterOSQueue extends NetworkConfigItem
     4{
     5  var $UsedNames;
    126
    13 $Routerboard = new Routerboard();
    14 $Routerboard->UserName = $Config['MainRouter']['UserName'];
    15 $Routerboard->Timeout = $Config['MainRouter']['ConnectTimeout'];
    16 $Routerboard->HostName = $Config['MainRouter']['HostName'];
    17 $Routerboard->Debug = true;
     7  function CheckName($Name)
     8  {
     9    if(in_array($Name, $this->UsedNames)) die("\n".'Duplicate name: '.$Name);
     10      else $this->UsedNames[] = $Name;
     11  }
    1812
    19 $UsedNames = array();
     13  function Run()
     14  {
     15    $PathQueue = array('queue', 'tree');
    2016
    21 function CheckName($Name)
    22 {
    23   global $UsedNames;
     17    $Routerboard = new Routerboard();
     18    $Routerboard->UserName = $this->System->Config['MainRouter']['UserName'];
     19    $Routerboard->Timeout = $this->System->Config['MainRouter']['ConnectTimeout'];
     20    $Routerboard->HostName = $this->System->Config['MainRouter']['HostName'];
     21    $Routerboard->Debug = true;
    2422
    25   if(in_array($Name, $UsedNames)) die("\n".'Duplicate name: '.$Name);
    26   else $UsedNames[] = $Name;
    27 }
     23    $this->UsedNames = array();
    2824
    29 $Finance = &$System->Modules['Finance'];
    30 $Finance->LoadMonthParameters(0);
     25    $Finance = &$this->System->Modules['Finance'];
     26    $Finance->LoadMonthParameters(0);
    3127
    32 // Generate traffic shaping rules
    33 //$TotalMaxSpeedIn = 4048; //$RealMaxSpeed; //1536;
    34 //TotalMaxSpeedOut = 3048; //$RealMaxSpeed; //1536;
    35 //$UsersMaxSpeedIn = 1900; //$MaxSpeed;
    36 //$UsersMaxSpeedOut = 1900; //$MaxSpeed;
     28    // Generate traffic shaping rules
     29    //$TotalMaxSpeedIn = 4048; //$RealMaxSpeed; //1536;
     30    //TotalMaxSpeedOut = 3048; //$RealMaxSpeed; //1536;
     31    //$UsersMaxSpeedIn = 1900; //$MaxSpeed;
     32    //$UsersMaxSpeedOut = 1900; //$MaxSpeed;
    3733
    38 $InDivider = 1;
    39 $OutDivider = 1;
    40 $TotalMaxSpeedIn = round($Finance->RealMaxSpeed / $InDivider) * 1000;
    41 $TotalMaxSpeedOut = round($Finance->RealMaxSpeed / $OutDivider) * 1000;
    42 $UsersMaxSpeedIn = round($Finance->MaxSpeed / $InDivider) * 1000;
    43 $UsersMaxSpeedOut = round($Finance->MaxSpeed / $OutDivider) * 1000;
    44 $VoipMaxSpeedIn = $TotalMaxSpeedIn - 136;
    45 $VoipMaxSpeedOut = $TotalMaxSpeedOut - 136;
    46 $VoipSpeedIn = 100; //$SpeedReserve;
    47 $VoipSpeedOut = 100; //$SpeedReserve;
    48 $OutInterface = 'eth1';
    49 $InInterface = 'ifb0';
    50 $InetInterface = $Config['MainRouter']['InetInterface'];
     34    $InDivider = 1;
     35    $OutDivider = 1;
     36    $TotalMaxSpeedIn = round($Finance->RealMaxSpeed / $InDivider) * 1000;
     37    $TotalMaxSpeedOut = round($Finance->RealMaxSpeed / $OutDivider) * 1000;
     38    $UsersMaxSpeedIn = round($Finance->MaxSpeed / $InDivider) * 1000;
     39    $UsersMaxSpeedOut = round($Finance->MaxSpeed / $OutDivider) * 1000;
     40    $VoipMaxSpeedIn = $TotalMaxSpeedIn - 136;
     41    $VoipMaxSpeedOut = $TotalMaxSpeedOut - 136;
     42    $VoipSpeedIn = 100; //$SpeedReserve;
     43    $VoipSpeedOut = 100; //$SpeedReserve;
     44    $OutInterface = 'eth1';
     45    $InInterface = 'ifb0';
     46    $InetInterface = $this->System->Config['MainRouter']['InetInterface'];
    5147
    52 $DbResult = $System->Database->select('Service', '*', '(`ChangeAction` IS NULL) AND (`Id`='.TARIFF_FREE.')');
    53 if($DbResult->num_rows == 1)
    54 {
    55   $Service = $DbResult->fetch_array();
    56   $FreeInetSpeed = $Service['InternetSpeedMax'] * 1000;
    57 } else $FreeInetSpeed = 0;
     48    $DbResult = $this->Database->select('Service', '*', '(`ChangeAction` IS NULL) AND (`Id`='.TARIFF_FREE.')');
     49    if($DbResult->num_rows == 1)
     50    {
     51      $Service = $DbResult->fetch_array();
     52      $FreeInetSpeed = $Service['InternetSpeedMax'] * 1000;
     53    } else $FreeInetSpeed = 0;
    5854
    59 $ItemsQueue = array();
     55    $ItemsQueue = array();
    6056
    61 // Root of tree and main limit
    62 $ItemsQueue[] = array('name' => 'main-out', 'limit-at' => $UsersMaxSpeedIn, 'max-limit' => $UsersMaxSpeedIn, 'parent' => 'global');
    63 $ItemsQueue[] = array('name' => 'main-in', 'limit-at' => $UsersMaxSpeedOut, 'max-limit' => $UsersMaxSpeedOut, 'parent' => 'global');
     57    // Root of tree and main limit
     58    $ItemsQueue[] = array('name' => 'main-out', 'limit-at' => $UsersMaxSpeedIn, 'max-limit' => $UsersMaxSpeedIn, 'parent' => 'global');
     59    $ItemsQueue[] = array('name' => 'main-in', 'limit-at' => $UsersMaxSpeedOut, 'max-limit' => $UsersMaxSpeedOut, 'parent' => 'global');
    6460
    65 // Divide rules by subnet number
    66 $DbResult = $System->Database->query('SELECT `Id`, `Name`, `AddressRange`, `Mask` FROM `NetworkSubnet`');
    67 // Slow free internet
    68 $PacketMark = GetMarkByComment('free-out');
    69 $ItemsQueue[] = array('name' => 'free-out', 'limit-at' => $FreeInetSpeed, 'max-limit' => $FreeInetSpeed, 'parent' => 'main-out', 'packet-mark' => $PacketMark);
    70 $PacketMark = GetMarkByComment('free-in');
    71 $ItemsQueue[] = array('name' => 'free-in', 'limit-at' => $FreeInetSpeed, 'max-limit' => $FreeInetSpeed, 'parent' => 'main-in', 'packet-mark' => $PacketMark);
     61    // Divide rules by subnet number
     62    $DbResult = $this->Database->query('SELECT `Id`, `Name`, `AddressRange`, `Mask` FROM `NetworkSubnet`');
     63    // Slow free internet
     64    $PacketMark = GetMarkByComment('free-out');
     65    $ItemsQueue[] = array('name' => 'free-out', 'limit-at' => $FreeInetSpeed, 'max-limit' => $FreeInetSpeed, 'parent' => 'main-out', 'packet-mark' => $PacketMark);
     66    $PacketMark = GetMarkByComment('free-in');
     67    $ItemsQueue[] = array('name' => 'free-in', 'limit-at' => $FreeInetSpeed, 'max-limit' => $FreeInetSpeed, 'parent' => 'main-in', 'packet-mark' => $PacketMark);
    7268
    73 // Process users
    74 $DbResult = $System->Database->query('SELECT `Member`.*, `Subject`.`Name` FROM `Member` LEFT JOIN `Subject` ON `Subject`.`Id` = `Member`.`Subject` WHERE `Member`.`Blocked`=0');
    75 while($Member = $DbResult->fetch_assoc())
    76 {
    77   $ServiceIndex = 1;
    78   echo('Zákazník '.$Member['Name']."\n");
    79   $DbResult4 = $System->Database->query('SELECT `Service`.*, `ServiceCustomerRel`.`Id` AS `RelId` FROM `ServiceCustomerRel` '.
    80     'JOIN `Service` ON `Service`.`Id` = `ServiceCustomerRel`.`Service` '.
    81     'WHERE (`ServiceCustomerRel`.`Customer` = '.$Member['Id'].') AND (`ServiceCustomerRel`.`ChangeAction` IS NULL) '.
    82     'AND (`Service`.`InternetSpeedMax` > 0) AND (`Service`.`InternetSpeedMin` > 0)');
    83   while($Service = $DbResult4->fetch_assoc())
    84   {
    85     echo('Služba '.$Service['Name'].': ');
    86     $MemberName = RouterOSIdent($Member['Name'].'-'.$Member['Id'].'-'.$ServiceIndex);
    87     $SpeedIn = round($Service['InternetSpeedMin'] / $InDivider) * 1000;
    88     $SpeedOut = round($Service['InternetSpeedMin'] / $OutDivider) * 1000;
    89     $UserMaxSpeedIn = round($Service['InternetSpeedMax'] / $InDivider) * 1000;
    90     $UserMaxSpeedOut = round($Service['InternetSpeedMax'] / $OutDivider) * 1000;
    91     $ItemsQueue[] = array('name' => $MemberName.'-out', 'limit-at' => $SpeedIn, 'max-limit' => $UserMaxSpeedIn, 'parent' => 'main-out');
    92     $ItemsQueue[] = array('name' => $MemberName.'-in', 'limit-at' => $SpeedOut, 'max-limit' => $UserMaxSpeedOut, 'parent' => 'main-in');
    93     CheckName($MemberName.'-out');
    94     CheckName($MemberName.'-in');
     69    // Process users
     70    $DbResult = $this->Database->query('SELECT `Member`.*, `Subject`.`Name` FROM `Member` LEFT JOIN `Subject` ON `Subject`.`Id` = `Member`.`Subject` WHERE `Member`.`Blocked`=0');
     71    while($Member = $DbResult->fetch_assoc())
     72    {
     73      $ServiceIndex = 1;
     74      echo('Zákazník '.$Member['Name']."\n");
     75      $DbResult4 = $this->Database->query('SELECT `Service`.*, `ServiceCustomerRel`.`Id` AS `RelId` FROM `ServiceCustomerRel` '.
     76          'JOIN `Service` ON `Service`.`Id` = `ServiceCustomerRel`.`Service` '.
     77          'WHERE (`ServiceCustomerRel`.`Customer` = '.$Member['Id'].') AND (`ServiceCustomerRel`.`ChangeAction` IS NULL) '.
     78          'AND (`Service`.`InternetSpeedMax` > 0) AND (`Service`.`InternetSpeedMin` > 0)');
     79      while($Service = $DbResult4->fetch_assoc())
     80      {
     81        echo('Služba '.$Service['Name'].': ');
     82        $MemberName = RouterOSIdent($Member['Name'].'-'.$Member['Id'].'-'.$ServiceIndex);
     83        $SpeedIn = round($Service['InternetSpeedMin'] / $InDivider) * 1000;
     84        $SpeedOut = round($Service['InternetSpeedMin'] / $OutDivider) * 1000;
     85        $UserMaxSpeedIn = round($Service['InternetSpeedMax'] / $InDivider) * 1000;
     86        $UserMaxSpeedOut = round($Service['InternetSpeedMax'] / $OutDivider) * 1000;
     87        $ItemsQueue[] = array('name' => $MemberName.'-out', 'limit-at' => $SpeedIn, 'max-limit' => $UserMaxSpeedIn, 'parent' => 'main-out');
     88        $ItemsQueue[] = array('name' => $MemberName.'-in', 'limit-at' => $SpeedOut, 'max-limit' => $UserMaxSpeedOut, 'parent' => 'main-in');
     89        $this->CheckName($MemberName.'-out');
     90        $this->CheckName($MemberName.'-in');
    9591
    96     $Filter = '(`Used` = 1) AND (`Service` = '.$Service['RelId'].')';
    97     $DbResult2 = $System->Database->select('NetworkDevice', 'COUNT(*)', $Filter);
    98     $Row = $DbResult2->fetch_row();
    99     $HostCount = $Row[0];
    100     if($HostCount > 0)
    101     {
    102       $HostSpeedIn = round($SpeedIn / $HostCount);
    103       $HostSpeedOut = round($SpeedOut / $HostCount);
    104     } else
    105     {
    106       $HostSpeedIn = $SpeedIn;
    107       $HostSpeedOut = $SpeedOut;
    108     }
     92        $Filter = '(`Used` = 1) AND (`Service` = '.$Service['RelId'].')';
     93        $DbResult2 = $this->Database->select('NetworkDevice', 'COUNT(*)', $Filter);
     94        $Row = $DbResult2->fetch_row();
     95        $HostCount = $Row[0];
     96        if($HostCount > 0)
     97        {
     98          $HostSpeedIn = round($SpeedIn / $HostCount);
     99          $HostSpeedOut = round($SpeedOut / $HostCount);
     100        } else
     101        {
     102          $HostSpeedIn = $SpeedIn;
     103          $HostSpeedOut = $SpeedOut;
     104        }
    109105
    110     $DbResult2 = $System->Database->select('NetworkDevice', '*', $Filter);
    111     while($Device = $DbResult2->fetch_assoc())
    112     {
    113       $DbResult3 = $System->Database->select('NetworkInterface', '*', '`Device` = '.$Device['Id'].' AND `LocalIP` != ""');
    114       while($Interface = $DbResult3->fetch_assoc())
    115       {
    116         $Name = $Device['Name'];
    117         if($Interface['Name'] != '') $Name .= '-'.$Interface['Name'];
    118         $Name = RouterOSIdent($Name);
    119         echo($Name.', ');
    120         $IPParts = explode('.', $Interface['LocalIP']);
    121         $Subnet = $IPParts[2];
    122         $PacketMark = GetMarkByComment($Name.'-out');
    123         $ItemsQueue[] = array('name' => $Name.'-out', 'limit-at' => $HostSpeedIn, 'max-limit' => $UserMaxSpeedIn, 'parent' => $MemberName.'-out', 'packet-mark' => $PacketMark);
    124         $PacketMark = GetMarkByComment($Name.'-in');
    125         $ItemsQueue[] = array('name' => $Name.'-in', 'limit-at' => $HostSpeedOut, 'max-limit' => $UserMaxSpeedOut, 'parent' => $MemberName.'-in', 'packet-mark' => $PacketMark);
    126         CheckName($Name.'-out');
    127         CheckName($Name.'-in');
     106        $DbResult2 = $this->Database->select('NetworkDevice', '*', $Filter);
     107        while($Device = $DbResult2->fetch_assoc())
     108        {
     109          $DbResult3 = $this->Database->select('NetworkInterface', '*', '`Device` = '.$Device['Id'].' AND `LocalIP` != ""');
     110          while($Interface = $DbResult3->fetch_assoc())
     111          {
     112            $Name = $Device['Name'];
     113            if($Interface['Name'] != '') $Name .= '-'.$Interface['Name'];
     114            $Name = RouterOSIdent($Name);
     115            echo($Name.', ');
     116            $IPParts = explode('.', $Interface['LocalIP']);
     117            $Subnet = $IPParts[2];
     118            $PacketMark = GetMarkByComment($Name.'-out');
     119            $ItemsQueue[] = array('name' => $Name.'-out', 'limit-at' => $HostSpeedIn, 'max-limit' => $UserMaxSpeedIn, 'parent' => $MemberName.'-out', 'packet-mark' => $PacketMark);
     120            $PacketMark = GetMarkByComment($Name.'-in');
     121            $ItemsQueue[] = array('name' => $Name.'-in', 'limit-at' => $HostSpeedOut, 'max-limit' => $UserMaxSpeedOut, 'parent' => $MemberName.'-in', 'packet-mark' => $PacketMark);
     122            $this->CheckName($Name.'-out');
     123            $this->CheckName($Name.'-in');
     124          }
     125        }
     126
     127        $DbResult2 = $this->Database->select('NetworkSubnet', '*', '`Service`='.$Service['RelId']);
     128        while($Subnet = $DbResult2->fetch_assoc())
     129        {
     130          $Subnet['Name'] = RouterOSIdent('subnet-'.$Subnet['Name']);
     131          echo($Subnet['Name'].', ');
     132          $IPParts = explode('.', $Subnet['AddressRange']);
     133          $SubnetNumber = $IPParts[2];
     134          $PacketMark = GetMarkByComment($Subnet['Name'].'-out');
     135          $ItemsQueue[] = array('name' => $Subnet['Name'].'-out', 'limit-at' => $HostSpeedIn, 'max-limit' => $UserMaxSpeedIn, 'parent' => $MemberName.'-out', 'packet-mark' => $PacketMark);
     136          $PacketMark = GetMarkByComment($Subnet['Name'].'-in');
     137          $ItemsQueue[] = array('name' => $Subnet['Name'].'-in', 'limit-at' => $HostSpeedOut, 'max-limit' => $UserMaxSpeedOut, 'parent' => $MemberName.'-in', 'packet-mark' => $PacketMark);
     138          $this->CheckName($Subnet['Name'].'-out');
     139          $this->CheckName($Subnet['Name'].'-in');
     140        }
     141        echo("\n");
     142        $ServiceIndex++;
    128143      }
    129144    }
    130145
    131     $DbResult2 = $System->Database->select('NetworkSubnet', '*', '`Service`='.$Service['RelId']);
    132     while($Subnet = $DbResult2->fetch_assoc())
    133     {
    134       $Subnet['Name'] = RouterOSIdent('subnet-'.$Subnet['Name']);
    135       echo($Subnet['Name'].', ');
    136       $IPParts = explode('.', $Subnet['AddressRange']);
    137       $SubnetNumber = $IPParts[2];
    138       $PacketMark = GetMarkByComment($Subnet['Name'].'-out');
    139       $ItemsQueue[] = array('name' => $Subnet['Name'].'-out', 'limit-at' => $HostSpeedIn, 'max-limit' => $UserMaxSpeedIn, 'parent' => $MemberName.'-out', 'packet-mark' => $PacketMark);
    140       $PacketMark = GetMarkByComment($Subnet['Name'].'-in');
    141       $ItemsQueue[] = array('name' => $Subnet['Name'].'-in', 'limit-at' => $HostSpeedOut, 'max-limit' => $UserMaxSpeedOut, 'parent' => $MemberName.'-in', 'packet-mark' => $PacketMark);
    142       CheckName($Subnet['Name'].'-out');
    143       CheckName($Subnet['Name'].'-in');
    144     }
    145     echo("\n");
    146     $ServiceIndex++;
     146    //print_r($ItemsQueue);
     147    $Routerboard->ListUpdate($PathQueue, array('name', 'limit-at', 'max-limit', 'parent', 'packet-mark'), $ItemsQueue, array(), true);
    147148  }
    148149}
    149 
    150 //print_r($ItemsQueue);
    151 $Routerboard->ListUpdate($PathQueue, array('name', 'limit-at', 'max-limit', 'parent', 'packet-mark'), $ItemsQueue, array(), true);
  • trunk/Modules/NetworkConfigRouterOS/Generators/Signal.php

    r752 r781  
    11<?php
    22
    3 if(array_key_exists('REMOTE_ADDR', $_SERVER)) die();
    4 include_once(dirname(__FILE__).'/../../../Application/System.php');
    5 $System = new System();
    6 $System->ShowPage = false;
    7 $System->Run();
     3class ConfigRouterOSSignal extends NetworkConfigItem
     4{
     5  function ReadWirelessRegistration()
     6  {
     7    $Time = time();
    88
    9 function ReadWirelessRegistration()
    10 {
    11   global $System, $Config;
     9    // Load netwatch status from all DHCP routers
     10    $DbResult3 = $this->Database->query('SELECT `Id`, '.
     11        '(SELECT `LocalIP` FROM `NetworkInterface` WHERE `NetworkInterface`.`Device` = `NetworkDevice`.`Id` LIMIT 1) AS `LocalIP` '.
     12        'FROM `NetworkDevice` WHERE (`API` = 1) AND (`Used` = 1)');
     13    while($Device = $DbResult3->fetch_assoc())
     14    {
     15      echo($Device['LocalIP']."\n");
     16      $Routerboard = new RouterosAPI();
     17      //$Routerboard->SSL = true;
     18      //$Routerboard->Port = 8729;
     19      $Routerboard->Connect($Device['LocalIP'], $this->System->Config['API']['UserName'], $this->System->Config['API']['Password']);
     20      if(!$Routerboard->Connected) continue;
     21      $Routerboard->Write('/interface/wireless/registration-table/getall', false);
     22      $Routerboard->Write('=.proplist=signal-strength,mac-address,rx-rate,tx-rate', false);
     23      $Routerboard->Write('=stats=');
     24      $Read = $Routerboard->Read(false);
     25      $Array = $Routerboard->ParseResponse($Read);
     26      foreach($Array as $Properties)
     27      {
     28        $DbResult = $this->Database->select('NetworkInterface', 'Id', 'MAC="'.$Properties['mac-address'].'"');
     29        if($DbResult->num_rows > 0)
     30        {
     31          $DbRow = $DbResult->fetch_assoc();
     32          $Interface = $DbRow['Id'];
     33        } else $Interface = null;
    1234
    13   $Time = time();
    14 
    15   // Load netwatch status from all DHCP routers
    16   $DbResult3 = $System->Database->query('SELECT `Id`, '.
    17     '(SELECT `LocalIP` FROM `NetworkInterface` WHERE `NetworkInterface`.`Device` = `NetworkDevice`.`Id` LIMIT 1) AS `LocalIP` '.
    18     'FROM `NetworkDevice` WHERE (`API` = 1) AND (`Used` = 1)');
    19   while($Device = $DbResult3->fetch_assoc())
    20   {
    21     echo($Device['LocalIP']."\n");
    22     $Routerboard = new RouterosAPI();
    23     //$Routerboard->SSL = true;
    24     //$Routerboard->Port = 8729;
    25     $Routerboard->Connect($Device['LocalIP'], $Config['API']['UserName'], $Config['API']['Password']);
    26     if(!$Routerboard->Connected) continue;
    27     $Routerboard->Write('/interface/wireless/registration-table/getall', false);
    28     $Routerboard->Write('=.proplist=signal-strength,mac-address,rx-rate,tx-rate', false);
    29     $Routerboard->Write('=stats=');
    30     $Read = $Routerboard->Read(false);
    31     $Array = $Routerboard->ParseResponse($Read);
    32     foreach($Array as $Properties)
    33     {
    34       $DbResult = $System->Database->select('NetworkInterface', 'Id', 'MAC="'.$Properties['mac-address'].'"');
    35       if($DbResult->num_rows > 0)
    36       {
    37         $DbRow = $DbResult->fetch_assoc();
    38         $Interface = $DbRow['Id'];
    39       } else $Interface = null;
    40 
    41       if(strpos($Properties['signal-strength'], '@') === false)
    42       {
    43         $Strength = $Properties['signal-strength'];
    44       } else {
    45         $Parts = explode('@', $Properties['signal-strength']);
    46         if(substr($Parts[0], -3) == 'dBm')
    47           $Strength = substr($Parts[0], 0, -3); // without dBm
    48           else $Strength = $Parts[0];
     35        if(strpos($Properties['signal-strength'], '@') === false)
     36        {
     37          $Strength = $Properties['signal-strength'];
     38        } else {
     39          $Parts = explode('@', $Properties['signal-strength']);
     40          if(substr($Parts[0], -3) == 'dBm')
     41            $Strength = substr($Parts[0], 0, -3); // without dBm
     42            else $Strength = $Parts[0];
     43        }
     44        $RateRx = substr($Properties['rx-rate'], 0, -3); // without MHz
     45        $RateTx = substr($Properties['tx-rate'], 0, -3); // without MHz
     46        $this->Database->insert('NetworkSignal', array('MAC' => $Properties['mac-address'],
     47            'Value' => $Strength, 'RateRx' => $RateRx, 'RateTx' => $RateTx,
     48            'Time' => TimeToMysqlDateTime($Time), 'Interface' => $Interface, 'Device' => $Device['Id']));
     49        /*
     50         $DbResult = $this->Database->select('Measure', 'Id', '`Name` = "'.$Properties['mac-address'].'"');
     51         if($DbResult->num_rows > 0)
     52         {
     53         $this->Database->insert('Measure', array('Name' => $Properties['mac-address']));
     54         $Id = $this->Database->LastInsertId;
     55         } else {
     56         $DbRow = $DbResult->fetch_assoc();
     57         $Id = $DbRow['Id'];
     58         }
     59         $Measure = new Measure($Id);
     60         $Measure->Load($Id);
     61         $Measure->AddValue($Properties['signal-strength']);
     62         */
    4963      }
    50       $RateRx = substr($Properties['rx-rate'], 0, -3); // without MHz
    51       $RateTx = substr($Properties['tx-rate'], 0, -3); // without MHz
    52       $System->Database->insert('NetworkSignal', array('MAC' => $Properties['mac-address'],
    53         'Value' => $Strength, 'RateRx' => $RateRx, 'RateTx' => $RateTx,
    54         'Time' => TimeToMysqlDateTime($Time), 'Interface' => $Interface, 'Device' => $Device['Id']));
    55       /*
    56       $DbResult = $System->Database->select('Measure', 'Id', '`Name` = "'.$Properties['mac-address'].'"');
    57       if($DbResult->num_rows > 0)
    58       {
    59         $System->Database->insert('Measure', array('Name' => $Properties['mac-address']));
    60         $Id = $System->Database->LastInsertId;
    61       } else {
    62         $DbRow = $DbResult->fetch_assoc();
    63         $Id = $DbRow['Id'];
    64       }
    65       $Measure = new Measure($Id);
    66       $Measure->Load($Id);
    67       $Measure->AddValue($Properties['signal-strength']);
    68       */
    6964    }
    7065  }
     66
     67  function Run()
     68  {
     69    RepeatFunction(60 * 60, array($this, 'ReadWirelessRegistration'));
     70  }
    7171}
    72 
    73 RepeatFunction(60 * 60, 'ReadWirelessRegistration');
  • trunk/Modules/NetworkConfigRouterOS/NetworkConfigRouterOS.php

    r738 r781  
    44include_once(dirname(__FILE__).'/RouterboardAPI.php');
    55include_once(dirname(__FILE__).'/Generators/Common.php');
     6
     7// Config actions
     8include_once(dirname(__FILE__).'/Generators/Signal.php');
     9include_once(dirname(__FILE__).'/Generators/DHCP.php');
     10include_once(dirname(__FILE__).'/Generators/DNS.php');
     11include_once(dirname(__FILE__).'/Generators/Netwatch.php');
     12include_once(dirname(__FILE__).'/Generators/NetwatchImport.php');
     13include_once(dirname(__FILE__).'/Generators/FirewallFilter.php');
     14include_once(dirname(__FILE__).'/Generators/FirewallNAT.php');
     15include_once(dirname(__FILE__).'/Generators/FirewallMangle.php');
     16include_once(dirname(__FILE__).'/Generators/Queue.php');
    617
    718class ModuleNetworkConfigRouterOS extends AppModule
     
    4152      ),
    4253    ));
     54
     55    $this->System->ModuleManager->Modules['NetworkConfig']->RegisterConfigItem('routeros-dns', 'ConfigRouterOSDNS');
     56    $this->System->ModuleManager->Modules['NetworkConfig']->RegisterConfigItem('routeros-dhcp', 'ConfigRouterOSDHCP');
     57    $this->System->ModuleManager->Modules['NetworkConfig']->RegisterConfigItem('routeros-signal', 'ConfigRouterOSSignal');
     58    $this->System->ModuleManager->Modules['NetworkConfig']->RegisterConfigItem('routeros-netwatch', 'ConfigRouterOSNetwatch');
     59    $this->System->ModuleManager->Modules['NetworkConfig']->RegisterConfigItem('routeros-netwatch-import', 'ConfigRouterOSNetwatchImport');
     60    $this->System->ModuleManager->Modules['NetworkConfig']->RegisterConfigItem('routeros-firewall-filter', 'ConfigRouterOSFirewallFilter');
     61    $this->System->ModuleManager->Modules['NetworkConfig']->RegisterConfigItem('routeros-firewall-nat', 'ConfigRouterOSFirewallNAT');
     62    $this->System->ModuleManager->Modules['NetworkConfig']->RegisterConfigItem('routeros-firewall-mangle', 'ConfigRouterOSFirewallMangle');
     63    $this->System->ModuleManager->Modules['NetworkConfig']->RegisterConfigItem('routeros-queue', 'ConfigRouterOSQueue');
    4364  }
    4465}
Note: See TracChangeset for help on using the changeset viewer.