sync_mikrotik.pl 38 KB

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