sync_mikrotik.pl 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050
  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 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 @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");
  195. push(@auth_records,@tmp1);
  196. undef @tmp1;
  197. }
  198. my %leases;
  199. foreach my $lease (@auth_records) {
  200. next if (!$lease);
  201. next if (!$lease->{mac});
  202. next if (!$lease->{ip});
  203. my $found_subnet = $dhcp_networks->match_string($lease->{ip});
  204. next if (!$found_subnet);
  205. next if ($lease->{ip} eq $dhcp_conf{$found_subnet}->{relay_ip});
  206. $leases{$lease->{ip}}{ip}=$lease->{ip};
  207. $leases{$lease->{ip}}{comment}=$lease->{id};
  208. $leases{$lease->{ip}}{id}=$lease->{id};
  209. $leases{$lease->{ip}}{dns_name}=$lease->{dns_name};
  210. if ($lease->{comments}) { $leases{$lease->{ip}}{comment}=translit($lease->{comments}); }
  211. $leases{$lease->{ip}}{mac}=uc(mac_splitted($lease->{mac}));
  212. if ($lease->{dhcp_acl}) {
  213. $leases{$lease->{ip}}{acl}=trim($lease->{dhcp_acl});
  214. $leases{$lease->{ip}}{acl}=~s/;/,/g;
  215. if ($leases{$lease->{ip}}{acl}=~/hotspot\-free/) {
  216. $hotspot_exceptions{$leases{$lease->{ip}}{mac}}=$leases{$lease->{ip}}{mac};
  217. $hotspot_exceptions{$leases{$lease->{ip}}{mac}}=$leases{$lease->{ip}}{comment} if ($leases{$lease->{ip}}{comment});
  218. }
  219. }
  220. if ($lease->{dhcp_option_set}) {
  221. $leases{$lease->{ip}}{dhcp_option_set}=trim($lease->{dhcp_option_set});
  222. }
  223. $leases{$lease->{ip}}{acl}='' if (!$leases{$lease->{ip}}{acl});
  224. $leases{$lease->{ip}}{dhcp_option_set}='' if (!$leases{$lease->{ip}}{dhcp_option_set});
  225. }
  226. my %active_leases;
  227. foreach my $lease (@current_static_leases) {
  228. my @words = split(/\s+/,$lease);
  229. my %tmp_lease;
  230. if ($lease=~/^(\d*)\s+/) { $tmp_lease{id}=$1; };
  231. next if (!defined($tmp_lease{id}));
  232. foreach my $option (@words) {
  233. next if (!$option);
  234. $option=trim($option);
  235. next if (!$option);
  236. my @tmp = split(/\=/,$option);
  237. my $token = trim($tmp[0]);
  238. my $value = trim($tmp[1]);
  239. next if (!$token);
  240. next if (!$value);
  241. $value=~s/\"//g;
  242. if ($token=~/^address$/i) { $tmp_lease{ip}=GetIP($value); }
  243. if ($token=~/^mac-address$/i) { $tmp_lease{mac}=uc(mac_splitted($value)); }
  244. if ($token=~/^address-lists$/i) { $tmp_lease{acl}=$value; }
  245. if ($token=~/^dhcp-option-set$/i) { $tmp_lease{dhcp_option_set}=$value; }
  246. }
  247. next if (!$tmp_lease{ip});
  248. next if (!$tmp_lease{mac});
  249. next if ($lease=~/^(\d*)\s+D\s+/);
  250. $active_leases{$tmp_lease{ip}}{ip}=$tmp_lease{ip};
  251. $active_leases{$tmp_lease{ip}}{mac}=$tmp_lease{mac};
  252. $active_leases{$tmp_lease{ip}}{id}=$tmp_lease{id};
  253. $active_leases{$tmp_lease{ip}}{acl}='';
  254. $active_leases{$tmp_lease{ip}}{dhcp_option_set}='';
  255. if ($tmp_lease{acl}) {
  256. $active_leases{$tmp_lease{ip}}{acl}=$tmp_lease{acl};
  257. }
  258. if ($tmp_lease{dhcp_option_set}) {
  259. $active_leases{$tmp_lease{ip}}{dhcp_option_set}=$tmp_lease{dhcp_option_set};
  260. }
  261. }
  262. log_debug($gate_ident."Active leases: ".Dumper(\%active_leases));
  263. #sync state
  264. foreach my $ip (keys %active_leases) {
  265. if (!exists $leases{$ip}) {
  266. db_log_verbose($dbh,$gate_ident."Address $ip not found in stat. Remove from router.");
  267. push(@cmd_list,':foreach i in [/ip dhcp-server lease find where address='.$ip.' ] do={/ip dhcp-server lease remove $i};');
  268. push(@cmd_list,'/ip dhcp-server lease remove [find address='.$ip.']');
  269. push(@cmd_list,'/ip arp remove [find address='.$ip.']');
  270. next;
  271. }
  272. if ($leases{$ip}{mac}!~/$active_leases{$ip}{mac}/i) {
  273. 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.");
  274. push(@cmd_list,':foreach i in [/ip dhcp-server lease find where address='.$ip.' ] do={/ip dhcp-server lease remove $i};');
  275. push(@cmd_list,'/ip dhcp-server lease remove [find address='.$ip.']');
  276. push(@cmd_list,'/ip arp remove [find address='.$ip.']');
  277. next;
  278. }
  279. if (!(!$leases{$ip}{acl} and !$active_leases{$ip}{acl}) and $leases{$ip}{acl} ne $active_leases{$ip}{acl}) {
  280. db_log_error($dbh,$gate_ident."Acl mismatch for ip $ip. stat: $leases{$ip}{acl} active: $active_leases{$ip}{acl}. Remove lease from router.");
  281. push(@cmd_list,':foreach i in [/ip dhcp-server lease find where address='.$ip.' ] do={/ip dhcp-server lease remove $i};');
  282. push(@cmd_list,'/ip dhcp-server lease remove [find address='.$ip.']');
  283. push(@cmd_list,'/ip arp remove [find address='.$ip.']');
  284. next;
  285. }
  286. 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}) {
  287. 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.");
  288. push(@cmd_list,':foreach i in [/ip dhcp-server lease find where address='.$ip.' ] do={/ip dhcp-server lease remove $i};');
  289. push(@cmd_list,'/ip dhcp-server lease remove [find address='.$ip.']');
  290. push(@cmd_list,'/ip arp remove [find address='.$ip.']');
  291. next;
  292. }
  293. }
  294. foreach my $ip (keys %leases) {
  295. my $acl='';
  296. if ($leases{$ip}{acl}) { $acl = 'address-lists='.$leases{$ip}{acl}; }
  297. my $dhcp_option_set='';
  298. if ($leases{$ip}{dhcp_option_set}) { $dhcp_option_set = 'dhcp-option-set='.$leases{$ip}{dhcp_option_set}; }
  299. my $comment = $leases{$ip}{comment};
  300. $comment =~s/\=//g;
  301. my $dns_name='';
  302. if ($leases{$ip}{dns_name}) { $dns_name = $leases{$ip}{dns_name}; }
  303. $dns_name =~s/\=//g;
  304. if ($dns_name) { $comment = 'comment="'.$dns_name." - ".$comment.'"'; } else { $comment = 'comment="'.$comment.'"'; }
  305. if (!exists $active_leases{$ip}) {
  306. db_log_verbose($dbh,$gate_ident."Address $ip not found in router. Create static lease record.");
  307. #remove static and dynamic records for mac
  308. 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};');
  309. push(@cmd_list,'/ip dhcp-server lease remove [find mac-address='.uc($leases{$ip}{mac}).']');
  310. #remove current ip binding
  311. push(@cmd_list,':foreach i in [/ip dhcp-server lease find where address='.$ip.' ] do={/ip dhcp-server lease remove $i};');
  312. push(@cmd_list,'/ip dhcp-server lease remove [find address='.$ip.']');
  313. #add new bind
  314. push(@cmd_list,'/ip dhcp-server lease add address='.$ip.' mac-address='.$leases{$ip}{mac}.' '.$acl.' '.$dhcp_option_set.' server=dhcp-'.$int.' '.$comment);
  315. #clear arp record
  316. push(@cmd_list,'/ip arp remove [find mac-address='.uc($leases{$ip}{mac}).']');
  317. next;
  318. }
  319. if ($leases{$ip}{mac}!~/$active_leases{$ip}{mac}/i) {
  320. 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.");
  321. #remove static and dynamic records for mac
  322. 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};');
  323. push(@cmd_list,'/ip dhcp-server lease remove [find mac-address='.uc($leases{$ip}{mac}).']');
  324. #remove current ip binding
  325. push(@cmd_list,':foreach i in [/ip dhcp-server lease find where address='.$ip.' ] do={/ip dhcp-server lease remove $i};');
  326. push(@cmd_list,'/ip dhcp-server lease remove [find address='.$ip.']');
  327. #add new bind
  328. push(@cmd_list,'/ip dhcp-server lease add address='.$ip.' mac-address='.$leases{$ip}{mac}.' '.$acl.' '.$dhcp_option_set.' server=dhcp-'.$int.' '.$comment);
  329. #clear arp record
  330. push(@cmd_list,'/ip arp remove [find mac-address='.uc($leases{$ip}{mac}).']');
  331. next;
  332. }
  333. if (!(!$leases{$ip}{acl} and !$active_leases{$ip}{acl}) and $leases{$ip}{acl} ne $active_leases{$ip}{acl}) {
  334. db_log_error($dbh,$gate_ident."Acl mismatch for ip $ip. stat: $leases{$ip}{acl} active: $active_leases{$ip}{acl}. Create static lease record.");
  335. 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};');
  336. push(@cmd_list,'/ip dhcp-server lease remove [find mac-address='.uc($leases{$ip}{mac}).']');
  337. push(@cmd_list,'/ip dhcp-server lease add address='.$ip.' mac-address='.$leases{$ip}{mac}.' '.$acl.' '.$dhcp_option_set.' server=dhcp-'.$int.' '.$comment);
  338. #clear arp record
  339. push(@cmd_list,'/ip arp remove [find mac-address='.uc($leases{$ip}{mac}).']');
  340. next;
  341. }
  342. 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}) {
  343. db_log_error($dbh,$gate_ident."Acl mismatch for ip $ip. stat: $leases{$ip}{acl} active: $active_leases{$ip}{acl}. Create static lease record.");
  344. 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};');
  345. push(@cmd_list,'/ip dhcp-server lease remove [find mac-address='.uc($leases{$ip}{mac}).']');
  346. push(@cmd_list,'/ip dhcp-server lease add address='.$ip.' mac-address='.$leases{$ip}{mac}.' '.$acl.' '.$dhcp_option_set.' server=dhcp-'.$int.' '.$comment);
  347. #clear arp record
  348. push(@cmd_list,'/ip arp remove [find mac-address='.uc($leases{$ip}{mac}).']');
  349. next;
  350. }
  351. }
  352. }#end interface dhcp loop
  353. #check hotspot
  354. my @ret_hotspot = netdev_cmd($gate,$t,'/ip hotspot print terse where disabled=no',1);
  355. #if hotspot found - apply exception
  356. if (@ret_hotspot and scalar(@ret_hotspot)) {
  357. #hotspot exceptions
  358. my @ret_hotspot_bindings=netdev_cmd($gate,$t,'/ip hotspot ip-binding print terse without-paging where type=bypassed',1);
  359. my %actual_hotspot_bindings;
  360. foreach my $row (@ret_hotspot_bindings) {
  361. next if (!$row or $row !~ /^\s*\d/);
  362. my %data;
  363. # Используем регулярное выражение для извлечения пар ключ=значение
  364. while ($row =~/\b(\S+?)=([^\s=]+(?:\s(?!\S+=)[^\s=]+)*)/g) {
  365. my ($key, $value) = ($1, $2);
  366. $data{$key} = $value;
  367. }
  368. if (exists $data{'mac-address'}) {
  369. $actual_hotspot_bindings{$data{'mac-address'}} = $data{'mac-address'};
  370. $actual_hotspot_bindings{$data{'mac-address'}} = $data{comment} if (exists $data{comment});
  371. }
  372. }
  373. log_debug("Actual bindings:".Dumper(\%actual_hotspot_bindings));
  374. log_debug("Configuration exceptions:".Dumper(\%hotspot_exceptions));
  375. #update binding
  376. foreach my $actual_mac (keys %actual_hotspot_bindings) {
  377. if (!exists $hotspot_exceptions{$actual_mac}) {
  378. db_log_info($dbh,$gate_ident."Address $actual_mac removed from hotspot ip-binding");
  379. push(@cmd_list,':foreach i in [/ip hotspot ip-binding find where mac-address='.uc($actual_mac).' ] do={/ip hotspot ip-binding remove $i};');
  380. }
  381. }
  382. foreach my $actual_mac (keys %hotspot_exceptions) {
  383. if (!exists $actual_hotspot_bindings{$actual_mac}) {
  384. db_log_info($dbh,$gate_ident."Address $actual_mac added to hotspot ip-binding");
  385. push(@cmd_list,':foreach i in [/ip hotspot ip-binding find where mac-address='.uc($actual_mac).' ] do={/ip hotspot ip-binding remove $i};');
  386. push(@cmd_list,'/ip hotspot ip-binding add mac-address='.uc($actual_mac).' type=bypassed comment="'.$hotspot_exceptions{$actual_mac}.'"');
  387. }
  388. }
  389. }
  390. }#end dhcp config
  391. #access lists config
  392. if ($gate->{user_acl}) {
  393. db_log_verbose($dbh,$gate_ident."Sync user state at router $router_name [".$router_ip."] started.");
  394. #get userid list
  395. my $user_auth_sql="SELECT User_auth.ip, User_auth.filter_group_id, User_auth.queue_id, User_auth.id
  396. FROM User_auth, User_list
  397. WHERE User_auth.user_id = User_list.id
  398. AND User_auth.deleted =0
  399. AND User_auth.enabled =1
  400. AND User_auth.blocked =0
  401. AND User_list.blocked =0
  402. AND User_list.enabled =1
  403. AND User_auth.ou_id <> $default_hotspot_ou_id
  404. ORDER BY ip_int";
  405. my @authlist_ref = get_records_sql($dbh,$user_auth_sql);
  406. my %users;
  407. my %lists;
  408. my %found_users;
  409. foreach my $row (@authlist_ref) {
  410. if ($connected_users_only) { next if (!$connected_users->match_string($row->{ip})); }
  411. #skip not office ip's
  412. next if (!$office_networks->match_string($row->{ip}));
  413. $found_users{$row->{'id'}}=$row->{ip};
  414. #filter group acl's
  415. $users{'group_'.$row->{filter_group_id}}->{$row->{ip}}=1;
  416. $users{'group_all'}->{$row->{ip}}=1;
  417. $lists{'group_'.$row->{filter_group_id}}=1;
  418. #queue acl's
  419. if ($row->{queue_id}) { $users{'queue_'.$row->{queue_id}}->{$row->{ip}}=1; }
  420. }
  421. log_debug($gate_ident."Users status:".Dumper(\%users));
  422. #full list
  423. $lists{'group_all'}=1;
  424. #get queue list
  425. my @queuelist_ref = get_records_sql($dbh,"SELECT * FROM Queue_list");
  426. my %queues;
  427. foreach my $row (@queuelist_ref) {
  428. $lists{'queue_'.$row->{id}}=1;
  429. next if ((!$row->{Download}) and !($row->{Upload}));
  430. $queues{'queue_'.$row->{id}}{id}=$row->{id};
  431. $queues{'queue_'.$row->{id}}{down}=$row->{Download};
  432. $queues{'queue_'.$row->{id}}{up}=$row->{Upload};
  433. }
  434. log_debug($gate_ident."Queues status:".Dumper(\%queues));
  435. my @filter_instances = get_records_sql($dbh,"SELECT * FROM filter_instances");
  436. my @filterlist_ref = get_records_sql($dbh,"SELECT * FROM Filter_list where type=0");
  437. my %filters;
  438. my %dyn_filters;
  439. my $max_filter_rec = get_record_sql($dbh,"SELECT MAX(id) FROM Filter_list");
  440. my $max_filter_id = $max_filter_rec->{id};
  441. my $dyn_filters_base = $max_filter_id+1000;
  442. my $dyn_filters_index = $dyn_filters_base;
  443. foreach my $row (@filterlist_ref) {
  444. #if dst - ip address
  445. if (is_ip($row->{dst})) {
  446. $filters{$row->{id}}->{id}=$row->{id};
  447. $filters{$row->{id}}->{proto}=$row->{proto};
  448. $filters{$row->{id}}->{dst}=$row->{dst};
  449. $filters{$row->{id}}->{dstport}=$row->{dstport};
  450. $filters{$row->{id}}->{srcport}=$row->{srcport};
  451. #set false for dns dst flag
  452. $filters{$row->{id}}->{dns_dst}=0;
  453. } else {
  454. #if dst not ip - check dns record
  455. my @dns_record=ResolveNames($row->{dst},undef);
  456. my $resolved_ips = (scalar @dns_record>0);
  457. next if (!$resolved_ips);
  458. foreach my $resolved_ip (sort @dns_record) {
  459. next if (!$resolved_ip);
  460. #enable dns dst filters
  461. $filters{$row->{id}}->{dns_dst}=1;
  462. #add dynamic dns filter
  463. $filters{$dyn_filters_index}->{id}=$row->{id};
  464. $filters{$dyn_filters_index}->{proto}=$row->{proto};
  465. $filters{$dyn_filters_index}->{dst}=$resolved_ip;
  466. $filters{$dyn_filters_index}->{dstport}=$row->{dstport};
  467. $filters{$dyn_filters_index}->{srcport}=$row->{srcport};
  468. $filters{$dyn_filters_index}->{dns_dst}=0;
  469. #save new filter dns id for original filter id
  470. push(@{$dyn_filters{$row->{id}}},$dyn_filters_index);
  471. $dyn_filters_index++;
  472. }
  473. }
  474. }
  475. log_debug($gate_ident."Filters status:". Dumper(\%filters));
  476. log_debug($gate_ident."DNS-filters status:". Dumper(\%dyn_filters));
  477. #clean unused filter records
  478. do_sql($dbh,"DELETE FROM Group_filters WHERE group_id NOT IN (SELECT id FROM Group_list)");
  479. do_sql($dbh,"DELETE FROM Group_filters WHERE filter_id NOT IN (SELECT id FROM Filter_list)");
  480. my @groups_list = get_records_sql($dbh,"SELECT * FROM Group_list");
  481. my %groups;
  482. foreach my $group (@groups_list) { $groups{'group_'.$group->{id}}=$group; }
  483. 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");
  484. my %group_filters;
  485. my $index = 0;
  486. my $cur_group;
  487. foreach my $row (@grouplist_ref) {
  488. if (!$cur_group) { $cur_group = $row->{group_id}; }
  489. if ($cur_group != $row->{group_id}) {
  490. $index = 0;
  491. $cur_group = $row->{group_id};
  492. }
  493. #if dst dns filter not found
  494. if (!$filters{$row->{filter_id}}->{dns_dst}) {
  495. $group_filters{'group_'.$row->{group_id}}->{$index}->{filter_id}=$row->{filter_id};
  496. $group_filters{'group_'.$row->{group_id}}->{$index}->{action}=$row->{action};
  497. $index++;
  498. } else {
  499. #if found dns dst filters - add
  500. if (exists $dyn_filters{$row->{filter_id}}) {
  501. my @dyn_ips = @{$dyn_filters{$row->{filter_id}}};
  502. if (scalar @dyn_ips >0) {
  503. for (my $i = 0; $i < scalar @dyn_ips; $i++) {
  504. $group_filters{'group_'.$row->{group_id}}->{$index}->{filter_id}=$dyn_ips[$i];
  505. $group_filters{'group_'.$row->{group_id}}->{$index}->{action}=$row->{action};
  506. $index++;
  507. }
  508. }
  509. }
  510. }
  511. }
  512. log_debug($gate_ident."Group filters: ".Dumper(\%group_filters));
  513. my %cur_users;
  514. foreach my $group_name (keys %lists) {
  515. my @address_lists=netdev_cmd($gate,$t,'/ip firewall address-list print terse without-paging where list='.$group_name,1);
  516. log_debug($gate_ident."Get address lists:".Dumper(\@address_lists));
  517. foreach my $row (@address_lists) {
  518. $row=trim($row);
  519. next if (!$row);
  520. my @address=split(' ',$row);
  521. foreach my $row (@address) {
  522. if ($row=~/address\=(.*)/i) { $cur_users{$group_name}{$1}=1; }
  523. }
  524. }
  525. }
  526. #new-ips
  527. foreach my $group_name (keys %users) {
  528. foreach my $user_ip (keys %{$users{$group_name}}) {
  529. if (!exists($cur_users{$group_name}{$user_ip})) {
  530. db_log_verbose($dbh,$gate_ident."Add user with ip: $user_ip to access-list $group_name");
  531. push(@cmd_list,"/ip firewall address-list add address=".$user_ip." list=".$group_name);
  532. }
  533. }
  534. }
  535. #old-ips
  536. foreach my $group_name (keys %cur_users) {
  537. foreach my $user_ip (keys %{$cur_users{$group_name}}) {
  538. if (!exists($users{$group_name}{$user_ip})) {
  539. db_log_verbose($dbh,$gate_ident."Remove user with ip: $user_ip from access-list $group_name");
  540. 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};");
  541. }
  542. }
  543. }
  544. timestamp;
  545. #sync firewall rules
  546. #sync group chains
  547. foreach my $filter_instance (@filter_instances) {
  548. my $instance_name = 'Users';
  549. if ($filter_instance->{id}>1) {
  550. $instance_name = 'Users-'.$filter_instance->{name};
  551. #check filter instance exist at gateway
  552. my $instance_ok = get_record_sql($dbh,"SELECT * FROM device_filter_instances WHERE device_id=$gate->{'id'} AND instance_id=$filter_instance->{id}");
  553. #skip insatnce if not found
  554. if (!$instance_ok) { next; }
  555. }
  556. my @chain_list=netdev_cmd($gate,$t,'/ip firewall filter print terse without-paging where chain='.$instance_name.' and action=jump',1);
  557. log_debug($gate_ident."Get firewall chains:".Dumper(\@chain_list));
  558. my %cur_chain;
  559. foreach my $jump_list (@chain_list) {
  560. next if (!$jump_list);
  561. $jump_list=trim($jump_list);
  562. if ($jump_list=~/jump-target=(\S*)\s+/i) {
  563. if ($1) { $cur_chain{$1}++; }
  564. }
  565. }
  566. #old chains
  567. foreach my $group_name (keys %cur_chain) {
  568. if (!exists($group_filters{$group_name}) or $groups{$group_name}->{instance_id} ne $filter_instance->{id}) {
  569. 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};");
  570. } else {
  571. if ($cur_chain{$group_name} != 2) {
  572. 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};");
  573. push (@cmd_list,"/ip firewall filter add chain=".$instance_name." action=jump jump-target=".$group_name." src-address-list=".$group_name);
  574. push (@cmd_list,"/ip firewall filter add chain=".$instance_name." action=jump jump-target=".$group_name." dst-address-list=".$group_name);
  575. }
  576. }
  577. }
  578. #new chains
  579. foreach my $group_name (keys %group_filters) {
  580. if (!exists($cur_chain{$group_name}) and $groups{$group_name}->{instance_id} eq $filter_instance->{id}) {
  581. push (@cmd_list,"/ip firewall filter add chain=".$instance_name." action=jump jump-target=".$group_name." src-address-list=".$group_name);
  582. push (@cmd_list,"/ip firewall filter add chain=".$instance_name." action=jump jump-target=".$group_name." dst-address-list=".$group_name);
  583. }
  584. }
  585. }
  586. my %chain_rules;
  587. foreach my $group_name (sort keys %group_filters) {
  588. next if (!$group_name);
  589. next if (!exists($group_filters{$group_name}));
  590. my %group_filter = %{$group_filters{$group_name}};
  591. foreach my $filter_index (sort keys %group_filter) {
  592. my $filter = $group_filter{$filter_index};
  593. my $filter_id=$filter->{filter_id};
  594. next if (!$filters{$filter_id});
  595. next if ($filters{$filter_id}->{dns_dst});
  596. my $src_rule='chain='.$group_name;
  597. my $dst_rule='chain='.$group_name;
  598. if ($filter->{action}) {
  599. $src_rule=$src_rule." action=accept";
  600. $dst_rule=$dst_rule." action=accept";
  601. } else {
  602. $src_rule=$src_rule." action=reject";
  603. $dst_rule=$dst_rule." action=reject";
  604. }
  605. if ($filters{$filter_id}->{proto} and ($filters{$filter_id}->{proto}!~/all/i)) {
  606. $src_rule=$src_rule." protocol=".$filters{$filter_id}->{proto};
  607. $dst_rule=$dst_rule." protocol=".$filters{$filter_id}->{proto};
  608. }
  609. if ($filters{$filter_id}->{dst} and $filters{$filter_id}->{dst} ne '0/0') {
  610. $src_rule=$src_rule." src-address=".trim($filters{$filter_id}->{dst});
  611. $dst_rule=$dst_rule." dst-address=".trim($filters{$filter_id}->{dst});
  612. }
  613. #dstport and srcport
  614. if (!$filters{$filter_id}->{dstport}) { $filters{$filter_id}->{dstport}=0; }
  615. if (!$filters{$filter_id}->{srcport}) { $filters{$filter_id}->{srcport}=0; }
  616. if ($filters{$filter_id}->{dstport} ne '0' and $filters{$filter_id}->{srcport} ne '0') {
  617. $src_rule=$src_rule." dst-port=".trim($filters{$filter_id}->{srcport})." src-port=".trim($filters{$filter_id}->{dstport});
  618. $dst_rule=$dst_rule." src-port=".trim($filters{$filter_id}->{srcport})." dst-port=".trim($filters{$filter_id}->{dstport});
  619. }
  620. if ($filters{$filter_id}->{dstport} eq '0' and $filters{$filter_id}->{srcport} ne '0') {
  621. $src_rule=$src_rule." dst-port=".trim($filters{$filter_id}->{srcport});
  622. $dst_rule=$dst_rule." src-port=".trim($filters{$filter_id}->{srcport});
  623. }
  624. if ($filters{$filter_id}->{dstport} ne '0' and $filters{$filter_id}->{srcport} eq '0') {
  625. $src_rule=$src_rule." src-port=".trim($filters{$filter_id}->{dstport});
  626. $dst_rule=$dst_rule." dst-port=".trim($filters{$filter_id}->{dstport});
  627. }
  628. if ($src_rule ne $dst_rule) {
  629. push(@{$chain_rules{$group_name}},$src_rule);
  630. push(@{$chain_rules{$group_name}},$dst_rule);
  631. } else {
  632. push(@{$chain_rules{$group_name}},$src_rule);
  633. }
  634. }
  635. }
  636. #chain filters
  637. foreach my $group_name (sort keys %group_filters) {
  638. next if (!$group_name);
  639. my @get_filter=netdev_cmd($gate,$t,'/ip firewall filter print terse without-paging where chain='.$group_name,1);
  640. chomp(@get_filter);
  641. my @cur_filter=();
  642. my $chain_ok=1;
  643. foreach (my $f_index=0; $f_index<scalar(@get_filter); $f_index++) {
  644. my $filter_str=trim($get_filter[$f_index]);
  645. next if (!$filter_str);
  646. next if ($filter_str!~/^(\d){1,3}/);
  647. $filter_str=~s/[^[:ascii:]]//g;
  648. $filter_str=~s/^\d{1,3}\s+//;
  649. $filter_str=trim($filter_str);
  650. next if (!$filter_str);
  651. push(@cur_filter,$filter_str);
  652. }
  653. log_debug($gate_ident."Current filters:".Dumper(\@cur_filter));
  654. log_debug($gate_ident."New filters:".Dumper($chain_rules{$group_name}));
  655. #current state rules
  656. foreach (my $f_index=0; $f_index<scalar(@cur_filter); $f_index++) {
  657. my $filter_str=trim($cur_filter[$f_index]);
  658. if (!$chain_rules{$group_name}[$f_index] or $filter_str!~/$chain_rules{$group_name}[$f_index]/i) {
  659. print "Check chain $group_name error! $filter_str not found in new config. Recreate chain.\n";
  660. $chain_ok=0;
  661. last;
  662. }
  663. }
  664. #new rules
  665. if ($chain_ok and $chain_rules{$group_name} and scalar(@{$chain_rules{$group_name}})) {
  666. foreach (my $f_index=0; $f_index<scalar(@{$chain_rules{$group_name}}); $f_index++) {
  667. my $filter_str=trim($cur_filter[$f_index]);
  668. if (!$filter_str) {
  669. print "Check chain $group_name error! Not found: $chain_rules{$group_name}[$f_index]. Recreate chain.\n";
  670. $chain_ok=0;
  671. last;
  672. }
  673. $filter_str=~s/^\d//;
  674. $filter_str=trim($filter_str);
  675. if ($filter_str!~/$chain_rules{$group_name}[$f_index]/i) {
  676. print "Check chain $group_name error! Expected: $chain_rules{$group_name}[$f_index] Found: $filter_str. Recreate chain.\n";
  677. $chain_ok=0;
  678. last;
  679. }
  680. }
  681. }
  682. if (!$chain_ok) {
  683. push(@cmd_list,":foreach i in [/ip firewall filter find where chain=".$group_name." ] do={/ip firewall filter remove \$i};");
  684. foreach my $filter_str (@{$chain_rules{$group_name}}) {
  685. push(@cmd_list,'/ip firewall filter add '.$filter_str);
  686. }
  687. }
  688. }
  689. if ($shaper_enabled) {
  690. #shapers
  691. my %get_queue_type=();
  692. my %get_queue_tree=();
  693. my %get_filter_mangle=();
  694. my @tmp=netdev_cmd($gate,$t,'/queue type print terse without-paging where name~"pcq_(down|up)load"',1);
  695. log_debug($gate_ident."Get queues: ".Dumper(\@tmp));
  696. # 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
  697. #pcq-src-address-mask=32 pcq-dst-address-mask=32 pcq-src-address6-mask=64 pcq-dst-address6-mask=64
  698. foreach my $row (@tmp) {
  699. next if (!$row);
  700. $row = trim($row);
  701. next if ($row!~/^(\d){1,3}/);
  702. $row=~s/^\d{1,3}\s+//;
  703. next if (!$row);
  704. if ($row=~/name=pcq_(down|up)load_(\d){1,3}\s+/i) {
  705. next if (!$1);
  706. next if (!$2);
  707. my $direct = $1;
  708. my $index = $2;
  709. $get_queue_type{$index}{$direct}=$row;
  710. if ($row=~/pcq-rate=(\S*)\s+\S/i) {
  711. my $rate = $1;
  712. if ($rate=~/k$/i) { $rate =~s/k$//i; }
  713. $get_queue_type{$index}{$direct."-rate"}=$rate;
  714. }
  715. if ($row=~/pcq-classifier=(\S*)\s+\S/i) { $get_queue_type{$index}{$direct."-classifier"}=$1; }
  716. if ($row=~/pcq-src-address-mask=(\S*)\s+\S/i) { $get_queue_type{$index}{$direct."-src-address-mask"}=$1; }
  717. if ($row=~/pcq-dst-address-mask=(\S*)\s+\S/i) { $get_queue_type{$index}{$direct."-dst-address-mask"}=$1; }
  718. }
  719. }
  720. @tmp=();
  721. @tmp=netdev_cmd($gate,$t,'/queue tree print terse without-paging where parent~"(download|upload)_root"',1);
  722. log_debug($gate_ident."Get root queues: ".Dumper(\@tmp));
  723. #print Dumper(\@tmp);
  724. # 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
  725. # 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
  726. foreach my $row (@tmp) {
  727. next if (!$row);
  728. $row = trim($row);
  729. next if ($row!~/^(\d)/);
  730. $row=~s/^(\d*)\s+//;
  731. next if (!$row);
  732. if ($row=~/queue=pcq_(down|up)load_(\d){1,3}/i) {
  733. if ($row=~/name=queue_(\d){1,3}_(\S*)_out\s+/i) {
  734. next if (!$1);
  735. next if (!$2);
  736. my $index = $1;
  737. my $int_name = $2;
  738. $get_queue_tree{$index}{$int_name}{up}=$row;
  739. if ($row=~/parent=(\S*)\s+\S/i) { $get_queue_tree{$index}{$int_name}{'up-parent'}=$1; }
  740. if ($row=~/packet-mark=(\S*)\s+\S/i) { $get_queue_tree{$index}{$int_name}{'up-mark'}=$1; }
  741. if ($row=~/queue=(\S*)\s+\S/i) { $get_queue_tree{$index}{$int_name}{'up-queue'}=$1; }
  742. }
  743. if ($row=~/name=queue_(\d){1,3}_(\S*)_in\s+/i) {
  744. next if (!$1);
  745. next if (!$2);
  746. my $index = $1;
  747. my $int_name = $2;
  748. $get_queue_tree{$index}{$int_name}{down}=$row;
  749. if ($row=~/parent=(\S*)\s+\S/i) { $get_queue_tree{$index}{$int_name}{'down-parent'}=$1; }
  750. if ($row=~/packet-mark=(\S*)\s+\S/i) { $get_queue_tree{$index}{$int_name}{'down-mark'}=$1; }
  751. if ($row=~/queue=(\S*)\s+\S/i) { $get_queue_tree{$index}{$int_name}{'down-queue'}=$1; }
  752. }
  753. }
  754. }
  755. @tmp=();
  756. @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);
  757. log_debug($gate_ident."Get firewall mangle rules for queues:".Dumper(\@tmp));
  758. # 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=""
  759. # 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=""
  760. foreach my $row (@tmp) {
  761. next if (!$row);
  762. $row = trim($row);
  763. next if ($row!~/^(\d){1,3}/);
  764. $row=~s/^\d{1,3}\s+//;
  765. next if (!$row);
  766. if ($row=~/new-packet-mark=upload_(\d){1,3}_(\S*)\s+/i) {
  767. next if (!$1);
  768. next if (!$2);
  769. my $index = $1;
  770. my $int_name = $2;
  771. $get_filter_mangle{$index}{$int_name}{up}=$row;
  772. if ($row=~/src-address-list=(\S*)\s+\S/i) { $get_filter_mangle{$index}{$int_name}{'up-list'}=$1; }
  773. if ($row=~/out-interface=(\S*)\s+\S/i) { $get_filter_mangle{$index}{$int_name}{'up-dev'}=$1; }
  774. if ($row=~/new-packet-mark=(\S*)\s+\S/i) { $get_filter_mangle{$index}{$int_name}{'up-mark'}=$1; }
  775. }
  776. if ($row=~/new-packet-mark=download_(\d){1,3}_(\S*)\s+/i) {
  777. next if (!$1);
  778. next if (!$2);
  779. my $index = $1;
  780. my $int_name = $2;
  781. $get_filter_mangle{$index}{$int_name}{down}=$row;
  782. if ($row=~/dst-address-list=(\S*)\s+\S/i) { $get_filter_mangle{$index}{$int_name}{'down-list'}=$1; }
  783. if ($row=~/new-packet-mark=(\S*)\s+\S/i) { $get_filter_mangle{$index}{$int_name}{'down-mark'}=$1; }
  784. if ($row=~/out-interface=(\S*)\s+\S/i) { $get_filter_mangle{$index}{$int_name}{'down-dev'}=$1; }
  785. }
  786. }
  787. log_debug($gate_ident."Queues type status:".Dumper(\%get_queue_type));
  788. log_debug($gate_ident."Queues tree status:".Dumper(\%get_queue_tree));
  789. log_debug($gate_ident."Firewall mangle status:".Dumper(\%get_filter_mangle));
  790. my %queue_type;
  791. my %queue_tree;
  792. my %filter_mangle;
  793. #generate new config
  794. foreach my $queue_name (keys %queues) {
  795. my $q_id=$queues{$queue_name}{id};
  796. my $q_up=$queues{$queue_name}{up}+1;
  797. my $q_down=$queues{$queue_name}{down}+1;
  798. #queue_types
  799. $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";
  800. $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";
  801. my $queue_ok=1;
  802. if (!$get_queue_type{$q_id}{up}) { $queue_ok=0; }
  803. if ($queue_ok and abs($q_up - $get_queue_type{$q_id}{'up-rate'})>10) { $queue_ok=0; }
  804. if ($queue_ok and $get_queue_type{$q_id}{'up-classifier'}!~/src-address/i) { $queue_ok=0; }
  805. if (!$queue_ok) {
  806. push(@cmd_list,':foreach i in [/queue type find where name~"pcq_upload_'.$q_id.'" ] do={/queue type remove $i};');
  807. push(@cmd_list,'/queue type add '.$queue_type{$q_id}{up});
  808. }
  809. $queue_ok=1;
  810. if (!$get_queue_type{$q_id}{down}) { $queue_ok=0; }
  811. if ($queue_ok and abs($q_up - $get_queue_type{$q_id}{'down-rate'})>10) { $queue_ok=0; }
  812. if ($queue_ok and $get_queue_type{$q_id}{'down-classifier'}!~/dst-address/i) { $queue_ok=0; }
  813. if (!$queue_ok) {
  814. push(@cmd_list,':foreach i in [/queue type find where name~"pcq_download_'.$q_id.'" ] do={/queue type remove $i};');
  815. push(@cmd_list,'/queue type add '.$queue_type{$q_id}{down});
  816. }
  817. #upload queue
  818. foreach my $int (@wan_int) {
  819. $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";
  820. $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=\"\"";
  821. $queue_ok=1;
  822. if (!$get_queue_tree{$q_id}{$int}{up}) { $queue_ok=0; }
  823. if ($queue_ok and ($get_queue_tree{$q_id}{$int}{'up-parent'} ne "upload_root_".$int)) { $queue_ok=0;}
  824. if ($queue_ok and ($get_queue_tree{$q_id}{$int}{'up-mark'} ne "upload_".$q_id."_".$int)) { $queue_ok=0; }
  825. if ($queue_ok and ($get_queue_tree{$q_id}{$int}{'up-queue'} ne "pcq_upload_".$q_id)) { $queue_ok=0; }
  826. if (!$queue_ok) {
  827. push(@cmd_list,':foreach i in [/queue tree find where name~"queue_'.$q_id."_".$int."_out".'" ] do={/queue tree remove $i};');
  828. push(@cmd_list,'/queue tree add '.$queue_tree{$q_id}{$int}{up});
  829. }
  830. $queue_ok=1;
  831. if (!$get_filter_mangle{$q_id}{$int}{up}) { $queue_ok=0; }
  832. if ($queue_ok and ($get_filter_mangle{$q_id}{$int}{'up-mark'} ne "upload_".$q_id."_".$int)) { $queue_ok=0; }
  833. if ($queue_ok and ($get_filter_mangle{$q_id}{$int}{'up-list'} ne "queue_".$q_id)) { $queue_ok=0; }
  834. if ($queue_ok and ($get_filter_mangle{$q_id}{$int}{'up-dev'} ne $int)) { $queue_ok=0; }
  835. if (!$queue_ok) {
  836. 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};');
  837. push(@cmd_list,'/ip firewall mangle add '.$filter_mangle{$q_id}{$int}{up});
  838. }
  839. }
  840. #download
  841. foreach my $int (@lan_int) {
  842. next if (!$int);
  843. $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";
  844. $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=\"\"";
  845. $queue_ok=1;
  846. if (!$get_queue_tree{$q_id}{$int}{down}) { $queue_ok=0; }
  847. if ($queue_ok and ($get_queue_tree{$q_id}{$int}{'down-parent'} ne "download_root_".$int)) { $queue_ok=0; }
  848. if ($queue_ok and ($get_queue_tree{$q_id}{$int}{'down-mark'} ne "download_".$q_id."_".$int)) { $queue_ok=0; }
  849. if ($queue_ok and ($get_queue_tree{$q_id}{$int}{'down-queue'} ne "pcq_download_".$q_id)) { $queue_ok=0; }
  850. if (!$queue_ok) {
  851. push(@cmd_list,':foreach i in [/queue tree find where name~"queue_'.$q_id."_".$int."_in".'" ] do={/queue tree remove $i};');
  852. push(@cmd_list,'/queue tree add '.$queue_tree{$q_id}{$int}{down});
  853. }
  854. $queue_ok=1;
  855. if (!$get_filter_mangle{$q_id}{$int}{down}) { $queue_ok=0; }
  856. if ($queue_ok and ($get_filter_mangle{$q_id}{$int}{'down-mark'} ne "download_".$q_id."_".$int)) { $queue_ok=0; }
  857. if ($queue_ok and ($get_filter_mangle{$q_id}{$int}{'down-list'} ne "queue_".$q_id)) { $queue_ok=0; }
  858. if ($queue_ok and ($get_filter_mangle{$q_id}{$int}{'down-dev'} ne $int)) { $queue_ok=0; }
  859. if (!$queue_ok) {
  860. 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};');
  861. push(@cmd_list,'/ip firewall mangle add '.$filter_mangle{$q_id}{$int}{down});
  862. }
  863. }
  864. #end shaper
  865. }
  866. }
  867. }#end access lists config
  868. if (scalar(@cmd_list)) {
  869. log_debug($gate_ident."Apply:");
  870. if ($debug) { foreach my $cmd (@cmd_list) { log_debug($gate_ident."$cmd"); } }
  871. eval {
  872. netdev_cmd($gate,$t,\@cmd_list,1);
  873. };
  874. if ($@) {
  875. $all_ok = 0;
  876. log_debug($gate_ident."Error programming gateway! Err: ".$@);
  877. }
  878. }
  879. db_log_verbose($dbh,$gate_ident."Sync user state stopped.");
  880. $dbh->disconnect();
  881. $pm->finish;
  882. }
  883. $pm->wait_all_children;
  884. #clear changed
  885. if ($all_ok) {
  886. foreach my $row (@changes_found) {
  887. do_sql($dbh,"UPDATE User_auth SET changed=0 WHERE id=".$row->{id});
  888. }
  889. }
  890. if (IsMyPID($SPID)) { Remove_PID($SPID); };
  891. do_exit 0;