sync_mikrotik.pl 44 KB

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