sync_mikrotik.pl 38 KB

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