1
0

sync_mikrotik.pl 29 KB

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