sync_mikrotik.pl 29 KB

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