sync_mikrotik.pl 31 KB

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