sync_mikrotik.pl 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127
  1. #!/usr/bin/perl
  2. #
  3. # Copyright (C) Roman Dmitriev, rnd@rajven.ru
  4. #
  5. use utf8;
  6. use warnings;
  7. use Encode;
  8. use open qw(:std :encoding(UTF-8));
  9. no warnings 'utf8';
  10. use English;
  11. use base;
  12. use FindBin '$Bin';
  13. use lib "/opt/Eye/scripts";
  14. use strict;
  15. use Time::Local;
  16. use FileHandle;
  17. use Data::Dumper;
  18. use eyelib::config;
  19. use eyelib::main;
  20. use eyelib::cmd;
  21. use Net::Patricia;
  22. use Date::Parse;
  23. use eyelib::net_utils;
  24. use eyelib::database;
  25. use eyelib::common;
  26. use DBI;
  27. use Fcntl qw(:flock);
  28. use Parallel::ForkManager;
  29. use Net::DNS;
  30. use Getopt::Long;
  31. #$debug = 1;
  32. open(SELF,"<",$0) or die "Cannot open $0 - $!";
  33. flock(SELF, LOCK_EX|LOCK_NB) or exit 1;
  34. $|=1;
  35. if (IsNotRun($SPID)) { Add_PID($SPID); } else { die "Warning!!! $SPID already runnning!\n"; }
  36. my $fork_count = $cpu_count*10;
  37. #flag for operation status
  38. my $all_ok = 1;
  39. my $changes_only = 0;
  40. my $router_id = undef;
  41. # Парсим аргументы
  42. GetOptions(
  43. 'changes-only|c' => \$changes_only,
  44. 'router-id|r=i' => \$router_id,
  45. ) or die "Ошибка в параметрах!\n";
  46. my @gateways = ();
  47. #save changed records
  48. my @changes_found = get_records_sql($dbh,"SELECT id, ip FROM user_auth WHERE changed=1");
  49. #@office_network_list - все рабочие сети
  50. if ($changes_only) {
  51. my @all_gateways = get_records_sql($dbh,'SELECT * FROM devices WHERE (device_type=2 OR device_type=0) AND protocol>=0 AND (user_acl=1 OR dhcp=1) AND deleted=0 AND vendor_id=9' );
  52. my %network_to_routers;
  53. for my $gate (@all_gateways) {
  54. my $router_id = $gate->{id};
  55. my $connected_only = $gate->{connected_user_only} // 0;
  56. my @subnets_for_router=();
  57. if ($connected_only) {
  58. # Только привязанные подсети
  59. my @gw_subnets = get_records_sql($dbh,"SELECT s.subnet FROM gateway_subnets gs JOIN subnets s ON gs.subnet_id = s.id WHERE gs.device_id = ? AND s.subnet IS NOT NULL", $router_id );
  60. @subnets_for_router = map { $_->{subnet} } @gw_subnets;
  61. } else {
  62. # Все офисные сети
  63. push(@subnets_for_router,@office_network_list);
  64. }
  65. # Добавляем роутер ко всем его подсетям
  66. for my $subnet (@subnets_for_router) {
  67. next unless $subnet && $subnet =~ m{^\d+\.\d+\.\d+\.\d+/\d+$};
  68. $network_to_routers{$subnet} //= {};
  69. $network_to_routers{$subnet}{$router_id} = 1;
  70. }
  71. }
  72. my $GwPat = Net::Patricia->new(AF_INET);
  73. for my $subnet (keys %network_to_routers) {
  74. # Храним ссылку на хеш роутеров
  75. $GwPat->add_string($subnet, \%{$network_to_routers{$subnet}});
  76. }
  77. my %selected_router_ids;
  78. for my $user (@changes_found) {
  79. my $ip = $user->{ip};
  80. next unless $ip && $ip =~ /^\d+\.\d+\.\d+\.\d+$/;
  81. my $data_ref = $GwPat->match_string($ip);
  82. if ($data_ref) {
  83. for my $rid (keys %$data_ref) {
  84. if (defined $router_id) {
  85. $selected_router_ids{$rid} = 1 if ($router_id == $rid);
  86. } else {
  87. $selected_router_ids{$rid} = 1;
  88. }
  89. }
  90. }
  91. }
  92. if (%selected_router_ids) {
  93. my @ids = keys %selected_router_ids;
  94. my $ph = join ',', ('?') x @ids;
  95. @gateways = get_records_sql($dbh, "SELECT * FROM devices WHERE id IN ($ph)", @ids );
  96. } else {
  97. @gateways = (); # Нет затронутых роутеров
  98. }
  99. if (!scalar @gateways) { exit 0; }
  100. }
  101. else {
  102. # Если задан router_id — выбираем один роутер
  103. if (defined $router_id) {
  104. my $router = get_record_sql($dbh, 'SELECT * FROM devices WHERE (device_type=2 OR device_type=0) AND protocol>=0 AND (user_acl=1 OR dhcp=1) AND deleted=0 AND vendor_id=9 AND id=?', $router_id );
  105. if ($router) { push(@gateways, $router); }
  106. } else {
  107. # Иначе выбираем все подходящие роутеры
  108. @gateways = get_records_sql($dbh,'SELECT * FROM devices WHERE (device_type=2 OR device_type=0) AND protocol>=0 AND (user_acl=1 OR dhcp=1) AND deleted=0 AND vendor_id=9' );
  109. }
  110. }
  111. #все сети организации, работающие по dhcp
  112. my $dhcp_networks = new Net::Patricia;
  113. my %dhcp_conf;
  114. my @subnets=get_records_sql($dbh,'SELECT * FROM subnets WHERE dhcp=1 and office=1 and vpn=0 ORDER BY ip_int_start');
  115. foreach my $subnet (@subnets) {
  116. next if (!$subnet->{gateway});
  117. my $dhcp_info=GetDhcpRange($subnet->{subnet});
  118. $dhcp_networks->add_string($subnet->{subnet},$subnet->{subnet});
  119. $dhcp_conf{$subnet->{subnet}}->{first_pool_ip}=IpToStr($subnet->{dhcp_start});
  120. $dhcp_conf{$subnet->{subnet}}->{last_pool_ip}=IpToStr($subnet->{dhcp_stop});
  121. $dhcp_conf{$subnet->{subnet}}->{relay_ip}=IpToStr($subnet->{gateway});
  122. $dhcp_conf{$subnet->{subnet}}->{gateway}=IpToStr($subnet->{gateway});
  123. #раскрываем подсеть
  124. $dhcp_conf{$subnet->{subnet}}->{network} = $dhcp_info->{network};
  125. $dhcp_conf{$subnet->{subnet}}->{masklen} = $dhcp_info->{masklen};
  126. $dhcp_conf{$subnet->{subnet}}->{first_ip} = $dhcp_info->{first_ip};
  127. $dhcp_conf{$subnet->{subnet}}->{last_ip} = $dhcp_info->{last_ip};
  128. $dhcp_conf{$subnet->{subnet}}->{first_ip_aton}=StrToIp($dhcp_info->{first_ip});
  129. $dhcp_conf{$subnet->{subnet}}->{last_ip_aton}=StrToIp($dhcp_info->{last_ip});
  130. }
  131. my $pm = Parallel::ForkManager->new($fork_count);
  132. foreach my $gate (@gateways) {
  133. next if (!$gate);
  134. my $gate_ident = $gate->{device_name}." [$gate->{ip}]:: ";
  135. $pm->start and next;
  136. $dbh = init_db();
  137. my @cmd_list=();
  138. $gate = netdev_set_auth($gate);
  139. $gate->{login}.='+ct400w';
  140. my $t = netdev_login($gate);
  141. if (!$t) {
  142. log_error($gate_ident."Login to $gate->{device_name} [$gate->{ip}] failed! Skip gateway.");
  143. $dbh->disconnect();
  144. $pm->finish;
  145. next;
  146. }
  147. my $router_name=$gate->{device_name};
  148. my $router_ip=$gate->{ip};
  149. my $shaper_enabled = $gate->{queue_enabled};
  150. my $connected_users_only = $gate->{connected_user_only};
  151. my @changed_ref=();
  152. #все сети роутера, которые к нему подключены по информации из БД - Patricia Object
  153. my $connected_users = new Net::Patricia;
  154. #сети, которые должен отдавать роутер по dhcp - simple hash
  155. my %connected_nets_hash;
  156. #исключения из авторизации хот-спота
  157. my %hotspot_exceptions;
  158. my @lan_int=();
  159. my @wan_int=();
  160. my @l3_int = get_records_sql($dbh,'SELECT * FROM device_l3_interfaces WHERE device_id=?',$gate->{'id'});
  161. foreach my $l3 (@l3_int) {
  162. $l3->{'name'}=~s/\"//g;
  163. if ($l3->{'interface_type'} eq '0') { push(@lan_int,$l3->{'name'}); }
  164. if ($l3->{'interface_type'} eq '1') { push(@wan_int,$l3->{'name'}); }
  165. }
  166. #формируем список подключенных к роутеру сетей
  167. my @gw_subnets = get_records_sql($dbh,"SELECT gateway_subnets.*,subnets.subnet FROM gateway_subnets LEFT JOIN subnets ON gateway_subnets.subnet_id = subnets.id WHERE gateway_subnets.device_id=?",$gate->{'id'});
  168. if (@gw_subnets and scalar @gw_subnets) {
  169. foreach my $gw_subnet (@gw_subnets) {
  170. if ($gw_subnet and $gw_subnet->{'subnet'}) {
  171. $connected_users->add_string($gw_subnet->{'subnet'});
  172. $connected_nets_hash{$gw_subnet->{'subnet'}} = $gw_subnet;
  173. }
  174. }
  175. }
  176. #dhcp config
  177. if ($gate->{dhcp}) {
  178. #все сети роутера, которые к нему подключены напрямую фактически - Patricia Object
  179. my $fact_connected_nets = new Net::Patricia;
  180. #интерфейсы, которые будут использоваться для конфигурирования dhcp-сервера
  181. my @work_int=();
  182. #dhcp-сервер, обрабатывающий запросы от dhcp-relay
  183. my @relayed_dhcp = netdev_cmd($gate,$t,"/ip dhcp-server print terse without-paging where relay=255.255.255.255",1);
  184. my $relayed_dhcp_server;
  185. my $relayed_dhcp_interface;
  186. if (@relayed_dhcp and scalar @relayed_dhcp) {
  187. my $dhcp_server = $relayed_dhcp[0];
  188. if ($dhcp_server and $dhcp_server=~/name=(\S+)\s+/i) { $relayed_dhcp_server = $1; }
  189. if ($dhcp_server and $dhcp_server=~/interface=(\S+)\s+/i) { $relayed_dhcp_interface= $1; }
  190. }
  191. #ищем интерфейсы, на которых поднята необходимая для dhcp сервера сеть
  192. foreach my $int (@lan_int) { #interface loop
  193. next if (!$int);
  194. $int=trim($int);
  195. #get ip addr at interface
  196. my @int_addr=netdev_cmd($gate,$t,'/ip address print terse without-paging where interface='.$int,1);
  197. log_debug($gate_ident."Get interfaces: ".Dumper(\@int_addr));
  198. my $found_subnet;
  199. foreach my $int_str(@int_addr) {
  200. $int_str=trim($int_str);
  201. next if (!$int_str);
  202. if ($int_str=~/\s+address=(\S*)\s+/i) {
  203. my $gate_interface=$1;
  204. if ($gate_interface) {
  205. my $gate_ip=$gate_interface;
  206. my $gate_net = GetDhcpRange($gate_interface);
  207. $fact_connected_nets->add_string($gate_net->{network}."/".$gate_net->{masklen});
  208. $gate_ip=~s/\/.*$//;
  209. #search for first match
  210. $found_subnet=$dhcp_networks->match_string($gate_ip);
  211. last;
  212. }
  213. }
  214. }
  215. if (!$found_subnet) { db_log_verbose($dbh,$gate_ident."DHCP subnet for interface $int not found! Skip interface."); next; }
  216. my $dhcp_state;
  217. $dhcp_state->{subnet}=$found_subnet;
  218. $dhcp_state->{interface}=$int;
  219. #формируем список локальных интерфейсов, на котором есть dhcp-сеть
  220. push(@work_int,$dhcp_state);
  221. }
  222. #формируем список сетей, не подключенных к роутеру непосредтственно
  223. my @relayed_subnets=();
  224. foreach my $gw_subnet (keys %connected_nets_hash ) {
  225. next if (!$gw_subnet);
  226. next if ($fact_connected_nets->match_string($gw_subnet));
  227. push(@relayed_subnets,$gw_subnet);
  228. }
  229. if (scalar @relayed_subnets and $relayed_dhcp_interface) {
  230. my $dhcp_state;
  231. $dhcp_state->{interface} = $relayed_dhcp_interface;
  232. $dhcp_state->{subnet} = join(",",@relayed_subnets);
  233. push(@work_int,$dhcp_state);
  234. }
  235. #interface dhcp loop
  236. foreach my $dhcpd_int (@work_int) {
  237. my $found_subnet=$dhcpd_int->{subnet};
  238. my @dhcp_subnets = split(/\,/,$found_subnet);
  239. my $int=$dhcpd_int->{interface};
  240. db_log_verbose($dbh,$gate_ident."Analyze interface $int. Found: ".Dumper($dhcp_conf{$found_subnet}));
  241. #fetch current dhcp records
  242. my @ret_static_leases=netdev_cmd($gate,$t,'/ip dhcp-server lease print terse without-paging where server=dhcp-'.$int,1);
  243. log_debug($gate_ident."Get dhcp leases:".Dumper(\@ret_static_leases));
  244. my @current_static_leases=();
  245. foreach my $str (@ret_static_leases) {
  246. next if (!$str);
  247. $str=trim($str);
  248. if ($str=~/^\d/) {
  249. log_debug($gate_ident."Found current static lease record: ".$str);
  250. push(@current_static_leases,$str);
  251. }
  252. }
  253. #select users for this interface
  254. my @auth_records=();
  255. foreach my $dhcp_subnet (@dhcp_subnets) {
  256. next if (!$dhcp_subnet);
  257. next if (!exists $dhcp_conf{$dhcp_subnet});
  258. my $a_sql = "SELECT * FROM user_auth WHERE deleted = 0 AND dhcp = 1 AND ip_int BETWEEN ? AND ? AND ou_id NOT IN (?, ?) ORDER BY ip_int";
  259. my @tmp1=get_records_sql($dbh,$a_sql,$dhcp_conf{$dhcp_subnet}->{first_ip_aton},$dhcp_conf{$dhcp_subnet}->{last_ip_aton},$default_user_ou_id, $default_hotspot_ou_id);
  260. push(@auth_records,@tmp1);
  261. undef @tmp1;
  262. }
  263. my %leases;
  264. foreach my $lease (@auth_records) {
  265. next if (!$lease);
  266. next if (!$lease->{mac});
  267. next if (!$lease->{ip});
  268. my $found_subnet = $dhcp_networks->match_string($lease->{ip});
  269. next if (!$found_subnet);
  270. next if ($lease->{ip} eq $dhcp_conf{$found_subnet}->{relay_ip});
  271. $leases{$lease->{ip}}{ip}=$lease->{ip};
  272. $leases{$lease->{ip}}{description}=$lease->{id};
  273. $leases{$lease->{ip}}{id}=$lease->{id};
  274. $leases{$lease->{ip}}{dns_name}=$lease->{dns_name};
  275. if ($lease->{description}) { $leases{$lease->{ip}}{description}=translit($lease->{description}); }
  276. $leases{$lease->{ip}}{mac}=uc(mac_splitted($lease->{mac}));
  277. if ($lease->{dhcp_acl}) {
  278. $leases{$lease->{ip}}{acl}=trim($lease->{dhcp_acl});
  279. $leases{$lease->{ip}}{acl}=~s/;/,/g;
  280. if ($leases{$lease->{ip}}{acl}=~/hotspot\-free/) {
  281. $hotspot_exceptions{$leases{$lease->{ip}}{mac}}=$leases{$lease->{ip}}{mac};
  282. $hotspot_exceptions{$leases{$lease->{ip}}{mac}}=$leases{$lease->{ip}}{description} if ($leases{$lease->{ip}}{description});
  283. }
  284. }
  285. if ($lease->{dhcp_option_set}) {
  286. $leases{$lease->{ip}}{dhcp_option_set}=trim($lease->{dhcp_option_set});
  287. }
  288. $leases{$lease->{ip}}{acl}='' if (!$leases{$lease->{ip}}{acl});
  289. $leases{$lease->{ip}}{dhcp_option_set}='' if (!$leases{$lease->{ip}}{dhcp_option_set});
  290. }
  291. my %active_leases;
  292. foreach my $lease (@current_static_leases) {
  293. my @words = split(/\s+/,$lease);
  294. my %tmp_lease;
  295. if ($lease=~/^(\d*)\s+/) { $tmp_lease{id}=$1; };
  296. next if (!defined($tmp_lease{id}));
  297. foreach my $option (@words) {
  298. next if (!$option);
  299. $option=trim($option);
  300. next if (!$option);
  301. my @tmp = split(/\=/,$option);
  302. my $token = trim($tmp[0]);
  303. my $value = trim($tmp[1]);
  304. next if (!$token);
  305. next if (!$value);
  306. $value=~s/\"//g;
  307. if ($token=~/^address$/i) { $tmp_lease{ip}=GetIP($value); }
  308. if ($token=~/^mac-address$/i) { $tmp_lease{mac}=uc(mac_splitted($value)); }
  309. if ($token=~/^address-lists$/i) { $tmp_lease{acl}=$value; }
  310. if ($token=~/^dhcp-option-set$/i) { $tmp_lease{dhcp_option_set}=$value; }
  311. }
  312. next if (!$tmp_lease{ip});
  313. next if (!$tmp_lease{mac});
  314. next if ($lease=~/^(\d*)\s+D\s+/);
  315. $active_leases{$tmp_lease{ip}}{ip}=$tmp_lease{ip};
  316. $active_leases{$tmp_lease{ip}}{mac}=$tmp_lease{mac};
  317. $active_leases{$tmp_lease{ip}}{id}=$tmp_lease{id};
  318. $active_leases{$tmp_lease{ip}}{acl}='';
  319. $active_leases{$tmp_lease{ip}}{dhcp_option_set}='';
  320. if ($tmp_lease{acl}) {
  321. $active_leases{$tmp_lease{ip}}{acl}=$tmp_lease{acl};
  322. }
  323. if ($tmp_lease{dhcp_option_set}) {
  324. $active_leases{$tmp_lease{ip}}{dhcp_option_set}=$tmp_lease{dhcp_option_set};
  325. }
  326. }
  327. log_debug($gate_ident."Active leases: ".Dumper(\%active_leases));
  328. #sync state
  329. foreach my $ip (keys %active_leases) {
  330. if (!exists $leases{$ip}) {
  331. db_log_verbose($dbh,$gate_ident."Address $ip not found in stat. Remove from router.");
  332. push(@cmd_list,':foreach i in [/ip dhcp-server lease find where address='.$ip.' ] do={/ip dhcp-server lease remove $i};');
  333. push(@cmd_list,'/ip dhcp-server lease remove [find address='.$ip.']');
  334. push(@cmd_list,'/ip arp remove [find address='.$ip.']');
  335. next;
  336. }
  337. if ($leases{$ip}{mac}!~/$active_leases{$ip}{mac}/i) {
  338. db_log_verbose($dbh,$gate_ident."Mac-address mismatch for ip $ip. stat: $leases{$ip}{mac} active: $active_leases{$ip}{mac}. Remove lease from router.");
  339. push(@cmd_list,':foreach i in [/ip dhcp-server lease find where address='.$ip.' ] do={/ip dhcp-server lease remove $i};');
  340. push(@cmd_list,'/ip dhcp-server lease remove [find address='.$ip.']');
  341. push(@cmd_list,'/ip arp remove [find address='.$ip.']');
  342. next;
  343. }
  344. if (!(!$leases{$ip}{acl} and !$active_leases{$ip}{acl}) and $leases{$ip}{acl} ne $active_leases{$ip}{acl}) {
  345. db_log_error($dbh,$gate_ident."Acl mismatch for ip $ip. stat: $leases{$ip}{acl} active: $active_leases{$ip}{acl}. Remove lease from router.");
  346. push(@cmd_list,':foreach i in [/ip dhcp-server lease find where address='.$ip.' ] do={/ip dhcp-server lease remove $i};');
  347. push(@cmd_list,'/ip dhcp-server lease remove [find address='.$ip.']');
  348. push(@cmd_list,'/ip arp remove [find address='.$ip.']');
  349. next;
  350. }
  351. if (!(!$leases{$ip}{dhcp_option_set} and !$active_leases{$ip}{dhcp_option_set}) and $leases{$ip}{dhcp_option_set} ne $active_leases{$ip}{dhcp_option_set}) {
  352. db_log_error($dbh,$gate_ident."DHCP option-set mismatch for ip $ip. stat: $leases{$ip}{dhcp_option_set} active: $active_leases{$ip}{dhcp_option_set}. Remove lease from router.");
  353. push(@cmd_list,':foreach i in [/ip dhcp-server lease find where address='.$ip.' ] do={/ip dhcp-server lease remove $i};');
  354. push(@cmd_list,'/ip dhcp-server lease remove [find address='.$ip.']');
  355. push(@cmd_list,'/ip arp remove [find address='.$ip.']');
  356. next;
  357. }
  358. }
  359. foreach my $ip (keys %leases) {
  360. my $acl='';
  361. if ($leases{$ip}{acl}) { $acl = 'address-lists='.$leases{$ip}{acl}; }
  362. my $dhcp_option_set='';
  363. if ($leases{$ip}{dhcp_option_set}) { $dhcp_option_set = 'dhcp-option-set='.$leases{$ip}{dhcp_option_set}; }
  364. my $description = $leases{$ip}{description};
  365. $description =~s/\=//g;
  366. my $dns_name='';
  367. if ($leases{$ip}{dns_name}) { $dns_name = $leases{$ip}{dns_name}; }
  368. $dns_name =~s/\=//g;
  369. if ($dns_name) { $description = 'comment="'.$dns_name." - ".$description.'"'; } else { $description = 'comment="'.$description.'"'; }
  370. if (!exists $active_leases{$ip}) {
  371. db_log_verbose($dbh,$gate_ident."Address $ip not found in router. Create static lease record.");
  372. #remove static and dynamic records for mac
  373. 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};');
  374. push(@cmd_list,'/ip dhcp-server lease remove [find mac-address='.uc($leases{$ip}{mac}).']');
  375. #remove current ip binding
  376. push(@cmd_list,':foreach i in [/ip dhcp-server lease find where address='.$ip.' ] do={/ip dhcp-server lease remove $i};');
  377. push(@cmd_list,'/ip dhcp-server lease remove [find address='.$ip.']');
  378. #add new bind
  379. push(@cmd_list,'/ip dhcp-server lease add address='.$ip.' mac-address='.$leases{$ip}{mac}.' '.$acl.' '.$dhcp_option_set.' server=dhcp-'.$int.' '.$description);
  380. #clear arp record
  381. push(@cmd_list,'/ip arp remove [find mac-address='.uc($leases{$ip}{mac}).']');
  382. next;
  383. }
  384. if ($leases{$ip}{mac}!~/$active_leases{$ip}{mac}/i) {
  385. db_log_error($dbh,$gate_ident."Mac-address mismatch for ip $ip. stat: $leases{$ip}{mac} active: $active_leases{$ip}{mac}. Create static lease record.");
  386. #remove static and dynamic records for mac
  387. 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};');
  388. push(@cmd_list,'/ip dhcp-server lease remove [find mac-address='.uc($leases{$ip}{mac}).']');
  389. #remove current ip binding
  390. push(@cmd_list,':foreach i in [/ip dhcp-server lease find where address='.$ip.' ] do={/ip dhcp-server lease remove $i};');
  391. push(@cmd_list,'/ip dhcp-server lease remove [find address='.$ip.']');
  392. #add new bind
  393. push(@cmd_list,'/ip dhcp-server lease add address='.$ip.' mac-address='.$leases{$ip}{mac}.' '.$acl.' '.$dhcp_option_set.' server=dhcp-'.$int.' '.$description);
  394. #clear arp record
  395. push(@cmd_list,'/ip arp remove [find mac-address='.uc($leases{$ip}{mac}).']');
  396. next;
  397. }
  398. if (!(!$leases{$ip}{acl} and !$active_leases{$ip}{acl}) and $leases{$ip}{acl} ne $active_leases{$ip}{acl}) {
  399. db_log_error($dbh,$gate_ident."Acl mismatch for ip $ip. stat: $leases{$ip}{acl} active: $active_leases{$ip}{acl}. Create static lease record.");
  400. 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};');
  401. push(@cmd_list,'/ip dhcp-server lease remove [find mac-address='.uc($leases{$ip}{mac}).']');
  402. push(@cmd_list,'/ip dhcp-server lease add address='.$ip.' mac-address='.$leases{$ip}{mac}.' '.$acl.' '.$dhcp_option_set.' server=dhcp-'.$int.' '.$description);
  403. #clear arp record
  404. push(@cmd_list,'/ip arp remove [find mac-address='.uc($leases{$ip}{mac}).']');
  405. next;
  406. }
  407. if (!(!$leases{$ip}{dhcp_option_set} and !$active_leases{$ip}{dhcp_option_set}) and $leases{$ip}{dhcp_option_set} ne $active_leases{$ip}{dhcp_option_set}) {
  408. db_log_error($dbh,$gate_ident."Acl mismatch for ip $ip. stat: $leases{$ip}{acl} active: $active_leases{$ip}{acl}. Create static lease record.");
  409. 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};');
  410. push(@cmd_list,'/ip dhcp-server lease remove [find mac-address='.uc($leases{$ip}{mac}).']');
  411. push(@cmd_list,'/ip dhcp-server lease add address='.$ip.' mac-address='.$leases{$ip}{mac}.' '.$acl.' '.$dhcp_option_set.' server=dhcp-'.$int.' '.$description);
  412. #clear arp record
  413. push(@cmd_list,'/ip arp remove [find mac-address='.uc($leases{$ip}{mac}).']');
  414. next;
  415. }
  416. }
  417. }#end interface dhcp loop
  418. #check hotspot
  419. my @ret_hotspot = netdev_cmd($gate,$t,'/ip hotspot print terse where disabled=no',1);
  420. #if hotspot found - apply exception
  421. if (@ret_hotspot and scalar(@ret_hotspot)) {
  422. #hotspot exceptions
  423. my @ret_hotspot_bindings=netdev_cmd($gate,$t,'/ip hotspot ip-binding print terse without-paging where type=bypassed',1);
  424. my %actual_hotspot_bindings;
  425. foreach my $row (@ret_hotspot_bindings) {
  426. next if (!$row or $row !~ /^\s*\d/);
  427. my %data;
  428. # Используем регулярное выражение для извлечения пар ключ=значение
  429. while ($row =~/\b(\S+?)=([^\s=]+(?:\s(?!\S+=)[^\s=]+)*)/g) {
  430. my ($key, $value) = ($1, $2);
  431. $data{$key} = $value;
  432. }
  433. if (exists $data{'mac-address'}) {
  434. $actual_hotspot_bindings{$data{'mac-address'}} = $data{'mac-address'};
  435. $actual_hotspot_bindings{$data{'mac-address'}} = $data{description} if (exists $data{description});
  436. }
  437. }
  438. log_debug("Actual bindings:".Dumper(\%actual_hotspot_bindings));
  439. log_debug("Configuration exceptions:".Dumper(\%hotspot_exceptions));
  440. #update binding
  441. foreach my $actual_mac (keys %actual_hotspot_bindings) {
  442. if (!exists $hotspot_exceptions{$actual_mac}) {
  443. db_log_info($dbh,$gate_ident."Address $actual_mac removed from hotspot ip-binding");
  444. push(@cmd_list,':foreach i in [/ip hotspot ip-binding find where mac-address='.uc($actual_mac).' ] do={/ip hotspot ip-binding remove $i};');
  445. }
  446. }
  447. foreach my $actual_mac (keys %hotspot_exceptions) {
  448. if (!exists $actual_hotspot_bindings{$actual_mac}) {
  449. db_log_info($dbh,$gate_ident."Address $actual_mac added to hotspot ip-binding");
  450. push(@cmd_list,':foreach i in [/ip hotspot ip-binding find where mac-address='.uc($actual_mac).' ] do={/ip hotspot ip-binding remove $i};');
  451. push(@cmd_list,'/ip hotspot ip-binding add mac-address='.uc($actual_mac).' type=bypassed comment="'.$hotspot_exceptions{$actual_mac}.'"');
  452. }
  453. }
  454. }
  455. }#end dhcp config
  456. #access lists config
  457. if ($gate->{user_acl}) {
  458. db_log_verbose($dbh,$gate_ident."Sync user state at router $router_name [".$router_ip."] started.");
  459. #get userid list
  460. my $user_auth_sql="SELECT user_auth.ip, user_auth.filter_group_id, user_auth.queue_id, user_auth.id
  461. FROM user_auth, user_list
  462. WHERE user_auth.user_id = user_list.id
  463. AND user_auth.deleted =0
  464. AND user_auth.enabled =1
  465. AND user_auth.blocked =0
  466. AND user_list.blocked =0
  467. AND user_list.enabled =1
  468. AND user_auth.ou_id <> ?
  469. ORDER BY ip_int";
  470. my @authlist_ref = get_records_sql($dbh,$user_auth_sql,$default_hotspot_ou_id);
  471. my %users;
  472. my %lists;
  473. my %found_users;
  474. foreach my $row (@authlist_ref) {
  475. if ($connected_users_only) { next if (!$connected_users->match_string($row->{ip})); }
  476. #skip not office ip's
  477. next if (!$office_networks->match_string($row->{ip}));
  478. $found_users{$row->{'id'}}=$row->{ip};
  479. #filter group acl's
  480. $users{'group_'.$row->{filter_group_id}}->{$row->{ip}}=1;
  481. $users{'group_all'}->{$row->{ip}}=1;
  482. $lists{'group_'.$row->{filter_group_id}}=1;
  483. #queue acl's
  484. if ($row->{queue_id}) { $users{'queue_'.$row->{queue_id}}->{$row->{ip}}=1; }
  485. }
  486. log_debug($gate_ident."Users status:".Dumper(\%users));
  487. #full list
  488. $lists{'group_all'}=1;
  489. #get queue list
  490. my @queuelist_ref = get_records_sql($dbh,"SELECT * FROM queue_list");
  491. my %queues;
  492. foreach my $row (@queuelist_ref) {
  493. $lists{'queue_'.$row->{id}}=1;
  494. next if ((!$row->{download}) and !($row->{upload}));
  495. $queues{'queue_'.$row->{id}}{id}=$row->{id};
  496. $queues{'queue_'.$row->{id}}{down}=$row->{download};
  497. $queues{'queue_'.$row->{id}}{up}=$row->{upload};
  498. }
  499. log_debug($gate_ident."Queues status:".Dumper(\%queues));
  500. my @filter_instances = get_records_sql($dbh,"SELECT * FROM filter_instances");
  501. my @filterlist_ref = get_records_sql($dbh,"SELECT * FROM filter_list where filter_type=0");
  502. my %filters;
  503. my %dyn_filters;
  504. my $max_filter_rec = get_record_sql($dbh,"SELECT MAX(id) as max_filter FROM filter_list");
  505. my $max_filter_id = $max_filter_rec->{max_filter};
  506. my $dyn_filters_base = $max_filter_id+1000;
  507. my $dyn_filters_index = $dyn_filters_base;
  508. foreach my $row (@filterlist_ref) {
  509. #if dst - ip address
  510. if (is_ip($row->{dst})) {
  511. $filters{$row->{id}}->{id}=$row->{id};
  512. $filters{$row->{id}}->{proto}=$row->{proto};
  513. $filters{$row->{id}}->{dst}=$row->{dst};
  514. $filters{$row->{id}}->{dstport}=$row->{dstport};
  515. $filters{$row->{id}}->{srcport}=$row->{srcport};
  516. #set false for dns dst flag
  517. $filters{$row->{id}}->{dns_dst}=0;
  518. } else {
  519. #if dst not ip - check dns record
  520. my @dns_record=ResolveNames($row->{dst},undef);
  521. my $resolved_ips = (scalar @dns_record>0);
  522. next if (!$resolved_ips);
  523. foreach my $resolved_ip (sort @dns_record) {
  524. next if (!$resolved_ip);
  525. #enable dns dst filters
  526. $filters{$row->{id}}->{dns_dst}=1;
  527. #add dynamic dns filter
  528. $filters{$dyn_filters_index}->{id}=$row->{id};
  529. $filters{$dyn_filters_index}->{proto}=$row->{proto};
  530. $filters{$dyn_filters_index}->{dst}=$resolved_ip;
  531. $filters{$dyn_filters_index}->{dstport}=$row->{dstport};
  532. $filters{$dyn_filters_index}->{srcport}=$row->{srcport};
  533. $filters{$dyn_filters_index}->{dns_dst}=0;
  534. #save new filter dns id for original filter id
  535. push(@{$dyn_filters{$row->{id}}},$dyn_filters_index);
  536. $dyn_filters_index++;
  537. }
  538. }
  539. }
  540. log_debug($gate_ident."Filters status:". Dumper(\%filters));
  541. log_debug($gate_ident."DNS-filters status:". Dumper(\%dyn_filters));
  542. #clean unused filter records
  543. do_sql($dbh,"DELETE FROM group_filters WHERE group_id NOT IN (SELECT id FROM group_list)");
  544. do_sql($dbh,"DELETE FROM group_filters WHERE filter_id NOT IN (SELECT id FROM filter_list)");
  545. my @groups_list = get_records_sql($dbh,"SELECT * FROM group_list");
  546. my %groups;
  547. foreach my $group (@groups_list) { $groups{'group_'.$group->{id}}=$group; }
  548. my @grouplist_ref = get_records_sql($dbh,"SELECT group_id,filter_id,rule_order,action FROM group_filters ORDER BY group_filters.group_id,group_filters.rule_order");
  549. my %group_filters;
  550. my $index = 0;
  551. my $cur_group;
  552. foreach my $row (@grouplist_ref) {
  553. if (!$cur_group) { $cur_group = $row->{group_id}; }
  554. if ($cur_group != $row->{group_id}) {
  555. $index = 0;
  556. $cur_group = $row->{group_id};
  557. }
  558. #if dst dns filter not found
  559. if (!$filters{$row->{filter_id}}->{dns_dst}) {
  560. $group_filters{'group_'.$row->{group_id}}->{$index}->{filter_id}=$row->{filter_id};
  561. $group_filters{'group_'.$row->{group_id}}->{$index}->{action}=$row->{action};
  562. $index++;
  563. } else {
  564. #if found dns dst filters - add
  565. if (exists $dyn_filters{$row->{filter_id}}) {
  566. my @dyn_ips = @{$dyn_filters{$row->{filter_id}}};
  567. if (scalar @dyn_ips >0) {
  568. for (my $i = 0; $i < scalar @dyn_ips; $i++) {
  569. $group_filters{'group_'.$row->{group_id}}->{$index}->{filter_id}=$dyn_ips[$i];
  570. $group_filters{'group_'.$row->{group_id}}->{$index}->{action}=$row->{action};
  571. $index++;
  572. }
  573. }
  574. }
  575. }
  576. }
  577. log_debug($gate_ident."Group filters: ".Dumper(\%group_filters));
  578. my %cur_users;
  579. foreach my $group_name (keys %lists) {
  580. my @address_lists=netdev_cmd($gate,$t,'/ip firewall address-list print terse without-paging where list='.$group_name,1);
  581. log_debug($gate_ident."Get address lists:".Dumper(\@address_lists));
  582. foreach my $row (@address_lists) {
  583. $row=trim($row);
  584. next if (!$row);
  585. my @address=split(' ',$row);
  586. foreach my $row (@address) {
  587. if ($row=~/address\=(.*)/i) { $cur_users{$group_name}{$1}=1; }
  588. }
  589. }
  590. }
  591. #new-ips
  592. foreach my $group_name (keys %users) {
  593. foreach my $user_ip (keys %{$users{$group_name}}) {
  594. if (!exists($cur_users{$group_name}{$user_ip})) {
  595. db_log_verbose($dbh,$gate_ident."Add user with ip: $user_ip to access-list $group_name");
  596. push(@cmd_list,"/ip firewall address-list add address=".$user_ip." list=".$group_name);
  597. }
  598. }
  599. }
  600. #old-ips
  601. foreach my $group_name (keys %cur_users) {
  602. foreach my $user_ip (keys %{$cur_users{$group_name}}) {
  603. if (!exists($users{$group_name}{$user_ip})) {
  604. db_log_verbose($dbh,$gate_ident."Remove user with ip: $user_ip from access-list $group_name");
  605. 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};");
  606. }
  607. }
  608. }
  609. timestamp;
  610. #sync firewall rules
  611. #sync group chains
  612. foreach my $filter_instance (@filter_instances) {
  613. my $instance_name = 'Users';
  614. if ($filter_instance->{id}>1) {
  615. $instance_name = 'Users-'.$filter_instance->{name};
  616. #check filter instance exist at gateway
  617. my $instance_ok = get_record_sql($dbh,"SELECT * FROM device_filter_instances WHERE device_id= ? AND instance_id=?", $gate->{'id'}, $filter_instance->{id});
  618. #skip insatnce if not found
  619. if (!$instance_ok) { next; }
  620. }
  621. my @chain_list=netdev_cmd($gate,$t,'/ip firewall filter print terse without-paging where chain='.$instance_name.' and action=jump',1);
  622. log_debug($gate_ident."Get firewall chains:".Dumper(\@chain_list));
  623. my %cur_chain;
  624. foreach my $jump_list (@chain_list) {
  625. next if (!$jump_list);
  626. $jump_list=trim($jump_list);
  627. if ($jump_list=~/jump-target=(\S*)\s+/i) {
  628. if ($1) { $cur_chain{$1}++; }
  629. }
  630. }
  631. #old chains
  632. foreach my $group_name (keys %cur_chain) {
  633. if (!exists($group_filters{$group_name}) or $groups{$group_name}->{instance_id} ne $filter_instance->{id}) {
  634. push (@cmd_list,":foreach i in [/ip firewall filter find where chain=".$instance_name." and action=jump and jump-target=".$group_name."] do={/ip firewall filter remove \$i};");
  635. } else {
  636. if ($cur_chain{$group_name} != 2) {
  637. push (@cmd_list,":foreach i in [/ip firewall filter find where chain=".$instance_name." and action=jump and jump-target=".$group_name."] do={/ip firewall filter remove \$i};");
  638. push (@cmd_list,"/ip firewall filter add chain=".$instance_name." action=jump jump-target=".$group_name." src-address-list=".$group_name);
  639. push (@cmd_list,"/ip firewall filter add chain=".$instance_name." action=jump jump-target=".$group_name." dst-address-list=".$group_name);
  640. }
  641. }
  642. }
  643. #new chains
  644. foreach my $group_name (keys %group_filters) {
  645. if (!exists($cur_chain{$group_name}) and $groups{$group_name}->{instance_id} eq $filter_instance->{id}) {
  646. push (@cmd_list,"/ip firewall filter add chain=".$instance_name." action=jump jump-target=".$group_name." src-address-list=".$group_name);
  647. push (@cmd_list,"/ip firewall filter add chain=".$instance_name." action=jump jump-target=".$group_name." dst-address-list=".$group_name);
  648. }
  649. }
  650. }
  651. my %chain_rules;
  652. foreach my $group_name (sort keys %group_filters) {
  653. next if (!$group_name);
  654. next if (!exists($group_filters{$group_name}));
  655. my %group_filter = %{$group_filters{$group_name}};
  656. foreach my $filter_index (sort keys %group_filter) {
  657. my $filter = $group_filter{$filter_index};
  658. my $filter_id=$filter->{filter_id};
  659. next if (!$filters{$filter_id});
  660. next if ($filters{$filter_id}->{dns_dst});
  661. my $src_rule='chain='.$group_name;
  662. my $dst_rule='chain='.$group_name;
  663. if ($filter->{action}) {
  664. $src_rule=$src_rule." action=accept";
  665. $dst_rule=$dst_rule." action=accept";
  666. } else {
  667. $src_rule=$src_rule." action=reject";
  668. $dst_rule=$dst_rule." action=reject";
  669. }
  670. if ($filters{$filter_id}->{proto} and ($filters{$filter_id}->{proto}!~/all/i)) {
  671. $src_rule=$src_rule." protocol=".$filters{$filter_id}->{proto};
  672. $dst_rule=$dst_rule." protocol=".$filters{$filter_id}->{proto};
  673. }
  674. if ($filters{$filter_id}->{dst} and $filters{$filter_id}->{dst} ne '0/0') {
  675. $src_rule=$src_rule." src-address=".trim($filters{$filter_id}->{dst});
  676. $dst_rule=$dst_rule." dst-address=".trim($filters{$filter_id}->{dst});
  677. }
  678. #dstport and srcport
  679. if (!$filters{$filter_id}->{dstport}) { $filters{$filter_id}->{dstport}=0; }
  680. if (!$filters{$filter_id}->{srcport}) { $filters{$filter_id}->{srcport}=0; }
  681. if ($filters{$filter_id}->{dstport} ne '0' and $filters{$filter_id}->{srcport} ne '0') {
  682. $src_rule=$src_rule." dst-port=".trim($filters{$filter_id}->{srcport})." src-port=".trim($filters{$filter_id}->{dstport});
  683. $dst_rule=$dst_rule." src-port=".trim($filters{$filter_id}->{srcport})." dst-port=".trim($filters{$filter_id}->{dstport});
  684. }
  685. if ($filters{$filter_id}->{dstport} eq '0' and $filters{$filter_id}->{srcport} ne '0') {
  686. $src_rule=$src_rule." dst-port=".trim($filters{$filter_id}->{srcport});
  687. $dst_rule=$dst_rule." src-port=".trim($filters{$filter_id}->{srcport});
  688. }
  689. if ($filters{$filter_id}->{dstport} ne '0' and $filters{$filter_id}->{srcport} eq '0') {
  690. $src_rule=$src_rule." src-port=".trim($filters{$filter_id}->{dstport});
  691. $dst_rule=$dst_rule." dst-port=".trim($filters{$filter_id}->{dstport});
  692. }
  693. if ($src_rule ne $dst_rule) {
  694. push(@{$chain_rules{$group_name}},$src_rule);
  695. push(@{$chain_rules{$group_name}},$dst_rule);
  696. } else {
  697. push(@{$chain_rules{$group_name}},$src_rule);
  698. }
  699. }
  700. }
  701. #chain filters
  702. foreach my $group_name (sort keys %group_filters) {
  703. next if (!$group_name);
  704. my @get_filter=netdev_cmd($gate,$t,'/ip firewall filter print terse without-paging where chain='.$group_name,1);
  705. chomp(@get_filter);
  706. my @cur_filter=();
  707. my $chain_ok=1;
  708. foreach (my $f_index=0; $f_index<scalar(@get_filter); $f_index++) {
  709. my $filter_str=trim($get_filter[$f_index]);
  710. next if (!$filter_str);
  711. next if ($filter_str!~/^(\d){1,3}/);
  712. $filter_str=~s/[^[:ascii:]]//g;
  713. $filter_str=~s/^\d{1,3}\s+//;
  714. $filter_str=trim($filter_str);
  715. next if (!$filter_str);
  716. push(@cur_filter,$filter_str);
  717. }
  718. log_debug($gate_ident."Current filters:".Dumper(\@cur_filter));
  719. log_debug($gate_ident."New filters:".Dumper($chain_rules{$group_name}));
  720. #current state rules
  721. foreach (my $f_index=0; $f_index<scalar(@cur_filter); $f_index++) {
  722. my $filter_str=trim($cur_filter[$f_index]);
  723. if (!$chain_rules{$group_name}[$f_index] or $filter_str!~/$chain_rules{$group_name}[$f_index]/i) {
  724. print "Check chain $group_name error! $filter_str not found in new config. Recreate chain.\n";
  725. $chain_ok=0;
  726. last;
  727. }
  728. }
  729. #new rules
  730. if ($chain_ok and $chain_rules{$group_name} and scalar(@{$chain_rules{$group_name}})) {
  731. foreach (my $f_index=0; $f_index<scalar(@{$chain_rules{$group_name}}); $f_index++) {
  732. my $filter_str=trim($cur_filter[$f_index]);
  733. if (!$filter_str) {
  734. print "Check chain $group_name error! Not found: $chain_rules{$group_name}[$f_index]. Recreate chain.\n";
  735. $chain_ok=0;
  736. last;
  737. }
  738. $filter_str=~s/^\d//;
  739. $filter_str=trim($filter_str);
  740. if ($filter_str!~/$chain_rules{$group_name}[$f_index]/i) {
  741. print "Check chain $group_name error! Expected: $chain_rules{$group_name}[$f_index] Found: $filter_str. Recreate chain.\n";
  742. $chain_ok=0;
  743. last;
  744. }
  745. }
  746. }
  747. if (!$chain_ok) {
  748. push(@cmd_list,":foreach i in [/ip firewall filter find where chain=".$group_name." ] do={/ip firewall filter remove \$i};");
  749. foreach my $filter_str (@{$chain_rules{$group_name}}) {
  750. push(@cmd_list,'/ip firewall filter add '.$filter_str);
  751. }
  752. }
  753. }
  754. if ($shaper_enabled) {
  755. #shapers
  756. my %get_queue_type=();
  757. my %get_queue_tree=();
  758. my %get_filter_mangle=();
  759. my @tmp=netdev_cmd($gate,$t,'/queue type print terse without-paging where name~"pcq_(down|up)load"',1);
  760. log_debug($gate_ident."Get queues: ".Dumper(\@tmp));
  761. # 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
  762. #pcq-src-address-mask=32 pcq-dst-address-mask=32 pcq-src-address6-mask=64 pcq-dst-address6-mask=64
  763. foreach my $row (@tmp) {
  764. next if (!$row);
  765. $row = trim($row);
  766. next if ($row!~/^(\d){1,3}/);
  767. $row=~s/^\d{1,3}\s+//;
  768. next if (!$row);
  769. if ($row=~/name=pcq_(down|up)load_(\d){1,3}\s+/i) {
  770. next if (!$1);
  771. next if (!$2);
  772. my $direct = $1;
  773. my $index = $2;
  774. $get_queue_type{$index}{$direct}=$row;
  775. if ($row=~/pcq-rate=(\S*)\s+\S/i) {
  776. my $rate = $1;
  777. if ($rate=~/k$/i) { $rate =~s/k$//i; }
  778. $get_queue_type{$index}{$direct."-rate"}=$rate;
  779. }
  780. if ($row=~/pcq-classifier=(\S*)\s+\S/i) { $get_queue_type{$index}{$direct."-classifier"}=$1; }
  781. if ($row=~/pcq-src-address-mask=(\S*)\s+\S/i) { $get_queue_type{$index}{$direct."-src-address-mask"}=$1; }
  782. if ($row=~/pcq-dst-address-mask=(\S*)\s+\S/i) { $get_queue_type{$index}{$direct."-dst-address-mask"}=$1; }
  783. }
  784. }
  785. @tmp=();
  786. @tmp=netdev_cmd($gate,$t,'/queue tree print terse without-paging where parent~"(download|upload)_root"',1);
  787. log_debug($gate_ident."Get root queues: ".Dumper(\@tmp));
  788. #print Dumper(\@tmp);
  789. # 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
  790. # 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
  791. foreach my $row (@tmp) {
  792. next if (!$row);
  793. $row = trim($row);
  794. next if ($row!~/^(\d)/);
  795. $row=~s/^(\d*)\s+//;
  796. next if (!$row);
  797. if ($row=~/queue=pcq_(down|up)load_(\d){1,3}/i) {
  798. if ($row=~/name=queue_(\d){1,3}_(\S*)_out\s+/i) {
  799. next if (!$1);
  800. next if (!$2);
  801. my $index = $1;
  802. my $int_name = $2;
  803. $get_queue_tree{$index}{$int_name}{up}=$row;
  804. if ($row=~/parent=(\S*)\s+\S/i) { $get_queue_tree{$index}{$int_name}{'up-parent'}=$1; }
  805. if ($row=~/packet-mark=(\S*)\s+\S/i) { $get_queue_tree{$index}{$int_name}{'up-mark'}=$1; }
  806. if ($row=~/queue=(\S*)\s+\S/i) { $get_queue_tree{$index}{$int_name}{'up-queue'}=$1; }
  807. }
  808. if ($row=~/name=queue_(\d){1,3}_(\S*)_in\s+/i) {
  809. next if (!$1);
  810. next if (!$2);
  811. my $index = $1;
  812. my $int_name = $2;
  813. $get_queue_tree{$index}{$int_name}{down}=$row;
  814. if ($row=~/parent=(\S*)\s+\S/i) { $get_queue_tree{$index}{$int_name}{'down-parent'}=$1; }
  815. if ($row=~/packet-mark=(\S*)\s+\S/i) { $get_queue_tree{$index}{$int_name}{'down-mark'}=$1; }
  816. if ($row=~/queue=(\S*)\s+\S/i) { $get_queue_tree{$index}{$int_name}{'down-queue'}=$1; }
  817. }
  818. }
  819. }
  820. @tmp=();
  821. @tmp=netdev_cmd($gate,$t,'/ip firewall mangle print terse without-paging where action=mark-packet and new-packet-mark~"(upload|download)_[0-9]{1,3}"',1);
  822. log_debug($gate_ident."Get firewall mangle rules for queues:".Dumper(\@tmp));
  823. # 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=""
  824. # 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=""
  825. foreach my $row (@tmp) {
  826. next if (!$row);
  827. $row = trim($row);
  828. next if ($row!~/^(\d){1,3}/);
  829. $row=~s/^\d{1,3}\s+//;
  830. next if (!$row);
  831. if ($row=~/new-packet-mark=upload_(\d){1,3}_(\S*)\s+/i) {
  832. next if (!$1);
  833. next if (!$2);
  834. my $index = $1;
  835. my $int_name = $2;
  836. $get_filter_mangle{$index}{$int_name}{up}=$row;
  837. if ($row=~/src-address-list=(\S*)\s+\S/i) { $get_filter_mangle{$index}{$int_name}{'up-list'}=$1; }
  838. if ($row=~/out-interface=(\S*)\s+\S/i) { $get_filter_mangle{$index}{$int_name}{'up-dev'}=$1; }
  839. if ($row=~/new-packet-mark=(\S*)\s+\S/i) { $get_filter_mangle{$index}{$int_name}{'up-mark'}=$1; }
  840. }
  841. if ($row=~/new-packet-mark=download_(\d){1,3}_(\S*)\s+/i) {
  842. next if (!$1);
  843. next if (!$2);
  844. my $index = $1;
  845. my $int_name = $2;
  846. $get_filter_mangle{$index}{$int_name}{down}=$row;
  847. if ($row=~/dst-address-list=(\S*)\s+\S/i) { $get_filter_mangle{$index}{$int_name}{'down-list'}=$1; }
  848. if ($row=~/new-packet-mark=(\S*)\s+\S/i) { $get_filter_mangle{$index}{$int_name}{'down-mark'}=$1; }
  849. if ($row=~/out-interface=(\S*)\s+\S/i) { $get_filter_mangle{$index}{$int_name}{'down-dev'}=$1; }
  850. }
  851. }
  852. log_debug($gate_ident."Queues type status:".Dumper(\%get_queue_type));
  853. log_debug($gate_ident."Queues tree status:".Dumper(\%get_queue_tree));
  854. log_debug($gate_ident."Firewall mangle status:".Dumper(\%get_filter_mangle));
  855. my %queue_type;
  856. my %queue_tree;
  857. my %filter_mangle;
  858. #generate new config
  859. foreach my $queue_name (keys %queues) {
  860. my $q_id=$queues{$queue_name}{id};
  861. my $q_up=$queues{$queue_name}{up}+1;
  862. my $q_down=$queues{$queue_name}{down}+1;
  863. #queue_types
  864. $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";
  865. $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";
  866. my $queue_ok=1;
  867. if (!$get_queue_type{$q_id}{up}) { $queue_ok=0; }
  868. if ($queue_ok and abs($q_up - $get_queue_type{$q_id}{'up-rate'})>10) { $queue_ok=0; }
  869. if ($queue_ok and $get_queue_type{$q_id}{'up-classifier'}!~/src-address/i) { $queue_ok=0; }
  870. if (!$queue_ok) {
  871. push(@cmd_list,':foreach i in [/queue type find where name~"pcq_upload_'.$q_id.'" ] do={/queue type remove $i};');
  872. push(@cmd_list,'/queue type add '.$queue_type{$q_id}{up});
  873. }
  874. $queue_ok=1;
  875. if (!$get_queue_type{$q_id}{down}) { $queue_ok=0; }
  876. if ($queue_ok and abs($q_up - $get_queue_type{$q_id}{'down-rate'})>10) { $queue_ok=0; }
  877. if ($queue_ok and $get_queue_type{$q_id}{'down-classifier'}!~/dst-address/i) { $queue_ok=0; }
  878. if (!$queue_ok) {
  879. push(@cmd_list,':foreach i in [/queue type find where name~"pcq_download_'.$q_id.'" ] do={/queue type remove $i};');
  880. push(@cmd_list,'/queue type add '.$queue_type{$q_id}{down});
  881. }
  882. #upload queue
  883. foreach my $int (@wan_int) {
  884. $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";
  885. $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=\"\"";
  886. $queue_ok=1;
  887. if (!$get_queue_tree{$q_id}{$int}{up}) { $queue_ok=0; }
  888. if ($queue_ok and ($get_queue_tree{$q_id}{$int}{'up-parent'} ne "upload_root_".$int)) { $queue_ok=0;}
  889. if ($queue_ok and ($get_queue_tree{$q_id}{$int}{'up-mark'} ne "upload_".$q_id."_".$int)) { $queue_ok=0; }
  890. if ($queue_ok and ($get_queue_tree{$q_id}{$int}{'up-queue'} ne "pcq_upload_".$q_id)) { $queue_ok=0; }
  891. if (!$queue_ok) {
  892. push(@cmd_list,':foreach i in [/queue tree find where name~"queue_'.$q_id."_".$int."_out".'" ] do={/queue tree remove $i};');
  893. push(@cmd_list,'/queue tree add '.$queue_tree{$q_id}{$int}{up});
  894. }
  895. $queue_ok=1;
  896. if (!$get_filter_mangle{$q_id}{$int}{up}) { $queue_ok=0; }
  897. if ($queue_ok and ($get_filter_mangle{$q_id}{$int}{'up-mark'} ne "upload_".$q_id."_".$int)) { $queue_ok=0; }
  898. if ($queue_ok and ($get_filter_mangle{$q_id}{$int}{'up-list'} ne "queue_".$q_id)) { $queue_ok=0; }
  899. if ($queue_ok and ($get_filter_mangle{$q_id}{$int}{'up-dev'} ne $int)) { $queue_ok=0; }
  900. if (!$queue_ok) {
  901. 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};');
  902. push(@cmd_list,'/ip firewall mangle add '.$filter_mangle{$q_id}{$int}{up});
  903. }
  904. }
  905. #download
  906. foreach my $int (@lan_int) {
  907. next if (!$int);
  908. $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";
  909. $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=\"\"";
  910. $queue_ok=1;
  911. if (!$get_queue_tree{$q_id}{$int}{down}) { $queue_ok=0; }
  912. if ($queue_ok and ($get_queue_tree{$q_id}{$int}{'down-parent'} ne "download_root_".$int)) { $queue_ok=0; }
  913. if ($queue_ok and ($get_queue_tree{$q_id}{$int}{'down-mark'} ne "download_".$q_id."_".$int)) { $queue_ok=0; }
  914. if ($queue_ok and ($get_queue_tree{$q_id}{$int}{'down-queue'} ne "pcq_download_".$q_id)) { $queue_ok=0; }
  915. if (!$queue_ok) {
  916. push(@cmd_list,':foreach i in [/queue tree find where name~"queue_'.$q_id."_".$int."_in".'" ] do={/queue tree remove $i};');
  917. push(@cmd_list,'/queue tree add '.$queue_tree{$q_id}{$int}{down});
  918. }
  919. $queue_ok=1;
  920. if (!$get_filter_mangle{$q_id}{$int}{down}) { $queue_ok=0; }
  921. if ($queue_ok and ($get_filter_mangle{$q_id}{$int}{'down-mark'} ne "download_".$q_id."_".$int)) { $queue_ok=0; }
  922. if ($queue_ok and ($get_filter_mangle{$q_id}{$int}{'down-list'} ne "queue_".$q_id)) { $queue_ok=0; }
  923. if ($queue_ok and ($get_filter_mangle{$q_id}{$int}{'down-dev'} ne $int)) { $queue_ok=0; }
  924. if (!$queue_ok) {
  925. 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};');
  926. push(@cmd_list,'/ip firewall mangle add '.$filter_mangle{$q_id}{$int}{down});
  927. }
  928. }
  929. #end shaper
  930. }
  931. }
  932. }#end access lists config
  933. if (scalar(@cmd_list)) {
  934. log_debug($gate_ident."Apply:");
  935. if ($debug) { foreach my $cmd (@cmd_list) { log_debug($gate_ident."$cmd"); } }
  936. eval {
  937. netdev_cmd($gate,$t,\@cmd_list,1);
  938. };
  939. if ($@) {
  940. $all_ok = 0;
  941. log_debug($gate_ident."Error programming gateway! Err: ".$@);
  942. }
  943. }
  944. db_log_verbose($dbh,$gate_ident."Sync user state stopped.");
  945. $dbh->disconnect();
  946. $pm->finish;
  947. }
  948. $pm->wait_all_children;
  949. #clear changed
  950. if ($all_ok) {
  951. foreach my $row (@changes_found) {
  952. do_sql($dbh,"UPDATE user_auth SET changed=0 WHERE id=?",$row->{id});
  953. }
  954. }
  955. if (IsMyPID($SPID)) { Remove_PID($SPID); };
  956. do_exit 0;