sync_mikrotik.pl 39 KB

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