sync_mikrotik.pl 29 KB

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