sync_mikrotik.pl 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051
  1. #!/usr/bin/perl
  2. #
  3. # Copyright (C) Roman Dmitriev, rnd@rajven.ru
  4. #
  5. use utf8;
  6. use open ":encoding(utf8)";
  7. use Encode;
  8. no warnings 'utf8';
  9. use English;
  10. use base;
  11. use FindBin '$Bin';
  12. use lib "/opt/Eye/scripts";
  13. use strict;
  14. use Time::Local;
  15. use FileHandle;
  16. use Data::Dumper;
  17. use eyelib::config;
  18. use eyelib::main;
  19. use eyelib::cmd;
  20. use Net::Patricia;
  21. use Date::Parse;
  22. use eyelib::net_utils;
  23. use eyelib::database;
  24. use eyelib::common;
  25. use DBI;
  26. use Fcntl qw(:flock);
  27. use Parallel::ForkManager;
  28. use Net::DNS;
  29. #$debug = 1;
  30. open(SELF,"<",$0) or die "Cannot open $0 - $!";
  31. flock(SELF, LOCK_EX|LOCK_NB) or exit 1;
  32. $|=1;
  33. if (IsNotRun($SPID)) { Add_PID($SPID); } else { die "Warning!!! $SPID already runnning!\n"; }
  34. my $fork_count = $cpu_count*10;
  35. #flag for operation status
  36. my $all_ok = 1;
  37. my @gateways =();
  38. #select undeleted mikrotik routers only
  39. if ($ARGV[0]) {
  40. my $router = get_record_sql($dbh,'SELECT * FROM devices WHERE (device_type=2 OR device_type=0) and protocol>=0 and (user_acl=1 or dhcp=1) and deleted=0 and vendor_id=9 and id=?',$ARGV[0]);
  41. if ($router) { push(@gateways,$router); }
  42. } else {
  43. @gateways = get_records_sql($dbh,'SELECT * FROM devices WHERE (device_type=2 OR device_type=0) and protocol>=0 and (user_acl=1 or dhcp=1) and deleted=0 and vendor_id=9');
  44. }
  45. #все сети организации, работающие по dhcp
  46. my $dhcp_networks = new Net::Patricia;
  47. my %dhcp_conf;
  48. my @subnets=get_records_sql($dbh,'SELECT * FROM subnets WHERE dhcp=1 and office=1 and vpn=0 ORDER BY ip_int_start');
  49. foreach my $subnet (@subnets) {
  50. next if (!$subnet->{gateway});
  51. my $dhcp_info=GetDhcpRange($subnet->{subnet});
  52. $dhcp_networks->add_string($subnet->{subnet},$subnet->{subnet});
  53. $dhcp_conf{$subnet->{subnet}}->{first_pool_ip}=IpToStr($subnet->{dhcp_start});
  54. $dhcp_conf{$subnet->{subnet}}->{last_pool_ip}=IpToStr($subnet->{dhcp_stop});
  55. $dhcp_conf{$subnet->{subnet}}->{relay_ip}=IpToStr($subnet->{gateway});
  56. $dhcp_conf{$subnet->{subnet}}->{gateway}=IpToStr($subnet->{gateway});
  57. #раскрываем подсеть
  58. $dhcp_conf{$subnet->{subnet}}->{network} = $dhcp_info->{network};
  59. $dhcp_conf{$subnet->{subnet}}->{masklen} = $dhcp_info->{masklen};
  60. $dhcp_conf{$subnet->{subnet}}->{first_ip} = $dhcp_info->{first_ip};
  61. $dhcp_conf{$subnet->{subnet}}->{last_ip} = $dhcp_info->{last_ip};
  62. $dhcp_conf{$subnet->{subnet}}->{first_ip_aton}=StrToIp($dhcp_info->{first_ip});
  63. $dhcp_conf{$subnet->{subnet}}->{last_ip_aton}=StrToIp($dhcp_info->{last_ip});
  64. }
  65. my $pm = Parallel::ForkManager->new($fork_count);
  66. #save changed records
  67. my @changes_found = get_records_sql($dbh,"SELECT id FROM user_auth WHERE changed=1");
  68. foreach my $gate (@gateways) {
  69. next if (!$gate);
  70. my $gate_ident = $gate->{device_name}." [$gate->{ip}]:: ";
  71. $pm->start and next;
  72. $dbh = init_db();
  73. my @cmd_list=();
  74. $gate = netdev_set_auth($gate);
  75. $gate->{login}.='+ct400w';
  76. my $t = netdev_login($gate);
  77. if (!$t) {
  78. log_error($gate_ident."Login to $gate->{device_name} [$gate->{ip}] failed! Skip gateway.");
  79. $dbh->disconnect();
  80. $pm->finish;
  81. next;
  82. }
  83. my $router_name=$gate->{device_name};
  84. my $router_ip=$gate->{ip};
  85. my $shaper_enabled = $gate->{queue_enabled};
  86. my $connected_users_only = $gate->{connected_user_only};
  87. my @changed_ref=();
  88. #все сети роутера, которые к нему подключены по информации из БД - Patricia Object
  89. my $connected_users = new Net::Patricia;
  90. #сети, которые должен отдавать роутер по dhcp - simple hash
  91. my %connected_nets_hash;
  92. #исключения из авторизации хот-спота
  93. my %hotspot_exceptions;
  94. my @lan_int=();
  95. my @wan_int=();
  96. my @l3_int = get_records_sql($dbh,'SELECT * FROM device_l3_interfaces WHERE device_id=?',$gate->{'id'});
  97. foreach my $l3 (@l3_int) {
  98. $l3->{'name'}=~s/\"//g;
  99. if ($l3->{'interface_type'} eq '0') { push(@lan_int,$l3->{'name'}); }
  100. if ($l3->{'interface_type'} eq '1') { push(@wan_int,$l3->{'name'}); }
  101. }
  102. #формируем список подключенных к роутеру сетей
  103. my @gw_subnets = get_records_sql($dbh,"SELECT gateway_subnets.*,subnets.subnet FROM gateway_subnets LEFT JOIN subnets ON gateway_subnets.subnet_id = subnets.id WHERE gateway_subnets.device_id=?",$gate->{'id'});
  104. if (@gw_subnets and scalar @gw_subnets) {
  105. foreach my $gw_subnet (@gw_subnets) {
  106. if ($gw_subnet and $gw_subnet->{'subnet'}) {
  107. $connected_users->add_string($gw_subnet->{'subnet'});
  108. $connected_nets_hash{$gw_subnet->{'subnet'}} = $gw_subnet;
  109. }
  110. }
  111. }
  112. #dhcp config
  113. if ($gate->{dhcp}) {
  114. #все сети роутера, которые к нему подключены напрямую фактически - Patricia Object
  115. my $fact_connected_nets = new Net::Patricia;
  116. #интерфейсы, которые будут использоваться для конфигурирования dhcp-сервера
  117. my @work_int=();
  118. #dhcp-сервер, обрабатывающий запросы от dhcp-relay
  119. my @relayed_dhcp = netdev_cmd($gate,$t,"/ip dhcp-server print terse without-paging where relay=255.255.255.255",1);
  120. my $relayed_dhcp_server;
  121. my $relayed_dhcp_interface;
  122. if (@relayed_dhcp and scalar @relayed_dhcp) {
  123. my $dhcp_server = $relayed_dhcp[0];
  124. if ($dhcp_server and $dhcp_server=~/name=(\S+)\s+/i) { $relayed_dhcp_server = $1; }
  125. if ($dhcp_server and $dhcp_server=~/interface=(\S+)\s+/i) { $relayed_dhcp_interface= $1; }
  126. }
  127. #ищем интерфейсы, на которых поднята необходимая для dhcp сервера сеть
  128. foreach my $int (@lan_int) { #interface loop
  129. next if (!$int);
  130. $int=trim($int);
  131. #get ip addr at interface
  132. my @int_addr=netdev_cmd($gate,$t,'/ip address print terse without-paging where interface='.$int,1);
  133. log_debug($gate_ident."Get interfaces: ".Dumper(\@int_addr));
  134. my $found_subnet;
  135. foreach my $int_str(@int_addr) {
  136. $int_str=trim($int_str);
  137. next if (!$int_str);
  138. if ($int_str=~/\s+address=(\S*)\s+/i) {
  139. my $gate_interface=$1;
  140. if ($gate_interface) {
  141. my $gate_ip=$gate_interface;
  142. my $gate_net = GetDhcpRange($gate_interface);
  143. $fact_connected_nets->add_string($gate_net->{network}."/".$gate_net->{masklen});
  144. $gate_ip=~s/\/.*$//;
  145. #search for first match
  146. $found_subnet=$dhcp_networks->match_string($gate_ip);
  147. last;
  148. }
  149. }
  150. }
  151. if (!$found_subnet) { db_log_verbose($dbh,$gate_ident."DHCP subnet for interface $int not found! Skip interface."); next; }
  152. my $dhcp_state;
  153. $dhcp_state->{subnet}=$found_subnet;
  154. $dhcp_state->{interface}=$int;
  155. #формируем список локальных интерфейсов, на котором есть dhcp-сеть
  156. push(@work_int,$dhcp_state);
  157. }
  158. #формируем список сетей, не подключенных к роутеру непосредтственно
  159. my @relayed_subnets=();
  160. foreach my $gw_subnet (keys %connected_nets_hash ) {
  161. next if (!$gw_subnet);
  162. next if ($fact_connected_nets->match_string($gw_subnet));
  163. push(@relayed_subnets,$gw_subnet);
  164. }
  165. if (scalar @relayed_subnets and $relayed_dhcp_interface) {
  166. my $dhcp_state;
  167. $dhcp_state->{interface} = $relayed_dhcp_interface;
  168. $dhcp_state->{subnet} = join(",",@relayed_subnets);
  169. push(@work_int,$dhcp_state);
  170. }
  171. #interface dhcp loop
  172. foreach my $dhcpd_int (@work_int) {
  173. my $found_subnet=$dhcpd_int->{subnet};
  174. my @dhcp_subnets = split(/\,/,$found_subnet);
  175. my $int=$dhcpd_int->{interface};
  176. db_log_verbose($dbh,$gate_ident."Analyze interface $int. Found: ".Dumper($dhcp_conf{$found_subnet}));
  177. #fetch current dhcp records
  178. my @ret_static_leases=netdev_cmd($gate,$t,'/ip dhcp-server lease print terse without-paging where server=dhcp-'.$int,1);
  179. log_debug($gate_ident."Get dhcp leases:".Dumper(\@ret_static_leases));
  180. my @current_static_leases=();
  181. foreach my $str (@ret_static_leases) {
  182. next if (!$str);
  183. $str=trim($str);
  184. if ($str=~/^\d/) {
  185. log_debug($gate_ident."Found current static lease record: ".$str);
  186. push(@current_static_leases,$str);
  187. }
  188. }
  189. #select users for this interface
  190. my @auth_records=();
  191. foreach my $dhcp_subnet (@dhcp_subnets) {
  192. next if (!$dhcp_subnet);
  193. next if (!exists $dhcp_conf{$dhcp_subnet});
  194. my $a_sql = "SELECT * from user_auth WHERE dhcp=1 and ip_int>= ? AND ip_int<= ? and deleted=0 and ou_id != ? and ou_id != ? ORDER BY ip_int");
  195. my @tmp1=get_records_sql($dbh,$a_sql,$dhcp_conf{$dhcp_subnet}->{first_ip_aton},$dhcp_conf{$dhcp_subnet}->{last_ip_aton},$default_user_ou_id, $default_hotspot_ou_id);
  196. push(@auth_records,@tmp1);
  197. undef @tmp1;
  198. }
  199. my %leases;
  200. foreach my $lease (@auth_records) {
  201. next if (!$lease);
  202. next if (!$lease->{mac});
  203. next if (!$lease->{ip});
  204. my $found_subnet = $dhcp_networks->match_string($lease->{ip});
  205. next if (!$found_subnet);
  206. next if ($lease->{ip} eq $dhcp_conf{$found_subnet}->{relay_ip});
  207. $leases{$lease->{ip}}{ip}=$lease->{ip};
  208. $leases{$lease->{ip}}{description}=$lease->{id};
  209. $leases{$lease->{ip}}{id}=$lease->{id};
  210. $leases{$lease->{ip}}{dns_name}=$lease->{dns_name};
  211. if ($lease->{description}) { $leases{$lease->{ip}}{description}=translit($lease->{description}); }
  212. $leases{$lease->{ip}}{mac}=uc(mac_splitted($lease->{mac}));
  213. if ($lease->{dhcp_acl}) {
  214. $leases{$lease->{ip}}{acl}=trim($lease->{dhcp_acl});
  215. $leases{$lease->{ip}}{acl}=~s/;/,/g;
  216. if ($leases{$lease->{ip}}{acl}=~/hotspot\-free/) {
  217. $hotspot_exceptions{$leases{$lease->{ip}}{mac}}=$leases{$lease->{ip}}{mac};
  218. $hotspot_exceptions{$leases{$lease->{ip}}{mac}}=$leases{$lease->{ip}}{description} if ($leases{$lease->{ip}}{description});
  219. }
  220. }
  221. if ($lease->{dhcp_option_set}) {
  222. $leases{$lease->{ip}}{dhcp_option_set}=trim($lease->{dhcp_option_set});
  223. }
  224. $leases{$lease->{ip}}{acl}='' if (!$leases{$lease->{ip}}{acl});
  225. $leases{$lease->{ip}}{dhcp_option_set}='' if (!$leases{$lease->{ip}}{dhcp_option_set});
  226. }
  227. my %active_leases;
  228. foreach my $lease (@current_static_leases) {
  229. my @words = split(/\s+/,$lease);
  230. my %tmp_lease;
  231. if ($lease=~/^(\d*)\s+/) { $tmp_lease{id}=$1; };
  232. next if (!defined($tmp_lease{id}));
  233. foreach my $option (@words) {
  234. next if (!$option);
  235. $option=trim($option);
  236. next if (!$option);
  237. my @tmp = split(/\=/,$option);
  238. my $token = trim($tmp[0]);
  239. my $value = trim($tmp[1]);
  240. next if (!$token);
  241. next if (!$value);
  242. $value=~s/\"//g;
  243. if ($token=~/^address$/i) { $tmp_lease{ip}=GetIP($value); }
  244. if ($token=~/^mac-address$/i) { $tmp_lease{mac}=uc(mac_splitted($value)); }
  245. if ($token=~/^address-lists$/i) { $tmp_lease{acl}=$value; }
  246. if ($token=~/^dhcp-option-set$/i) { $tmp_lease{dhcp_option_set}=$value; }
  247. }
  248. next if (!$tmp_lease{ip});
  249. next if (!$tmp_lease{mac});
  250. next if ($lease=~/^(\d*)\s+D\s+/);
  251. $active_leases{$tmp_lease{ip}}{ip}=$tmp_lease{ip};
  252. $active_leases{$tmp_lease{ip}}{mac}=$tmp_lease{mac};
  253. $active_leases{$tmp_lease{ip}}{id}=$tmp_lease{id};
  254. $active_leases{$tmp_lease{ip}}{acl}='';
  255. $active_leases{$tmp_lease{ip}}{dhcp_option_set}='';
  256. if ($tmp_lease{acl}) {
  257. $active_leases{$tmp_lease{ip}}{acl}=$tmp_lease{acl};
  258. }
  259. if ($tmp_lease{dhcp_option_set}) {
  260. $active_leases{$tmp_lease{ip}}{dhcp_option_set}=$tmp_lease{dhcp_option_set};
  261. }
  262. }
  263. log_debug($gate_ident."Active leases: ".Dumper(\%active_leases));
  264. #sync state
  265. foreach my $ip (keys %active_leases) {
  266. if (!exists $leases{$ip}) {
  267. db_log_verbose($dbh,$gate_ident."Address $ip not found in stat. Remove from router.");
  268. push(@cmd_list,':foreach i in [/ip dhcp-server lease find where address='.$ip.' ] do={/ip dhcp-server lease remove $i};');
  269. push(@cmd_list,'/ip dhcp-server lease remove [find address='.$ip.']');
  270. push(@cmd_list,'/ip arp remove [find address='.$ip.']');
  271. next;
  272. }
  273. if ($leases{$ip}{mac}!~/$active_leases{$ip}{mac}/i) {
  274. db_log_verbose($dbh,$gate_ident."Mac-address mismatch for ip $ip. stat: $leases{$ip}{mac} active: $active_leases{$ip}{mac}. Remove lease from router.");
  275. push(@cmd_list,':foreach i in [/ip dhcp-server lease find where address='.$ip.' ] do={/ip dhcp-server lease remove $i};');
  276. push(@cmd_list,'/ip dhcp-server lease remove [find address='.$ip.']');
  277. push(@cmd_list,'/ip arp remove [find address='.$ip.']');
  278. next;
  279. }
  280. if (!(!$leases{$ip}{acl} and !$active_leases{$ip}{acl}) and $leases{$ip}{acl} ne $active_leases{$ip}{acl}) {
  281. db_log_error($dbh,$gate_ident."Acl mismatch for ip $ip. stat: $leases{$ip}{acl} active: $active_leases{$ip}{acl}. Remove lease from router.");
  282. push(@cmd_list,':foreach i in [/ip dhcp-server lease find where address='.$ip.' ] do={/ip dhcp-server lease remove $i};');
  283. push(@cmd_list,'/ip dhcp-server lease remove [find address='.$ip.']');
  284. push(@cmd_list,'/ip arp remove [find address='.$ip.']');
  285. next;
  286. }
  287. if (!(!$leases{$ip}{dhcp_option_set} and !$active_leases{$ip}{dhcp_option_set}) and $leases{$ip}{dhcp_option_set} ne $active_leases{$ip}{dhcp_option_set}) {
  288. db_log_error($dbh,$gate_ident."DHCP option-set mismatch for ip $ip. stat: $leases{$ip}{dhcp_option_set} active: $active_leases{$ip}{dhcp_option_set}. Remove lease from router.");
  289. push(@cmd_list,':foreach i in [/ip dhcp-server lease find where address='.$ip.' ] do={/ip dhcp-server lease remove $i};');
  290. push(@cmd_list,'/ip dhcp-server lease remove [find address='.$ip.']');
  291. push(@cmd_list,'/ip arp remove [find address='.$ip.']');
  292. next;
  293. }
  294. }
  295. foreach my $ip (keys %leases) {
  296. my $acl='';
  297. if ($leases{$ip}{acl}) { $acl = 'address-lists='.$leases{$ip}{acl}; }
  298. my $dhcp_option_set='';
  299. if ($leases{$ip}{dhcp_option_set}) { $dhcp_option_set = 'dhcp-option-set='.$leases{$ip}{dhcp_option_set}; }
  300. my $description = $leases{$ip}{description};
  301. $description =~s/\=//g;
  302. my $dns_name='';
  303. if ($leases{$ip}{dns_name}) { $dns_name = $leases{$ip}{dns_name}; }
  304. $dns_name =~s/\=//g;
  305. if ($dns_name) { $description = 'description="'.$dns_name." - ".$description.'"'; } else { $description = 'description="'.$description.'"'; }
  306. if (!exists $active_leases{$ip}) {
  307. db_log_verbose($dbh,$gate_ident."Address $ip not found in router. Create static lease record.");
  308. #remove static and dynamic records for mac
  309. push(@cmd_list,':foreach i in [/ip dhcp-server lease find where mac-address='.uc($leases{$ip}{mac}).' ] do={/ip dhcp-server lease remove $i};');
  310. push(@cmd_list,'/ip dhcp-server lease remove [find mac-address='.uc($leases{$ip}{mac}).']');
  311. #remove current ip binding
  312. push(@cmd_list,':foreach i in [/ip dhcp-server lease find where address='.$ip.' ] do={/ip dhcp-server lease remove $i};');
  313. push(@cmd_list,'/ip dhcp-server lease remove [find address='.$ip.']');
  314. #add new bind
  315. push(@cmd_list,'/ip dhcp-server lease add address='.$ip.' mac-address='.$leases{$ip}{mac}.' '.$acl.' '.$dhcp_option_set.' server=dhcp-'.$int.' '.$description);
  316. #clear arp record
  317. push(@cmd_list,'/ip arp remove [find mac-address='.uc($leases{$ip}{mac}).']');
  318. next;
  319. }
  320. if ($leases{$ip}{mac}!~/$active_leases{$ip}{mac}/i) {
  321. db_log_error($dbh,$gate_ident."Mac-address mismatch for ip $ip. stat: $leases{$ip}{mac} active: $active_leases{$ip}{mac}. Create static lease record.");
  322. #remove static and dynamic records for mac
  323. push(@cmd_list,':foreach i in [/ip dhcp-server lease find where mac-address='.uc($leases{$ip}{mac}).' ] do={/ip dhcp-server lease remove $i};');
  324. push(@cmd_list,'/ip dhcp-server lease remove [find mac-address='.uc($leases{$ip}{mac}).']');
  325. #remove current ip binding
  326. push(@cmd_list,':foreach i in [/ip dhcp-server lease find where address='.$ip.' ] do={/ip dhcp-server lease remove $i};');
  327. push(@cmd_list,'/ip dhcp-server lease remove [find address='.$ip.']');
  328. #add new bind
  329. push(@cmd_list,'/ip dhcp-server lease add address='.$ip.' mac-address='.$leases{$ip}{mac}.' '.$acl.' '.$dhcp_option_set.' server=dhcp-'.$int.' '.$description);
  330. #clear arp record
  331. push(@cmd_list,'/ip arp remove [find mac-address='.uc($leases{$ip}{mac}).']');
  332. next;
  333. }
  334. if (!(!$leases{$ip}{acl} and !$active_leases{$ip}{acl}) and $leases{$ip}{acl} ne $active_leases{$ip}{acl}) {
  335. db_log_error($dbh,$gate_ident."Acl mismatch for ip $ip. stat: $leases{$ip}{acl} active: $active_leases{$ip}{acl}. Create static lease record.");
  336. push(@cmd_list,':foreach i in [/ip dhcp-server lease find where mac-address='.uc($leases{$ip}{mac}).' ] do={/ip dhcp-server lease remove $i};');
  337. push(@cmd_list,'/ip dhcp-server lease remove [find mac-address='.uc($leases{$ip}{mac}).']');
  338. push(@cmd_list,'/ip dhcp-server lease add address='.$ip.' mac-address='.$leases{$ip}{mac}.' '.$acl.' '.$dhcp_option_set.' server=dhcp-'.$int.' '.$description);
  339. #clear arp record
  340. push(@cmd_list,'/ip arp remove [find mac-address='.uc($leases{$ip}{mac}).']');
  341. next;
  342. }
  343. if (!(!$leases{$ip}{dhcp_option_set} and !$active_leases{$ip}{dhcp_option_set}) and $leases{$ip}{dhcp_option_set} ne $active_leases{$ip}{dhcp_option_set}) {
  344. db_log_error($dbh,$gate_ident."Acl mismatch for ip $ip. stat: $leases{$ip}{acl} active: $active_leases{$ip}{acl}. Create static lease record.");
  345. push(@cmd_list,':foreach i in [/ip dhcp-server lease find where mac-address='.uc($leases{$ip}{mac}).' ] do={/ip dhcp-server lease remove $i};');
  346. push(@cmd_list,'/ip dhcp-server lease remove [find mac-address='.uc($leases{$ip}{mac}).']');
  347. push(@cmd_list,'/ip dhcp-server lease add address='.$ip.' mac-address='.$leases{$ip}{mac}.' '.$acl.' '.$dhcp_option_set.' server=dhcp-'.$int.' '.$description);
  348. #clear arp record
  349. push(@cmd_list,'/ip arp remove [find mac-address='.uc($leases{$ip}{mac}).']');
  350. next;
  351. }
  352. }
  353. }#end interface dhcp loop
  354. #check hotspot
  355. my @ret_hotspot = netdev_cmd($gate,$t,'/ip hotspot print terse where disabled=no',1);
  356. #if hotspot found - apply exception
  357. if (@ret_hotspot and scalar(@ret_hotspot)) {
  358. #hotspot exceptions
  359. my @ret_hotspot_bindings=netdev_cmd($gate,$t,'/ip hotspot ip-binding print terse without-paging where type=bypassed',1);
  360. my %actual_hotspot_bindings;
  361. foreach my $row (@ret_hotspot_bindings) {
  362. next if (!$row or $row !~ /^\s*\d/);
  363. my %data;
  364. # Используем регулярное выражение для извлечения пар ключ=значение
  365. while ($row =~/\b(\S+?)=([^\s=]+(?:\s(?!\S+=)[^\s=]+)*)/g) {
  366. my ($key, $value) = ($1, $2);
  367. $data{$key} = $value;
  368. }
  369. if (exists $data{'mac-address'}) {
  370. $actual_hotspot_bindings{$data{'mac-address'}} = $data{'mac-address'};
  371. $actual_hotspot_bindings{$data{'mac-address'}} = $data{description} if (exists $data{description});
  372. }
  373. }
  374. log_debug("Actual bindings:".Dumper(\%actual_hotspot_bindings));
  375. log_debug("Configuration exceptions:".Dumper(\%hotspot_exceptions));
  376. #update binding
  377. foreach my $actual_mac (keys %actual_hotspot_bindings) {
  378. if (!exists $hotspot_exceptions{$actual_mac}) {
  379. db_log_info($dbh,$gate_ident."Address $actual_mac removed from hotspot ip-binding");
  380. push(@cmd_list,':foreach i in [/ip hotspot ip-binding find where mac-address='.uc($actual_mac).' ] do={/ip hotspot ip-binding remove $i};');
  381. }
  382. }
  383. foreach my $actual_mac (keys %hotspot_exceptions) {
  384. if (!exists $actual_hotspot_bindings{$actual_mac}) {
  385. db_log_info($dbh,$gate_ident."Address $actual_mac added to hotspot ip-binding");
  386. push(@cmd_list,':foreach i in [/ip hotspot ip-binding find where mac-address='.uc($actual_mac).' ] do={/ip hotspot ip-binding remove $i};');
  387. push(@cmd_list,'/ip hotspot ip-binding add mac-address='.uc($actual_mac).' type=bypassed description="'.$hotspot_exceptions{$actual_mac}.'"');
  388. }
  389. }
  390. }
  391. }#end dhcp config
  392. #access lists config
  393. if ($gate->{user_acl}) {
  394. db_log_verbose($dbh,$gate_ident."Sync user state at router $router_name [".$router_ip."] started.");
  395. #get userid list
  396. my $user_auth_sql="SELECT user_auth.ip, user_auth.filter_group_id, user_auth.queue_id, user_auth.id
  397. FROM user_auth, user_list
  398. WHERE user_auth.user_id = user_list.id
  399. AND user_auth.deleted =0
  400. AND user_auth.enabled =1
  401. AND user_auth.blocked =0
  402. AND user_list.blocked =0
  403. AND user_list.enabled =1
  404. AND user_auth.ou_id <> ?
  405. ORDER BY ip_int";
  406. my @authlist_ref = get_records_sql($dbh,$user_auth_sql,$default_hotspot_ou_id);
  407. my %users;
  408. my %lists;
  409. my %found_users;
  410. foreach my $row (@authlist_ref) {
  411. if ($connected_users_only) { next if (!$connected_users->match_string($row->{ip})); }
  412. #skip not office ip's
  413. next if (!$office_networks->match_string($row->{ip}));
  414. $found_users{$row->{'id'}}=$row->{ip};
  415. #filter group acl's
  416. $users{'group_'.$row->{filter_group_id}}->{$row->{ip}}=1;
  417. $users{'group_all'}->{$row->{ip}}=1;
  418. $lists{'group_'.$row->{filter_group_id}}=1;
  419. #queue acl's
  420. if ($row->{queue_id}) { $users{'queue_'.$row->{queue_id}}->{$row->{ip}}=1; }
  421. }
  422. log_debug($gate_ident."Users status:".Dumper(\%users));
  423. #full list
  424. $lists{'group_all'}=1;
  425. #get queue list
  426. my @queuelist_ref = get_records_sql($dbh,"SELECT * FROM queue_list");
  427. my %queues;
  428. foreach my $row (@queuelist_ref) {
  429. $lists{'queue_'.$row->{id}}=1;
  430. next if ((!$row->{Download}) and !($row->{Upload}));
  431. $queues{'queue_'.$row->{id}}{id}=$row->{id};
  432. $queues{'queue_'.$row->{id}}{down}=$row->{Download};
  433. $queues{'queue_'.$row->{id}}{up}=$row->{Upload};
  434. }
  435. log_debug($gate_ident."Queues status:".Dumper(\%queues));
  436. my @filter_instances = get_records_sql($dbh,"SELECT * FROM filter_instances");
  437. my @filterlist_ref = get_records_sql($dbh,"SELECT * FROM filter_list where filter_type=0");
  438. my %filters;
  439. my %dyn_filters;
  440. my $max_filter_rec = get_record_sql($dbh,"SELECT MAX(id) FROM filter_list");
  441. my $max_filter_id = $max_filter_rec->{id};
  442. my $dyn_filters_base = $max_filter_id+1000;
  443. my $dyn_filters_index = $dyn_filters_base;
  444. foreach my $row (@filterlist_ref) {
  445. #if dst - ip address
  446. if (is_ip($row->{dst})) {
  447. $filters{$row->{id}}->{id}=$row->{id};
  448. $filters{$row->{id}}->{proto}=$row->{proto};
  449. $filters{$row->{id}}->{dst}=$row->{dst};
  450. $filters{$row->{id}}->{dstport}=$row->{dstport};
  451. $filters{$row->{id}}->{srcport}=$row->{srcport};
  452. #set false for dns dst flag
  453. $filters{$row->{id}}->{dns_dst}=0;
  454. } else {
  455. #if dst not ip - check dns record
  456. my @dns_record=ResolveNames($row->{dst},undef);
  457. my $resolved_ips = (scalar @dns_record>0);
  458. next if (!$resolved_ips);
  459. foreach my $resolved_ip (sort @dns_record) {
  460. next if (!$resolved_ip);
  461. #enable dns dst filters
  462. $filters{$row->{id}}->{dns_dst}=1;
  463. #add dynamic dns filter
  464. $filters{$dyn_filters_index}->{id}=$row->{id};
  465. $filters{$dyn_filters_index}->{proto}=$row->{proto};
  466. $filters{$dyn_filters_index}->{dst}=$resolved_ip;
  467. $filters{$dyn_filters_index}->{dstport}=$row->{dstport};
  468. $filters{$dyn_filters_index}->{srcport}=$row->{srcport};
  469. $filters{$dyn_filters_index}->{dns_dst}=0;
  470. #save new filter dns id for original filter id
  471. push(@{$dyn_filters{$row->{id}}},$dyn_filters_index);
  472. $dyn_filters_index++;
  473. }
  474. }
  475. }
  476. log_debug($gate_ident."Filters status:". Dumper(\%filters));
  477. log_debug($gate_ident."DNS-filters status:". Dumper(\%dyn_filters));
  478. #clean unused filter records
  479. do_sql($dbh,"DELETE FROM group_filters WHERE group_id NOT IN (SELECT id FROM group_list)");
  480. do_sql($dbh,"DELETE FROM group_filters WHERE filter_id NOT IN (SELECT id FROM filter_list)");
  481. my @groups_list = get_records_sql($dbh,"SELECT * FROM group_list");
  482. my %groups;
  483. foreach my $group (@groups_list) { $groups{'group_'.$group->{id}}=$group; }
  484. my @grouplist_ref = get_records_sql($dbh,"SELECT group_id,filter_id,rule_order,action FROM group_filters ORDER BY group_filters.group_id,group_filters.rule_order");
  485. my %group_filters;
  486. my $index = 0;
  487. my $cur_group;
  488. foreach my $row (@grouplist_ref) {
  489. if (!$cur_group) { $cur_group = $row->{group_id}; }
  490. if ($cur_group != $row->{group_id}) {
  491. $index = 0;
  492. $cur_group = $row->{group_id};
  493. }
  494. #if dst dns filter not found
  495. if (!$filters{$row->{filter_id}}->{dns_dst}) {
  496. $group_filters{'group_'.$row->{group_id}}->{$index}->{filter_id}=$row->{filter_id};
  497. $group_filters{'group_'.$row->{group_id}}->{$index}->{action}=$row->{action};
  498. $index++;
  499. } else {
  500. #if found dns dst filters - add
  501. if (exists $dyn_filters{$row->{filter_id}}) {
  502. my @dyn_ips = @{$dyn_filters{$row->{filter_id}}};
  503. if (scalar @dyn_ips >0) {
  504. for (my $i = 0; $i < scalar @dyn_ips; $i++) {
  505. $group_filters{'group_'.$row->{group_id}}->{$index}->{filter_id}=$dyn_ips[$i];
  506. $group_filters{'group_'.$row->{group_id}}->{$index}->{action}=$row->{action};
  507. $index++;
  508. }
  509. }
  510. }
  511. }
  512. }
  513. log_debug($gate_ident."Group filters: ".Dumper(\%group_filters));
  514. my %cur_users;
  515. foreach my $group_name (keys %lists) {
  516. my @address_lists=netdev_cmd($gate,$t,'/ip firewall address-list print terse without-paging where list='.$group_name,1);
  517. log_debug($gate_ident."Get address lists:".Dumper(\@address_lists));
  518. foreach my $row (@address_lists) {
  519. $row=trim($row);
  520. next if (!$row);
  521. my @address=split(' ',$row);
  522. foreach my $row (@address) {
  523. if ($row=~/address\=(.*)/i) { $cur_users{$group_name}{$1}=1; }
  524. }
  525. }
  526. }
  527. #new-ips
  528. foreach my $group_name (keys %users) {
  529. foreach my $user_ip (keys %{$users{$group_name}}) {
  530. if (!exists($cur_users{$group_name}{$user_ip})) {
  531. db_log_verbose($dbh,$gate_ident."Add user with ip: $user_ip to access-list $group_name");
  532. push(@cmd_list,"/ip firewall address-list add address=".$user_ip." list=".$group_name);
  533. }
  534. }
  535. }
  536. #old-ips
  537. foreach my $group_name (keys %cur_users) {
  538. foreach my $user_ip (keys %{$cur_users{$group_name}}) {
  539. if (!exists($users{$group_name}{$user_ip})) {
  540. db_log_verbose($dbh,$gate_ident."Remove user with ip: $user_ip from access-list $group_name");
  541. push(@cmd_list,":foreach i in [/ip firewall address-list find where address=".$user_ip." and list=".$group_name."] do={/ip firewall address-list remove \$i};");
  542. }
  543. }
  544. }
  545. timestamp;
  546. #sync firewall rules
  547. #sync group chains
  548. foreach my $filter_instance (@filter_instances) {
  549. my $instance_name = 'Users';
  550. if ($filter_instance->{id}>1) {
  551. $instance_name = 'Users-'.$filter_instance->{name};
  552. #check filter instance exist at gateway
  553. my $instance_ok = get_record_sql($dbh,"SELECT * FROM device_filter_instances WHERE device_id= ? AND instance_id=?", $gate->{'id'}, $filter_instance->{id});
  554. #skip insatnce if not found
  555. if (!$instance_ok) { next; }
  556. }
  557. my @chain_list=netdev_cmd($gate,$t,'/ip firewall filter print terse without-paging where chain='.$instance_name.' and action=jump',1);
  558. log_debug($gate_ident."Get firewall chains:".Dumper(\@chain_list));
  559. my %cur_chain;
  560. foreach my $jump_list (@chain_list) {
  561. next if (!$jump_list);
  562. $jump_list=trim($jump_list);
  563. if ($jump_list=~/jump-target=(\S*)\s+/i) {
  564. if ($1) { $cur_chain{$1}++; }
  565. }
  566. }
  567. #old chains
  568. foreach my $group_name (keys %cur_chain) {
  569. if (!exists($group_filters{$group_name}) or $groups{$group_name}->{instance_id} ne $filter_instance->{id}) {
  570. push (@cmd_list,":foreach i in [/ip firewall filter find where chain=".$instance_name." and action=jump and jump-target=".$group_name."] do={/ip firewall filter remove \$i};");
  571. } else {
  572. if ($cur_chain{$group_name} != 2) {
  573. push (@cmd_list,":foreach i in [/ip firewall filter find where chain=".$instance_name." and action=jump and jump-target=".$group_name."] do={/ip firewall filter remove \$i};");
  574. push (@cmd_list,"/ip firewall filter add chain=".$instance_name." action=jump jump-target=".$group_name." src-address-list=".$group_name);
  575. push (@cmd_list,"/ip firewall filter add chain=".$instance_name." action=jump jump-target=".$group_name." dst-address-list=".$group_name);
  576. }
  577. }
  578. }
  579. #new chains
  580. foreach my $group_name (keys %group_filters) {
  581. if (!exists($cur_chain{$group_name}) and $groups{$group_name}->{instance_id} eq $filter_instance->{id}) {
  582. push (@cmd_list,"/ip firewall filter add chain=".$instance_name." action=jump jump-target=".$group_name." src-address-list=".$group_name);
  583. push (@cmd_list,"/ip firewall filter add chain=".$instance_name." action=jump jump-target=".$group_name." dst-address-list=".$group_name);
  584. }
  585. }
  586. }
  587. my %chain_rules;
  588. foreach my $group_name (sort keys %group_filters) {
  589. next if (!$group_name);
  590. next if (!exists($group_filters{$group_name}));
  591. my %group_filter = %{$group_filters{$group_name}};
  592. foreach my $filter_index (sort keys %group_filter) {
  593. my $filter = $group_filter{$filter_index};
  594. my $filter_id=$filter->{filter_id};
  595. next if (!$filters{$filter_id});
  596. next if ($filters{$filter_id}->{dns_dst});
  597. my $src_rule='chain='.$group_name;
  598. my $dst_rule='chain='.$group_name;
  599. if ($filter->{action}) {
  600. $src_rule=$src_rule." action=accept";
  601. $dst_rule=$dst_rule." action=accept";
  602. } else {
  603. $src_rule=$src_rule." action=reject";
  604. $dst_rule=$dst_rule." action=reject";
  605. }
  606. if ($filters{$filter_id}->{proto} and ($filters{$filter_id}->{proto}!~/all/i)) {
  607. $src_rule=$src_rule." protocol=".$filters{$filter_id}->{proto};
  608. $dst_rule=$dst_rule." protocol=".$filters{$filter_id}->{proto};
  609. }
  610. if ($filters{$filter_id}->{dst} and $filters{$filter_id}->{dst} ne '0/0') {
  611. $src_rule=$src_rule." src-address=".trim($filters{$filter_id}->{dst});
  612. $dst_rule=$dst_rule." dst-address=".trim($filters{$filter_id}->{dst});
  613. }
  614. #dstport and srcport
  615. if (!$filters{$filter_id}->{dstport}) { $filters{$filter_id}->{dstport}=0; }
  616. if (!$filters{$filter_id}->{srcport}) { $filters{$filter_id}->{srcport}=0; }
  617. if ($filters{$filter_id}->{dstport} ne '0' and $filters{$filter_id}->{srcport} ne '0') {
  618. $src_rule=$src_rule." dst-port=".trim($filters{$filter_id}->{srcport})." src-port=".trim($filters{$filter_id}->{dstport});
  619. $dst_rule=$dst_rule." src-port=".trim($filters{$filter_id}->{srcport})." dst-port=".trim($filters{$filter_id}->{dstport});
  620. }
  621. if ($filters{$filter_id}->{dstport} eq '0' and $filters{$filter_id}->{srcport} ne '0') {
  622. $src_rule=$src_rule." dst-port=".trim($filters{$filter_id}->{srcport});
  623. $dst_rule=$dst_rule." src-port=".trim($filters{$filter_id}->{srcport});
  624. }
  625. if ($filters{$filter_id}->{dstport} ne '0' and $filters{$filter_id}->{srcport} eq '0') {
  626. $src_rule=$src_rule." src-port=".trim($filters{$filter_id}->{dstport});
  627. $dst_rule=$dst_rule." dst-port=".trim($filters{$filter_id}->{dstport});
  628. }
  629. if ($src_rule ne $dst_rule) {
  630. push(@{$chain_rules{$group_name}},$src_rule);
  631. push(@{$chain_rules{$group_name}},$dst_rule);
  632. } else {
  633. push(@{$chain_rules{$group_name}},$src_rule);
  634. }
  635. }
  636. }
  637. #chain filters
  638. foreach my $group_name (sort keys %group_filters) {
  639. next if (!$group_name);
  640. my @get_filter=netdev_cmd($gate,$t,'/ip firewall filter print terse without-paging where chain='.$group_name,1);
  641. chomp(@get_filter);
  642. my @cur_filter=();
  643. my $chain_ok=1;
  644. foreach (my $f_index=0; $f_index<scalar(@get_filter); $f_index++) {
  645. my $filter_str=trim($get_filter[$f_index]);
  646. next if (!$filter_str);
  647. next if ($filter_str!~/^(\d){1,3}/);
  648. $filter_str=~s/[^[:ascii:]]//g;
  649. $filter_str=~s/^\d{1,3}\s+//;
  650. $filter_str=trim($filter_str);
  651. next if (!$filter_str);
  652. push(@cur_filter,$filter_str);
  653. }
  654. log_debug($gate_ident."Current filters:".Dumper(\@cur_filter));
  655. log_debug($gate_ident."New filters:".Dumper($chain_rules{$group_name}));
  656. #current state rules
  657. foreach (my $f_index=0; $f_index<scalar(@cur_filter); $f_index++) {
  658. my $filter_str=trim($cur_filter[$f_index]);
  659. if (!$chain_rules{$group_name}[$f_index] or $filter_str!~/$chain_rules{$group_name}[$f_index]/i) {
  660. print "Check chain $group_name error! $filter_str not found in new config. Recreate chain.\n";
  661. $chain_ok=0;
  662. last;
  663. }
  664. }
  665. #new rules
  666. if ($chain_ok and $chain_rules{$group_name} and scalar(@{$chain_rules{$group_name}})) {
  667. foreach (my $f_index=0; $f_index<scalar(@{$chain_rules{$group_name}}); $f_index++) {
  668. my $filter_str=trim($cur_filter[$f_index]);
  669. if (!$filter_str) {
  670. print "Check chain $group_name error! Not found: $chain_rules{$group_name}[$f_index]. Recreate chain.\n";
  671. $chain_ok=0;
  672. last;
  673. }
  674. $filter_str=~s/^\d//;
  675. $filter_str=trim($filter_str);
  676. if ($filter_str!~/$chain_rules{$group_name}[$f_index]/i) {
  677. print "Check chain $group_name error! Expected: $chain_rules{$group_name}[$f_index] Found: $filter_str. Recreate chain.\n";
  678. $chain_ok=0;
  679. last;
  680. }
  681. }
  682. }
  683. if (!$chain_ok) {
  684. push(@cmd_list,":foreach i in [/ip firewall filter find where chain=".$group_name." ] do={/ip firewall filter remove \$i};");
  685. foreach my $filter_str (@{$chain_rules{$group_name}}) {
  686. push(@cmd_list,'/ip firewall filter add '.$filter_str);
  687. }
  688. }
  689. }
  690. if ($shaper_enabled) {
  691. #shapers
  692. my %get_queue_type=();
  693. my %get_queue_tree=();
  694. my %get_filter_mangle=();
  695. my @tmp=netdev_cmd($gate,$t,'/queue type print terse without-paging where name~"pcq_(down|up)load"',1);
  696. log_debug($gate_ident."Get queues: ".Dumper(\@tmp));
  697. # 0 name=pcq_upload_3 kind=pcq pcq-rate=102401k pcq-limit=500KiB pcq-classifier=src-address pcq-total-limit=2000KiB pcq-burst-rate=0 pcq-burst-threshold=0 pcq-burst-time=10s
  698. #pcq-src-address-mask=32 pcq-dst-address-mask=32 pcq-src-address6-mask=64 pcq-dst-address6-mask=64
  699. foreach my $row (@tmp) {
  700. next if (!$row);
  701. $row = trim($row);
  702. next if ($row!~/^(\d){1,3}/);
  703. $row=~s/^\d{1,3}\s+//;
  704. next if (!$row);
  705. if ($row=~/name=pcq_(down|up)load_(\d){1,3}\s+/i) {
  706. next if (!$1);
  707. next if (!$2);
  708. my $direct = $1;
  709. my $index = $2;
  710. $get_queue_type{$index}{$direct}=$row;
  711. if ($row=~/pcq-rate=(\S*)\s+\S/i) {
  712. my $rate = $1;
  713. if ($rate=~/k$/i) { $rate =~s/k$//i; }
  714. $get_queue_type{$index}{$direct."-rate"}=$rate;
  715. }
  716. if ($row=~/pcq-classifier=(\S*)\s+\S/i) { $get_queue_type{$index}{$direct."-classifier"}=$1; }
  717. if ($row=~/pcq-src-address-mask=(\S*)\s+\S/i) { $get_queue_type{$index}{$direct."-src-address-mask"}=$1; }
  718. if ($row=~/pcq-dst-address-mask=(\S*)\s+\S/i) { $get_queue_type{$index}{$direct."-dst-address-mask"}=$1; }
  719. }
  720. }
  721. @tmp=();
  722. @tmp=netdev_cmd($gate,$t,'/queue tree print terse without-paging where parent~"(download|upload)_root"',1);
  723. log_debug($gate_ident."Get root queues: ".Dumper(\@tmp));
  724. #print Dumper(\@tmp);
  725. # 0 I name=queue_3_out parent=upload_root packet-mark=upload_3 limit-at=0 queue=*2A priority=8 max-limit=0 burst-limit=0 burst-threshold=0 burst-time=0s bucket-size=0.1
  726. # 5 I name=queue_3_vlan2_in parent=download_root_vlan2 packet-mark=download_3_vlan2 limit-at=0 queue=*2B priority=8 max-limit=0 burst-limit=0 burst-threshold=0 burst-time=0s bucket-size=0.1
  727. foreach my $row (@tmp) {
  728. next if (!$row);
  729. $row = trim($row);
  730. next if ($row!~/^(\d)/);
  731. $row=~s/^(\d*)\s+//;
  732. next if (!$row);
  733. if ($row=~/queue=pcq_(down|up)load_(\d){1,3}/i) {
  734. if ($row=~/name=queue_(\d){1,3}_(\S*)_out\s+/i) {
  735. next if (!$1);
  736. next if (!$2);
  737. my $index = $1;
  738. my $int_name = $2;
  739. $get_queue_tree{$index}{$int_name}{up}=$row;
  740. if ($row=~/parent=(\S*)\s+\S/i) { $get_queue_tree{$index}{$int_name}{'up-parent'}=$1; }
  741. if ($row=~/packet-mark=(\S*)\s+\S/i) { $get_queue_tree{$index}{$int_name}{'up-mark'}=$1; }
  742. if ($row=~/queue=(\S*)\s+\S/i) { $get_queue_tree{$index}{$int_name}{'up-queue'}=$1; }
  743. }
  744. if ($row=~/name=queue_(\d){1,3}_(\S*)_in\s+/i) {
  745. next if (!$1);
  746. next if (!$2);
  747. my $index = $1;
  748. my $int_name = $2;
  749. $get_queue_tree{$index}{$int_name}{down}=$row;
  750. if ($row=~/parent=(\S*)\s+\S/i) { $get_queue_tree{$index}{$int_name}{'down-parent'}=$1; }
  751. if ($row=~/packet-mark=(\S*)\s+\S/i) { $get_queue_tree{$index}{$int_name}{'down-mark'}=$1; }
  752. if ($row=~/queue=(\S*)\s+\S/i) { $get_queue_tree{$index}{$int_name}{'down-queue'}=$1; }
  753. }
  754. }
  755. }
  756. @tmp=();
  757. @tmp=netdev_cmd($gate,$t,'/ip firewall mangle print terse without-paging where action=mark-packet and new-packet-mark~"(upload|download)_[0-9]{1,3}"',1);
  758. log_debug($gate_ident."Get firewall mangle rules for queues:".Dumper(\@tmp));
  759. # 0 chain=forward action=mark-packet new-packet-mark=upload_0 passthrough=yes src-address-list=queue_0 out-interface=sfp-sfpplus1-wan log=no log-prefix=""
  760. # 0 chain=forward action=mark-packet new-packet-mark=download_3_vlan2 passthrough=yes dst-address-list=queue_3 out-interface=vlan2 in-interface-list=WAN log=no log-prefix=""
  761. foreach my $row (@tmp) {
  762. next if (!$row);
  763. $row = trim($row);
  764. next if ($row!~/^(\d){1,3}/);
  765. $row=~s/^\d{1,3}\s+//;
  766. next if (!$row);
  767. if ($row=~/new-packet-mark=upload_(\d){1,3}_(\S*)\s+/i) {
  768. next if (!$1);
  769. next if (!$2);
  770. my $index = $1;
  771. my $int_name = $2;
  772. $get_filter_mangle{$index}{$int_name}{up}=$row;
  773. if ($row=~/src-address-list=(\S*)\s+\S/i) { $get_filter_mangle{$index}{$int_name}{'up-list'}=$1; }
  774. if ($row=~/out-interface=(\S*)\s+\S/i) { $get_filter_mangle{$index}{$int_name}{'up-dev'}=$1; }
  775. if ($row=~/new-packet-mark=(\S*)\s+\S/i) { $get_filter_mangle{$index}{$int_name}{'up-mark'}=$1; }
  776. }
  777. if ($row=~/new-packet-mark=download_(\d){1,3}_(\S*)\s+/i) {
  778. next if (!$1);
  779. next if (!$2);
  780. my $index = $1;
  781. my $int_name = $2;
  782. $get_filter_mangle{$index}{$int_name}{down}=$row;
  783. if ($row=~/dst-address-list=(\S*)\s+\S/i) { $get_filter_mangle{$index}{$int_name}{'down-list'}=$1; }
  784. if ($row=~/new-packet-mark=(\S*)\s+\S/i) { $get_filter_mangle{$index}{$int_name}{'down-mark'}=$1; }
  785. if ($row=~/out-interface=(\S*)\s+\S/i) { $get_filter_mangle{$index}{$int_name}{'down-dev'}=$1; }
  786. }
  787. }
  788. log_debug($gate_ident."Queues type status:".Dumper(\%get_queue_type));
  789. log_debug($gate_ident."Queues tree status:".Dumper(\%get_queue_tree));
  790. log_debug($gate_ident."Firewall mangle status:".Dumper(\%get_filter_mangle));
  791. my %queue_type;
  792. my %queue_tree;
  793. my %filter_mangle;
  794. #generate new config
  795. foreach my $queue_name (keys %queues) {
  796. my $q_id=$queues{$queue_name}{id};
  797. my $q_up=$queues{$queue_name}{up}+1;
  798. my $q_down=$queues{$queue_name}{down}+1;
  799. #queue_types
  800. $queue_type{$q_id}{up}="name=pcq_upload_".$q_id." kind=pcq pcq-rate=".$q_up."k pcq-limit=500KiB pcq-classifier=src-address pcq-total-limit=2000KiB pcq-burst-rate=0 pcq-burst-threshold=0 pcq-burst-time=10s pcq-src-address-mask=32 pcq-dst-address-mask=32 pcq-src-address6-mask=64 pcq-dst-address6-mask=64";
  801. $queue_type{$q_id}{down}="name=pcq_download_".$q_id." kind=pcq pcq-rate=".$q_down."k pcq-limit=500KiB pcq-classifier=dst-address pcq-total-limit=2000KiB pcq-burst-rate=0 pcq-burst-threshold=0 pcq-burst-time=10s pcq-src-address-mask=32 pcq-dst-address-mask=32 pcq-src-address6-mask=64 pcq-dst-address6-mask=64";
  802. my $queue_ok=1;
  803. if (!$get_queue_type{$q_id}{up}) { $queue_ok=0; }
  804. if ($queue_ok and abs($q_up - $get_queue_type{$q_id}{'up-rate'})>10) { $queue_ok=0; }
  805. if ($queue_ok and $get_queue_type{$q_id}{'up-classifier'}!~/src-address/i) { $queue_ok=0; }
  806. if (!$queue_ok) {
  807. push(@cmd_list,':foreach i in [/queue type find where name~"pcq_upload_'.$q_id.'" ] do={/queue type remove $i};');
  808. push(@cmd_list,'/queue type add '.$queue_type{$q_id}{up});
  809. }
  810. $queue_ok=1;
  811. if (!$get_queue_type{$q_id}{down}) { $queue_ok=0; }
  812. if ($queue_ok and abs($q_up - $get_queue_type{$q_id}{'down-rate'})>10) { $queue_ok=0; }
  813. if ($queue_ok and $get_queue_type{$q_id}{'down-classifier'}!~/dst-address/i) { $queue_ok=0; }
  814. if (!$queue_ok) {
  815. push(@cmd_list,':foreach i in [/queue type find where name~"pcq_download_'.$q_id.'" ] do={/queue type remove $i};');
  816. push(@cmd_list,'/queue type add '.$queue_type{$q_id}{down});
  817. }
  818. #upload queue
  819. foreach my $int (@wan_int) {
  820. $queue_tree{$q_id}{$int}{up}="name=queue_".$q_id."_".$int."_out parent=upload_root_".$int." packet-mark=upload_".$q_id."_".$int." limit-at=0 queue=pcq_upload_".$q_id." priority=8 max-limit=0 burst-limit=0 burst-threshold=0 burst-time=0s bucket-size=0.1";
  821. $filter_mangle{$q_id}{$int}{up}="chain=forward action=mark-packet new-packet-mark=upload_".$q_id."_".$int." passthrough=yes src-address-list=queue_".$q_id." out-interface=".$int." log=no log-prefix=\"\"";
  822. $queue_ok=1;
  823. if (!$get_queue_tree{$q_id}{$int}{up}) { $queue_ok=0; }
  824. if ($queue_ok and ($get_queue_tree{$q_id}{$int}{'up-parent'} ne "upload_root_".$int)) { $queue_ok=0;}
  825. if ($queue_ok and ($get_queue_tree{$q_id}{$int}{'up-mark'} ne "upload_".$q_id."_".$int)) { $queue_ok=0; }
  826. if ($queue_ok and ($get_queue_tree{$q_id}{$int}{'up-queue'} ne "pcq_upload_".$q_id)) { $queue_ok=0; }
  827. if (!$queue_ok) {
  828. push(@cmd_list,':foreach i in [/queue tree find where name~"queue_'.$q_id."_".$int."_out".'" ] do={/queue tree remove $i};');
  829. push(@cmd_list,'/queue tree add '.$queue_tree{$q_id}{$int}{up});
  830. }
  831. $queue_ok=1;
  832. if (!$get_filter_mangle{$q_id}{$int}{up}) { $queue_ok=0; }
  833. if ($queue_ok and ($get_filter_mangle{$q_id}{$int}{'up-mark'} ne "upload_".$q_id."_".$int)) { $queue_ok=0; }
  834. if ($queue_ok and ($get_filter_mangle{$q_id}{$int}{'up-list'} ne "queue_".$q_id)) { $queue_ok=0; }
  835. if ($queue_ok and ($get_filter_mangle{$q_id}{$int}{'up-dev'} ne $int)) { $queue_ok=0; }
  836. if (!$queue_ok) {
  837. push(@cmd_list,':foreach i in [/ip firewall mangle find where action=mark-packet and new-packet-mark~"upload_'.$q_id."_".$int.'" ] do={/ip firewall mangle remove $i};');
  838. push(@cmd_list,'/ip firewall mangle add '.$filter_mangle{$q_id}{$int}{up});
  839. }
  840. }
  841. #download
  842. foreach my $int (@lan_int) {
  843. next if (!$int);
  844. $queue_tree{$q_id}{$int}{down}="name=queue_".$q_id."_".$int."_in parent=download_root_".$int." packet-mark=download_".$q_id."_".$int." limit-at=0 queue=pcq_download_".$q_id." priority=8 max-limit=0 burst-limit=0 burst-threshold=0 burst-time=0s bucket-size=0.1";
  845. $filter_mangle{$q_id}{$int}{down}="chain=forward action=mark-packet new-packet-mark=download_".$q_id."_".$int." passthrough=yes dst-address-list=queue_".$q_id." out-interface=".$int." in-interface-list=WAN log=no log-prefix=\"\"";
  846. $queue_ok=1;
  847. if (!$get_queue_tree{$q_id}{$int}{down}) { $queue_ok=0; }
  848. if ($queue_ok and ($get_queue_tree{$q_id}{$int}{'down-parent'} ne "download_root_".$int)) { $queue_ok=0; }
  849. if ($queue_ok and ($get_queue_tree{$q_id}{$int}{'down-mark'} ne "download_".$q_id."_".$int)) { $queue_ok=0; }
  850. if ($queue_ok and ($get_queue_tree{$q_id}{$int}{'down-queue'} ne "pcq_download_".$q_id)) { $queue_ok=0; }
  851. if (!$queue_ok) {
  852. push(@cmd_list,':foreach i in [/queue tree find where name~"queue_'.$q_id."_".$int."_in".'" ] do={/queue tree remove $i};');
  853. push(@cmd_list,'/queue tree add '.$queue_tree{$q_id}{$int}{down});
  854. }
  855. $queue_ok=1;
  856. if (!$get_filter_mangle{$q_id}{$int}{down}) { $queue_ok=0; }
  857. if ($queue_ok and ($get_filter_mangle{$q_id}{$int}{'down-mark'} ne "download_".$q_id."_".$int)) { $queue_ok=0; }
  858. if ($queue_ok and ($get_filter_mangle{$q_id}{$int}{'down-list'} ne "queue_".$q_id)) { $queue_ok=0; }
  859. if ($queue_ok and ($get_filter_mangle{$q_id}{$int}{'down-dev'} ne $int)) { $queue_ok=0; }
  860. if (!$queue_ok) {
  861. push(@cmd_list,':foreach i in [/ip firewall mangle find where action=mark-packet and new-packet-mark~"download_'.$q_id."_".$int.'" ] do={/ip firewall mangle remove $i};');
  862. push(@cmd_list,'/ip firewall mangle add '.$filter_mangle{$q_id}{$int}{down});
  863. }
  864. }
  865. #end shaper
  866. }
  867. }
  868. }#end access lists config
  869. if (scalar(@cmd_list)) {
  870. log_debug($gate_ident."Apply:");
  871. if ($debug) { foreach my $cmd (@cmd_list) { log_debug($gate_ident."$cmd"); } }
  872. eval {
  873. netdev_cmd($gate,$t,\@cmd_list,1);
  874. };
  875. if ($@) {
  876. $all_ok = 0;
  877. log_debug($gate_ident."Error programming gateway! Err: ".$@);
  878. }
  879. }
  880. db_log_verbose($dbh,$gate_ident."Sync user state stopped.");
  881. $dbh->disconnect();
  882. $pm->finish;
  883. }
  884. $pm->wait_all_children;
  885. #clear changed
  886. if ($all_ok) {
  887. foreach my $row (@changes_found) {
  888. do_sql($dbh,"UPDATE user_auth SET changed=0 WHERE id=?",$row->{id});
  889. }
  890. }
  891. if (IsMyPID($SPID)) { Remove_PID($SPID); };
  892. do_exit 0;