sync_mikrotik.pl 39 KB

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