sync_mikrotik.pl 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751
  1. #!/usr/bin/perl
  2. #
  3. # Copyright (C) Roman Dmitiriev, rnd@rajven.ru
  4. #
  5. use FindBin '$Bin';
  6. use lib "$Bin/";
  7. use strict;
  8. use Time::Local;
  9. use FileHandle;
  10. use Data::Dumper;
  11. use Rstat::config;
  12. use Rstat::main;
  13. use Rstat::mikrotik;
  14. use Rstat::cmd;
  15. use Net::Patricia;
  16. use Date::Parse;
  17. use Rstat::net_utils;
  18. use Rstat::mysql;
  19. use DBI;
  20. use utf8;
  21. use open ":encoding(utf8)";
  22. $|=1;
  23. if (IsNotRun($SPID)) { Add_PID($SPID); } else { die "Warning!!! $SPID already runnning!\n"; }
  24. my @gateways =();
  25. #select undeleted mikrotik routers only
  26. if ($ARGV[0]) {
  27. my $router = get_record_sql($dbh,'SELECT * FROM devices WHERE device_type=2 and (user_acl=1 or dhcp=1) and deleted=0 and vendor_id=9 and id='.$ARGV[0]);
  28. if ($router) { push(@gateways,$router); }
  29. } else {
  30. @gateways = get_records_sql($dbh,'SELECT * FROM devices WHERE device_type=2 and (user_acl=1 or dhcp=1) and deleted=0 and vendor_id=9');
  31. }
  32. my $dhcp_networks = new Net::Patricia;
  33. my %dhcp_conf;
  34. my @subnets=get_records_sql($dbh,'SELECT * FROM subnets WHERE dhcp=1 and office=1 and vpn=0 ORDER BY ip_int_start');
  35. foreach my $subnet (@subnets) {
  36. next if (!$subnet->{gateway});
  37. my $subnet_name = $subnet->{subnet};
  38. $subnet_name=~s/\/\d+$//g;
  39. $dhcp_networks->add_string($subnet->{subnet},$subnet_name);
  40. $dhcp_conf{$subnet_name}->{first_pool_ip}=IpToStr($subnet->{dhcp_start});
  41. $dhcp_conf{$subnet_name}->{last_pool_ip}=IpToStr($subnet->{dhcp_stop});
  42. $dhcp_conf{$subnet_name}->{relay_ip}=IpToStr($subnet->{gateway});
  43. my $dhcp_info=GetDhcpRange($subnet->{subnet});
  44. $dhcp_conf{$subnet_name}->{first_ip} = $dhcp_info->{first_ip};
  45. $dhcp_conf{$subnet_name}->{last_ip} = $dhcp_info->{last_ip};
  46. $dhcp_conf{$subnet_name}->{first_ip_aton}=StrToIp($dhcp_info->{first_ip});
  47. $dhcp_conf{$subnet_name}->{last_ip_aton}=StrToIp($dhcp_info->{last_ip});
  48. }
  49. foreach my $gate (@gateways) {
  50. next if (!$gate);
  51. my $router_name=$gate->{device_name};
  52. my $router_ip=$gate->{ip};
  53. my $shaper_enabled = $gate->{queue_enabled};
  54. my $connected_users_only = $gate->{connected_user_only};
  55. my $connected_users = new Net::Patricia;
  56. my @lan_int=();
  57. my @wan_int=();
  58. my @l3_int = get_records_sql($dbh,'SELECT * FROM device_l3_interfaces WHERE device_id='.$gate->{'id'});
  59. foreach my $l3 (@l3_int) {
  60. if ($l3->{'interface_type'} eq '0') { push(@lan_int,$l3->{'name'}); }
  61. if ($l3->{'interface_type'} eq '1') { push(@wan_int,$l3->{'name'}); }
  62. }
  63. my @cmd_list=();
  64. my $t = Login_Mikrotik($router_ip);
  65. foreach my $int (@lan_int) { #interface dhcp loop
  66. next if (!$int);
  67. $int=trim($int);
  68. #get ip addr at interface
  69. my @int_addr=log_cmd4($t,'/ip address print terse without-paging where interface='.$int);
  70. my $found_subnet;
  71. foreach my $int_str(@int_addr) {
  72. $int_str=trim($int_str);
  73. next if (!$int_str);
  74. if ($int_str=~/\s+address=(\S*)\s+/i) {
  75. my $gate_interface=$1;
  76. if ($gate_interface) {
  77. my $gate_ip=$gate_interface;
  78. $gate_ip=~s/\/.*$//;
  79. #search for first match
  80. if (!$found_subnet) { $found_subnet=$dhcp_networks->match_string($gate_ip); }
  81. #all subnets match
  82. if ($connected_users_only) { $connected_users->add_string($gate_interface); }
  83. }
  84. }
  85. }
  86. if (!$found_subnet) { db_log_verbose($dbh,"DHCP subnet for interface $int not found! Skip interface."); next; }
  87. db_log_verbose($dbh,"Analyze interface $int. Found: ".Dumper($dhcp_conf{$found_subnet}));
  88. #dhcp config
  89. if ($gate->{dhcp}) {
  90. #fetch current dhcp records
  91. my @ret_static_leases=log_cmd4($t,'/ip dhcp-server lease print terse without-paging where server=dhcp-'.$int);
  92. my @current_static_leases=();
  93. foreach my $str (@ret_static_leases) {
  94. next if (!$str);
  95. $str=trim($str);
  96. if ($str=~/^\d/) {
  97. log_debug("Found current static lease record: ".$str);
  98. push(@current_static_leases,$str);
  99. }
  100. }
  101. #select users for this interface
  102. my @auth_records=get_records_sql($dbh,"SELECT * from User_auth WHERE dhcp=1 and `ip_int`>=".$dhcp_conf{$found_subnet}->{first_ip_aton}." and `ip_int`<=".$dhcp_conf{$found_subnet}->{last_ip_aton}." and deleted=0 and user_id<>".$default_user_id." and user_id<>".$hotspot_user_id." ORDER BY ip_int");
  103. my %leases;
  104. foreach my $lease (@auth_records) {
  105. next if (!$lease);
  106. next if (!$lease->{mac});
  107. next if (!$lease->{ip});
  108. next if ($lease->{ip} eq $dhcp_conf{$found_subnet}->{relay_ip});
  109. $leases{$lease->{ip}}{ip}=$lease->{ip};
  110. $leases{$lease->{ip}}{comment}=$lease->{id};
  111. $leases{$lease->{ip}}{id}=$lease->{id};
  112. $leases{$lease->{ip}}{dns_name}=$lease->{dns_name};
  113. if ($lease->{comments}) { $leases{$lease->{ip}}{comment}=translit($lease->{comments}); }
  114. $leases{$lease->{ip}}{mac}=uc(mac_splitted($lease->{mac}));
  115. if ($lease->{dhcp_acl}) {
  116. $leases{$lease->{ip}}{acl}=trim($lease->{dhcp_acl});
  117. $leases{$lease->{ip}}{acl}=~s/;/,/g;
  118. }
  119. $leases{$lease->{ip}}{acl}='' if (!$leases{$lease->{ip}}{acl});
  120. }
  121. my %active_leases;
  122. foreach my $lease (@current_static_leases) {
  123. my @words = split(/\s+/,$lease);
  124. my %tmp_lease;
  125. if ($lease=~/^(\d*)\s+/) { $tmp_lease{id}=$1; };
  126. next if (!defined($tmp_lease{id}));
  127. foreach my $option (@words) {
  128. next if (!$option);
  129. $option=trim($option);
  130. next if (!$option);
  131. my @tmp = split(/\=/,$option);
  132. my $token = trim($tmp[0]);
  133. my $value = trim($tmp[1]);
  134. next if (!$token);
  135. next if (!$value);
  136. $value=~s/\"//g;
  137. if ($token=~/^address$/i) { $tmp_lease{ip}=GetIP($value); }
  138. if ($token=~/^mac-address$/i) { $tmp_lease{mac}=uc(mac_splitted($value)); }
  139. if ($token=~/^host-name$/i) { $tmp_lease{dhcp_hostname}=$value; }
  140. if ($token=~/^address-lists$/i) { $tmp_lease{acl}=$value; }
  141. }
  142. next if (!$tmp_lease{ip});
  143. next if (!$tmp_lease{mac});
  144. if ($tmp_lease{dhcp_hostname}) {
  145. my $dSQL="Update User_auth set dhcp_hostname='".$tmp_lease{dhcp_hostname}."' where deleted=0 and ip_int=".StrToIp($tmp_lease{ip})." and mac='".lc($tmp_lease{mac})."'";
  146. db_log_debug($dbh,"Update dhcp hostname $tmp_lease{dhcp_hostname} for $tmp_lease{ip} [$tmp_lease{mac}] from mikrotik dhcp server");
  147. do_sql($dbh,$dSQL);
  148. }
  149. #skip dynamic leases. this check MUST BE After update dhcp hostname!!!
  150. next if ($lease=~/^(\d*)\s+D\s+/);
  151. $active_leases{$tmp_lease{ip}}{ip}=$tmp_lease{ip};
  152. $active_leases{$tmp_lease{ip}}{mac}=$tmp_lease{mac};
  153. $active_leases{$tmp_lease{ip}}{id}=$tmp_lease{id};
  154. $active_leases{$tmp_lease{ip}}{acl}='';
  155. if ($tmp_lease{acl}) {
  156. $active_leases{$tmp_lease{ip}}{acl}=$tmp_lease{acl};
  157. }
  158. }
  159. if ($debug) { log_debug("Active leases: ".Dumper(\%active_leases)); }
  160. #sync state
  161. foreach my $ip (keys %active_leases) {
  162. if (!exists $leases{$ip}) {
  163. db_log_verbose($dbh,"Address $ip not found in stat. Remove from router.");
  164. push(@cmd_list,':foreach i in [/ip dhcp-server lease find where address='.$ip.' ] do={/ip dhcp-server lease remove $i};');
  165. push(@cmd_list,'/ip dhcp-server lease remove [find address='.$ip.']');
  166. next;
  167. }
  168. if ($leases{$ip}{mac}!~/$active_leases{$ip}{mac}/i) {
  169. db_log_verbose($dbh,"Mac-address mismatch for ip $ip. stat: $leases{$ip}{mac} active: $active_leases{$ip}{mac}. Remove lease from router.");
  170. push(@cmd_list,':foreach i in [/ip dhcp-server lease find where address='.$ip.' ] do={/ip dhcp-server lease remove $i};');
  171. push(@cmd_list,'/ip dhcp-server lease remove [find address='.$ip.']');
  172. next;
  173. }
  174. next if (!$leases{$ip}{acl} and !$active_leases{$ip}{acl});
  175. if ($leases{$ip}{acl}!~/$active_leases{$ip}{acl}/) {
  176. db_log_error($dbh,"Acl mismatch for ip $ip. stat: $leases{$ip}{acl} active: $active_leases{$ip}{acl}. Remove lease from router.");
  177. push(@cmd_list,':foreach i in [/ip dhcp-server lease find where address='.$ip.' ] do={/ip dhcp-server lease remove $i};');
  178. push(@cmd_list,'/ip dhcp-server lease remove [find address='.$ip.']');
  179. next;
  180. }
  181. }
  182. foreach my $ip (keys %leases) {
  183. my $acl='';
  184. if ($leases{$ip}{acl}) { $acl = 'address-lists='.$leases{$ip}{acl}; }
  185. my $comment = $leases{$ip}{comment};
  186. $comment =~s/\=//g;
  187. my $dns_name='';
  188. if ($leases{$ip}{dns_name}) { $dns_name = $leases{$ip}{dns_name}; }
  189. $dns_name =~s/\=//g;
  190. if ($dns_name) { $comment = 'comment="'.$dns_name." - ".$comment.'"'; } else { $comment = 'comment="'.$comment.'"'; }
  191. if (!exists $active_leases{$ip}) {
  192. db_log_verbose($dbh,"Address $ip not found in router. Create static lease record.");
  193. #remove static and dynamic records for mac
  194. 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};');
  195. push(@cmd_list,'/ip dhcp-server lease remove [find mac-address='.uc($leases{$ip}{mac}).']');
  196. #remove current ip binding
  197. push(@cmd_list,':foreach i in [/ip dhcp-server lease find where address='.$ip.' ] do={/ip dhcp-server lease remove $i};');
  198. push(@cmd_list,'/ip dhcp-server lease remove [find address='.$ip.']');
  199. #add new bind
  200. push(@cmd_list,'/ip dhcp-server lease add address='.$ip.' mac-address='.$leases{$ip}{mac}.' '.$acl.' server=dhcp-'.$int.' '.$comment);
  201. next;
  202. }
  203. if ($leases{$ip}{mac}!~/$active_leases{$ip}{mac}/i) {
  204. db_log_error($dbh,"Mac-address mismatch for ip $ip. stat: $leases{$ip}{mac} active: $active_leases{$ip}{mac}. Create static lease record.");
  205. #remove static and dynamic records for mac
  206. 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};');
  207. push(@cmd_list,'/ip dhcp-server lease remove [find mac-address='.uc($leases{$ip}{mac}).']');
  208. #remove current ip binding
  209. push(@cmd_list,':foreach i in [/ip dhcp-server lease find where address='.$ip.' ] do={/ip dhcp-server lease remove $i};');
  210. push(@cmd_list,'/ip dhcp-server lease remove [find address='.$ip.']');
  211. #add new bind
  212. push(@cmd_list,'/ip dhcp-server lease add address='.$ip.' mac-address='.$leases{$ip}{mac}.' '.$acl.' server=dhcp-'.$int.' '.$comment);
  213. next;
  214. }
  215. next if (!$leases{$ip}{acl} and !$active_leases{$ip}{acl});
  216. if ($leases{$ip}{acl}!~/$active_leases{$ip}{acl}/) {
  217. db_log_error($dbh,"Acl mismatch for ip $ip. stat: $leases{$ip}{acl} active: $active_leases{$ip}{acl}. Create static lease record.");
  218. 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};');
  219. push(@cmd_list,'/ip dhcp-server lease remove [find mac-address='.uc($leases{$ip}{mac}).']');
  220. push(@cmd_list,'/ip dhcp-server lease add address='.$ip.' mac-address='.$leases{$ip}{mac}.' '.$acl.' server=dhcp-'.$int.' '.$comment);
  221. next;
  222. }
  223. }
  224. }#end interface dhcp loop
  225. }#end dhcp config
  226. #access lists config
  227. if ($gate->{user_acl}) {
  228. db_log_verbose($dbh,"Sync user state at router $router_name [".$router_ip."] started.");
  229. #get userid list
  230. my $user_auth_sql="SELECT User_auth.ip, User_auth.filter_group_id, User_auth.queue_id
  231. FROM User_auth, User_list
  232. WHERE User_auth.user_id = User_list.id
  233. AND User_auth.deleted =0
  234. AND User_auth.enabled =1
  235. AND User_auth.blocked =0
  236. AND User_list.blocked =0
  237. AND User_auth.user_id <> $hotspot_user_id
  238. ORDER BY ip_int";
  239. my $user_auth_list = $dbh->prepare($user_auth_sql);
  240. if ( !defined $user_auth_list ) { die "Cannot prepare statement: $DBI::errstr\n"; }
  241. $user_auth_list->execute;
  242. # user auth list
  243. my $authlist_ref = $user_auth_list->fetchall_arrayref();
  244. $user_auth_list->finish();
  245. my %users;
  246. my %lists;
  247. my @squid_users=();
  248. foreach my $row (@$authlist_ref) {
  249. if ($connected_users_only) {
  250. next if (!$connected_users->match_string($row->[0]));
  251. }
  252. $users{'group_'.$row->[1]}->{$row->[0]}=1;
  253. $users{'group_all'}->{$row->[0]}=1;
  254. $lists{'group_'.$row->[1]}=1;
  255. if ($row->[2]) { $users{'queue_'.$row->[2]}->{$row->[0]}=1; }
  256. }
  257. #full list
  258. $lists{'group_all'}=1;
  259. #get queue list
  260. my $queue_list = $dbh->prepare( "SELECT id,queue_name,Download,Upload FROM Queue_list" );
  261. if ( !defined $queue_list ) { die "Cannot prepare statement: $DBI::errstr\n"; }
  262. $queue_list->execute;
  263. # user auth list
  264. my $queuelist_ref = $queue_list->fetchall_arrayref();
  265. $queue_list->finish();
  266. my %queues;
  267. foreach my $row (@$queuelist_ref) {
  268. $lists{'queue_'.$row->[0]}=1;
  269. next if ((!$row->[2]) and !($row->[3]));
  270. $queues{'queue_'.$row->[0]}{id}=$row->[0];
  271. $queues{'queue_'.$row->[0]}{down}=$row->[2];
  272. $queues{'queue_'.$row->[0]}{up}=$row->[3];
  273. }
  274. #print Dumper(\%users) if ($debug);
  275. #get filters
  276. my $filter_list = $dbh->prepare( "SELECT id,name,proto,dst,dstport,action FROM Filter_list where type=0" );
  277. if ( !defined $filter_list ) { die "Cannot prepare statement: $DBI::errstr\n"; }
  278. $filter_list->execute;
  279. # user auth list
  280. my $filterlist_ref = $filter_list->fetchall_arrayref();
  281. $filter_list->finish();
  282. my %filters;
  283. foreach my $row (@$filterlist_ref) {
  284. $filters{$row->[0]}->{id}=$row->[0];
  285. $filters{$row->[0]}->{proto}=$row->[2];
  286. $filters{$row->[0]}->{dst}=$row->[3];
  287. $filters{$row->[0]}->{port}=$row->[4];
  288. $filters{$row->[0]}->{action}=$row->[5];
  289. }
  290. #print Dumper(\%filters) if ($debug);
  291. #get groups
  292. my $group_list = $dbh->prepare( "SELECT group_id,filter_id,Group_filters.order FROM Group_filters order by Group_filters.group_id,Group_filters.order" );
  293. if ( !defined $group_list ) { die "Cannot prepare statement: $DBI::errstr\n"; }
  294. $group_list->execute;
  295. # user auth list
  296. my $grouplist_ref = $group_list->fetchall_arrayref();
  297. $group_list->finish();
  298. my %group_filters;
  299. my $index=1;
  300. foreach my $row (@$grouplist_ref) {
  301. #{group-name}->{filter_id}=order
  302. $group_filters{'group_'.$row->[0]}->{$index}=$row->[1];
  303. $index++;
  304. }
  305. #print Dumper(\%group_filters) if ($debug);
  306. my %cur_users;
  307. foreach my $group_name (keys %lists) {
  308. my @address_lists=log_cmd4($t,'/ip firewall address-list print terse without-paging where list='.$group_name);
  309. foreach my $row (@address_lists) {
  310. $row=trim($row);
  311. next if (!$row);
  312. my @address=split(' ',$row);
  313. foreach my $row (@address) {
  314. if ($row=~/address\=(.*)/i) { $cur_users{$group_name}{$1}=1; }
  315. }
  316. }
  317. }
  318. #new-ips
  319. foreach my $group_name (keys %users) {
  320. foreach my $user_ip (keys %{$users{$group_name}}) {
  321. if (!exists($cur_users{$group_name}{$user_ip})) {
  322. db_log_verbose($dbh,"Add user with ip: $user_ip to access-list $group_name");
  323. push(@cmd_list,"/ip firewall address-list add address=".$user_ip." list=".$group_name);
  324. }
  325. }
  326. }
  327. #old-ips
  328. foreach my $group_name (keys %cur_users) {
  329. foreach my $user_ip (keys %{$cur_users{$group_name}}) {
  330. if (!exists($users{$group_name}{$user_ip})) {
  331. db_log_verbose($dbh,"Remove user with ip: $user_ip from access-list $group_name");
  332. 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};");
  333. }
  334. }
  335. }
  336. timestamp;
  337. #sync firewall rules
  338. #sync group chains
  339. my @chain_list=log_cmd4($t,'/ip firewall filter print terse without-paging where chain=Users and action=jump');
  340. my %cur_chain;
  341. foreach my $jump_list (@chain_list) {
  342. next if (!$jump_list);
  343. $jump_list=trim($jump_list);
  344. if ($jump_list=~/jump-target=(\S*)\s+/i) {
  345. if ($1) { $cur_chain{$1}++; }
  346. }
  347. }
  348. #old chains
  349. foreach my $group_name (keys %cur_chain) {
  350. if (!exists($group_filters{$group_name})) {
  351. 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};");
  352. } else {
  353. if ($cur_chain{$group_name} != 2) {
  354. 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};");
  355. push (@cmd_list,"/ip firewall filter add chain=Users action=jump jump-target=".$group_name." src-address-list=".$group_name);
  356. push (@cmd_list,"/ip firewall filter add chain=Users action=jump jump-target=".$group_name." dst-address-list=".$group_name);
  357. }
  358. }
  359. }
  360. #new chains
  361. foreach my $group_name (keys %group_filters) {
  362. if (!exists($cur_chain{$group_name})) {
  363. push (@cmd_list,"/ip firewall filter add chain=Users action=jump jump-target=".$group_name." src-address-list=".$group_name);
  364. push (@cmd_list,"/ip firewall filter add chain=Users action=jump jump-target=".$group_name." dst-address-list=".$group_name);
  365. }
  366. }
  367. my %chain_rules;
  368. foreach my $group_name (keys %group_filters) {
  369. next if (!$group_name);
  370. next if (!exists($group_filters{$group_name}));
  371. foreach my $filter_index (sort keys %{$group_filters{$group_name}}) {
  372. my $filter_id=$group_filters{$group_name}->{$filter_index};
  373. next if (!$filters{$filter_id});
  374. my $src_rule='chain='.$group_name;
  375. my $dst_rule='chain='.$group_name;
  376. if ($filters{$filter_id}->{action}) {
  377. $src_rule=$src_rule." action=accept";
  378. $dst_rule=$dst_rule." action=accept";
  379. } else {
  380. $src_rule=$src_rule." action=reject";
  381. $dst_rule=$dst_rule." action=reject";
  382. }
  383. if ($filters{$filter_id}->{proto} and ($filters{$filter_id}->{proto}!~/all/i)) {
  384. $src_rule=$src_rule." protocol=".$filters{$filter_id}->{proto};
  385. $dst_rule=$dst_rule." protocol=".$filters{$filter_id}->{proto};
  386. }
  387. if ($filters{$filter_id}->{dst} and $filters{$filter_id}->{dst} ne '0/0') {
  388. $src_rule=$src_rule." src-address=".trim($filters{$filter_id}->{dst});
  389. $dst_rule=$dst_rule." dst-address=".trim($filters{$filter_id}->{dst});
  390. }
  391. if ($filters{$filter_id}->{port} and $filters{$filter_id}->{port} ne '0') {
  392. $src_rule=$src_rule." src-port=".trim($filters{$filter_id}->{port});
  393. $dst_rule=$dst_rule." dst-port=".trim($filters{$filter_id}->{port});
  394. }
  395. if ($src_rule ne $dst_rule) {
  396. push(@{$chain_rules{$group_name}},$src_rule);
  397. push(@{$chain_rules{$group_name}},$dst_rule);
  398. } else {
  399. push(@{$chain_rules{$group_name}},$src_rule);
  400. }
  401. }
  402. }
  403. #print Dumper(\%chain_rules) if ($debug);
  404. #chain filters
  405. foreach my $group_name (keys %group_filters) {
  406. next if (!$group_name);
  407. my @get_filter=log_cmd4($t,'/ip firewall filter print terse without-paging where chain='.$group_name,1);
  408. my @cur_filter=();
  409. my $chain_ok=1;
  410. foreach (my $f_index=0; $f_index<scalar(@get_filter); $f_index++) {
  411. my $filter_str=trim($get_filter[$f_index]);
  412. next if (!$filter_str);
  413. next if ($filter_str!~/^(\d){1,3}/);
  414. $filter_str=~s/^\d{1,3}\s+//;
  415. $filter_str=trim($filter_str);
  416. next if (!$filter_str);
  417. push(@cur_filter,$filter_str);
  418. }
  419. #current state rules
  420. foreach (my $f_index=0; $f_index<scalar(@cur_filter); $f_index++) {
  421. my $filter_str=trim($cur_filter[$f_index]);
  422. if (!$chain_rules{$group_name}[$f_index] or $filter_str!~/$chain_rules{$group_name}[$f_index]/i) {
  423. print "Check chain $group_name error! $filter_str not found in new config. Recreate chain.\n";
  424. $chain_ok=0;
  425. last;
  426. }
  427. }
  428. #new rules
  429. if ($chain_ok and $chain_rules{$group_name} and scalar(@{$chain_rules{$group_name}})) {
  430. foreach (my $f_index=0; $f_index<scalar(@{$chain_rules{$group_name}}); $f_index++) {
  431. my $filter_str=trim($cur_filter[$f_index]);
  432. if (!$filter_str) {
  433. print "Check chain $group_name error! Not found: $chain_rules{$group_name}[$f_index]. Recreate chain.\n";
  434. $chain_ok=0;
  435. last;
  436. }
  437. $filter_str=~s/^\d//;
  438. $filter_str=trim($filter_str);
  439. if ($filter_str!~/$chain_rules{$group_name}[$f_index]/i) {
  440. print "Check chain $group_name error! Expected: $chain_rules{$group_name}[$f_index] Found: $filter_str. Recreate chain.\n";
  441. $chain_ok=0;
  442. last;
  443. }
  444. }
  445. }
  446. if (!$chain_ok) {
  447. push(@cmd_list,":foreach i in [/ip firewall filter find where chain=".$group_name." ] do={/ip firewall filter remove \$i};");
  448. foreach my $filter_str (@{$chain_rules{$group_name}}) {
  449. push(@cmd_list,'/ip firewall filter add '.$filter_str);
  450. }
  451. }
  452. }
  453. if ($shaper_enabled) {
  454. #shapers
  455. my %get_queue_type=();
  456. my %get_queue_tree=();
  457. my %get_filter_mangle=();
  458. my @tmp=log_cmd4($t,'/queue type print terse without-paging where name~"pcq_(down|up)load"');
  459. # 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
  460. #pcq-src-address-mask=32 pcq-dst-address-mask=32 pcq-src-address6-mask=64 pcq-dst-address6-mask=64
  461. foreach my $row (@tmp) {
  462. next if (!$row);
  463. $row = trim($row);
  464. next if ($row!~/^(\d){1,3}/);
  465. $row=~s/^\d{1,3}\s+//;
  466. next if (!$row);
  467. if ($row=~/name=pcq_(down|up)load_(\d){1,3}\s+/i) {
  468. next if (!$1);
  469. next if (!$2);
  470. my $direct = $1;
  471. my $index = $2;
  472. $get_queue_type{$index}{$direct}=$row;
  473. if ($row=~/pcq-rate=(\S*)\s+\S/i) {
  474. my $rate = $1;
  475. if ($rate=~/k$/i) { $rate =~s/k$//i; }
  476. $get_queue_type{$index}{$direct."-rate"}=$rate;
  477. }
  478. if ($row=~/pcq-classifier=(\S*)\s+\S/i) { $get_queue_type{$index}{$direct."-classifier"}=$1; }
  479. if ($row=~/pcq-src-address-mask=(\S*)\s+\S/i) { $get_queue_type{$index}{$direct."-src-address-mask"}=$1; }
  480. if ($row=~/pcq-dst-address-mask=(\S*)\s+\S/i) { $get_queue_type{$index}{$direct."-dst-address-mask"}=$1; }
  481. }
  482. }
  483. @tmp=();
  484. @tmp=log_cmd4($t,'/queue tree print terse without-paging where parent~"(download|upload)_root"');
  485. # 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
  486. # 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
  487. foreach my $row (@tmp) {
  488. next if (!$row);
  489. $row = trim($row);
  490. next if ($row!~/^(\d)/);
  491. $row=~s/^(\d*)\s+//;
  492. next if (!$row);
  493. if ($row=~/queue=pcq_(down|up)load_(\d){1,3}/i) {
  494. if ($row=~/name=queue_(\d){1,3}_(\S*)_out\s+/i) {
  495. next if (!$1);
  496. next if (!$2);
  497. my $index = $1;
  498. my $int_name = $2;
  499. $get_queue_tree{$index}{$int_name}{up}=$row;
  500. if ($row=~/parent=(\S*)\s+\S/i) { $get_queue_tree{$index}{$int_name}{'up-parent'}=$1; }
  501. if ($row=~/packet-mark=(\S*)\s+\S/i) { $get_queue_tree{$index}{$int_name}{'up-mark'}=$1; }
  502. if ($row=~/queue=(\S*)\s+\S/i) { $get_queue_tree{$index}{$int_name}{'up-queue'}=$1; }
  503. }
  504. if ($row=~/name=queue_(\d){1,3}_(\S*)_in\s+/i) {
  505. next if (!$1);
  506. next if (!$2);
  507. my $index = $1;
  508. my $int_name = $2;
  509. $get_queue_tree{$index}{$int_name}{down}=$row;
  510. if ($row=~/parent=(\S*)\s+\S/i) { $get_queue_tree{$index}{$int_name}{'down-parent'}=$1; }
  511. if ($row=~/packet-mark=(\S*)\s+\S/i) { $get_queue_tree{$index}{$int_name}{'down-mark'}=$1; }
  512. if ($row=~/queue=(\S*)\s+\S/i) { $get_queue_tree{$index}{$int_name}{'down-queue'}=$1; }
  513. }
  514. }
  515. }
  516. @tmp=();
  517. @tmp=log_cmd4($t,'/ip firewall mangle print terse without-paging where action=mark-packet and new-packet-mark~"(upload|download)_[0-9]{1,3}"');
  518. # 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=""
  519. # 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=""
  520. foreach my $row (@tmp) {
  521. next if (!$row);
  522. $row = trim($row);
  523. next if ($row!~/^(\d){1,3}/);
  524. $row=~s/^\d{1,3}\s+//;
  525. next if (!$row);
  526. if ($row=~/new-packet-mark=upload_(\d){1,3}_(\S*)\s+/i) {
  527. next if (!$1);
  528. next if (!$2);
  529. my $index = $1;
  530. my $int_name = $2;
  531. $get_filter_mangle{$index}{$int_name}{up}=$row;
  532. if ($row=~/src-address-list=(\S*)\s+\S/i) { $get_filter_mangle{$index}{$int_name}{'up-list'}=$1; }
  533. if ($row=~/out-interface=(\S*)\s+\S/i) { $get_filter_mangle{$index}{$int_name}{'up-dev'}=$1; }
  534. if ($row=~/new-packet-mark=(\S*)\s+\S/i) { $get_filter_mangle{$index}{$int_name}{'up-mark'}=$1; }
  535. }
  536. if ($row=~/new-packet-mark=download_(\d){1,3}_(\S*)\s+/i) {
  537. next if (!$1);
  538. next if (!$2);
  539. my $index = $1;
  540. my $int_name = $2;
  541. $get_filter_mangle{$index}{$int_name}{down}=$row;
  542. if ($row=~/dst-address-list=(\S*)\s+\S/i) { $get_filter_mangle{$index}{$int_name}{'down-list'}=$1; }
  543. if ($row=~/new-packet-mark=(\S*)\s+\S/i) { $get_filter_mangle{$index}{$int_name}{'down-mark'}=$1; }
  544. if ($row=~/out-interface=(\S*)\s+\S/i) { $get_filter_mangle{$index}{$int_name}{'down-dev'}=$1; }
  545. }
  546. }
  547. #print Dumper(\%get_queue_type) if ($debug);
  548. #print Dumper(\%get_queue_tree) if ($debug);
  549. #print Dumper(\%get_filter_mangle) if ($debug);
  550. my %queue_type;
  551. my %queue_tree;
  552. my %filter_mangle;
  553. #generate new config
  554. foreach my $queue_name (keys %queues) {
  555. my $q_id=$queues{$queue_name}{id};
  556. my $q_up=$queues{$queue_name}{up}+1;
  557. my $q_down=$queues{$queue_name}{down}+1;
  558. #queue_types
  559. $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";
  560. $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";
  561. my $queue_ok=1;
  562. if (!$get_queue_type{$q_id}{up}) { $queue_ok=0; }
  563. if ($queue_ok and abs($q_up - $get_queue_type{$q_id}{'up-rate'})>10) { $queue_ok=0; }
  564. if ($queue_ok and $get_queue_type{$q_id}{'up-classifier'}!~/src-address/i) { $queue_ok=0; }
  565. if (!$queue_ok) {
  566. push(@cmd_list,':foreach i in [/queue type find where name~"pcq_upload_'.$q_id.'" ] do={/queue type remove $i};');
  567. push(@cmd_list,'/queue type add '.$queue_type{$q_id}{up});
  568. }
  569. $queue_ok=1;
  570. if (!$get_queue_type{$q_id}{down}) { $queue_ok=0; }
  571. if ($queue_ok and abs($q_up - $get_queue_type{$q_id}{'down-rate'})>10) { $queue_ok=0; }
  572. if ($queue_ok and $get_queue_type{$q_id}{'down-classifier'}!~/dst-address/i) { $queue_ok=0; }
  573. if (!$queue_ok) {
  574. push(@cmd_list,':foreach i in [/queue type find where name~"pcq_download_'.$q_id.'" ] do={/queue type remove $i};');
  575. push(@cmd_list,'/queue type add '.$queue_type{$q_id}{down});
  576. }
  577. #upload queue
  578. foreach my $int (@wan_int) {
  579. $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";
  580. $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=\"\"";
  581. $queue_ok=1;
  582. if (!$get_queue_tree{$q_id}{$int}{up}) { $queue_ok=0; }
  583. if ($queue_ok and ($get_queue_tree{$q_id}{$int}{'up-parent'} ne "upload_root_".$int)) { $queue_ok=0;}
  584. if ($queue_ok and ($get_queue_tree{$q_id}{$int}{'up-mark'} ne "upload_".$q_id."_".$int)) { $queue_ok=0; }
  585. if ($queue_ok and ($get_queue_tree{$q_id}{$int}{'up-queue'} ne "pcq_upload_".$q_id)) { $queue_ok=0; }
  586. if (!$queue_ok) {
  587. push(@cmd_list,':foreach i in [/queue tree find where name~"queue_'.$q_id."_".$int."_out".'" ] do={/queue tree remove $i};');
  588. push(@cmd_list,'/queue tree add '.$queue_tree{$q_id}{$int}{up});
  589. }
  590. $queue_ok=1;
  591. if (!$get_filter_mangle{$q_id}{$int}{up}) { $queue_ok=0; }
  592. if ($queue_ok and ($get_filter_mangle{$q_id}{$int}{'up-mark'} ne "upload_".$q_id."_".$int)) { $queue_ok=0; }
  593. if ($queue_ok and ($get_filter_mangle{$q_id}{$int}{'up-list'} ne "queue_".$q_id)) { $queue_ok=0; }
  594. if ($queue_ok and ($get_filter_mangle{$q_id}{$int}{'up-dev'} ne $int)) { $queue_ok=0; }
  595. if (!$queue_ok) {
  596. 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};');
  597. push(@cmd_list,'/ip firewall mangle add '.$filter_mangle{$q_id}{$int}{up});
  598. }
  599. }
  600. #download
  601. foreach my $int (@lan_int) {
  602. next if (!$int);
  603. $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";
  604. $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=\"\"";
  605. $queue_ok=1;
  606. if (!$get_queue_tree{$q_id}{$int}{down}) { $queue_ok=0; }
  607. if ($queue_ok and ($get_queue_tree{$q_id}{$int}{'down-parent'} ne "download_root_".$int)) { $queue_ok=0; }
  608. if ($queue_ok and ($get_queue_tree{$q_id}{$int}{'down-mark'} ne "download_".$q_id."_".$int)) { $queue_ok=0; }
  609. if ($queue_ok and ($get_queue_tree{$q_id}{$int}{'down-queue'} ne "pcq_download_".$q_id)) { $queue_ok=0; }
  610. if (!$queue_ok) {
  611. push(@cmd_list,':foreach i in [/queue tree find where name~"queue_'.$q_id."_".$int."_in".'" ] do={/queue tree remove $i};');
  612. push(@cmd_list,'/queue tree add '.$queue_tree{$q_id}{$int}{down});
  613. }
  614. $queue_ok=1;
  615. if (!$get_filter_mangle{$q_id}{$int}{down}) { $queue_ok=0; }
  616. if ($queue_ok and ($get_filter_mangle{$q_id}{$int}{'down-mark'} ne "download_".$q_id."_".$int)) { $queue_ok=0; }
  617. if ($queue_ok and ($get_filter_mangle{$q_id}{$int}{'down-list'} ne "queue_".$q_id)) { $queue_ok=0; }
  618. if ($queue_ok and ($get_filter_mangle{$q_id}{$int}{'down-dev'} ne $int)) { $queue_ok=0; }
  619. if (!$queue_ok) {
  620. 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};');
  621. push(@cmd_list,'/ip firewall mangle add '.$filter_mangle{$q_id}{$int}{down});
  622. }
  623. }
  624. #end shaper
  625. }
  626. }
  627. }#end access lists config
  628. if (scalar(@cmd_list)) {
  629. foreach my $cmd (@cmd_list) {
  630. log_info("$cmd");
  631. # print "$cmd\n" if ($debug);
  632. log_cmd($t,$cmd);
  633. }
  634. }
  635. db_log_verbose($dbh,"Sync user state at router $router_name [".$router_ip."] stopped.");
  636. }
  637. $dbh->disconnect();
  638. if (IsMyPID($SPID)) { Remove_PID($SPID); };
  639. do_exit 0;