sync_mikrotik.pl 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353
  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. # Helper для парсинга вывода Mikrotik
  32. my $parse_mikrotik_line = sub {
  33. my $line = shift;
  34. return undef unless defined $line;
  35. $line = trim($line);
  36. return undef unless $line =~ /^\s*\d/;
  37. $line =~ s/^\s*\d+\s+//;
  38. return $line;
  39. };
  40. #$debug = 1;
  41. open(SELF,"<",$0) or die "Cannot open $0 - $!";
  42. flock(SELF, LOCK_EX|LOCK_NB) or exit 1;
  43. $|=1;
  44. if (IsNotRun($SPID)) { Add_PID($SPID); } else { die "Warning!!! $SPID already runnning!\n"; }
  45. my $fork_count = $cpu_count*10;
  46. #flag for operation status
  47. my $all_ok = 1;
  48. my $changes_only = 0;
  49. my $router_id = undef;
  50. # Парсим аргументы
  51. GetOptions(
  52. 'changes-only|c' => \$changes_only,
  53. 'router-id|r=i' => \$router_id,
  54. ) or die "Ошибка в параметрах!\n";
  55. my @gateways = ();
  56. #save changed records
  57. my @changes_found = get_records_sql($dbh,"SELECT id, ip FROM user_auth WHERE changed=1");
  58. #@office_network_list - все рабочие сети
  59. if ($changes_only) {
  60. 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' );
  61. my %network_to_routers;
  62. for my $gate (@all_gateways) {
  63. my $router_id = $gate->{id};
  64. my $connected_only = $gate->{connected_user_only} // 0;
  65. my @subnets_for_router=();
  66. if ($connected_only) {
  67. # Только привязанные подсети
  68. 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 );
  69. @subnets_for_router = map { $_->{subnet} } @gw_subnets;
  70. } else {
  71. # Все офисные сети
  72. push(@subnets_for_router,@office_network_list);
  73. }
  74. # Добавляем роутер ко всем его подсетям
  75. for my $subnet (@subnets_for_router) {
  76. next unless $subnet && $subnet =~ m{^\d+\.\d+\.\d+\.\d+/\d+$};
  77. $network_to_routers{$subnet} //= {};
  78. $network_to_routers{$subnet}{$router_id} = 1;
  79. }
  80. }
  81. my $GwPat = Net::Patricia->new(AF_INET);
  82. for my $subnet (keys %network_to_routers) {
  83. # Храним ссылку на хеш роутеров
  84. $GwPat->add_string($subnet, \%{$network_to_routers{$subnet}});
  85. }
  86. my %selected_router_ids;
  87. for my $user (@changes_found) {
  88. my $ip = $user->{ip};
  89. next unless $ip && $ip =~ /^\d+\.\d+\.\d+\.\d+$/;
  90. my $data_ref = $GwPat->match_string($ip);
  91. if ($data_ref) {
  92. for my $rid (keys %$data_ref) {
  93. if (defined $router_id) {
  94. $selected_router_ids{$rid} = 1 if ($router_id == $rid);
  95. } else {
  96. $selected_router_ids{$rid} = 1;
  97. }
  98. }
  99. }
  100. }
  101. if (%selected_router_ids) {
  102. my @ids = keys %selected_router_ids;
  103. my $ph = join ',', ('?') x @ids;
  104. @gateways = get_records_sql($dbh, "SELECT * FROM devices WHERE id IN ($ph)", @ids );
  105. } else {
  106. @gateways = (); # Нет затронутых роутеров
  107. }
  108. if (!scalar @gateways) { exit 0; }
  109. }
  110. else {
  111. # Если задан router_id — выбираем один роутер
  112. if (defined $router_id) {
  113. 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 );
  114. if ($router) { push(@gateways, $router); }
  115. } else {
  116. # Иначе выбираем все подходящие роутеры
  117. @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' );
  118. }
  119. }
  120. #все сети организации, работающие по dhcp
  121. my $dhcp_networks = new Net::Patricia;
  122. my %dhcp_conf;
  123. my @subnets=get_records_sql($dbh,'SELECT * FROM subnets WHERE dhcp=1 and office=1 and vpn=0 ORDER BY ip_int_start');
  124. foreach my $subnet (@subnets) {
  125. next if (!$subnet->{gateway});
  126. my $dhcp_info=GetDhcpRange($subnet->{subnet});
  127. $dhcp_networks->add_string($subnet->{subnet},$subnet->{subnet});
  128. $dhcp_conf{$subnet->{subnet}}->{first_pool_ip}=IpToStr($subnet->{dhcp_start});
  129. $dhcp_conf{$subnet->{subnet}}->{last_pool_ip}=IpToStr($subnet->{dhcp_stop});
  130. $dhcp_conf{$subnet->{subnet}}->{relay_ip}=IpToStr($subnet->{gateway});
  131. $dhcp_conf{$subnet->{subnet}}->{gateway}=IpToStr($subnet->{gateway});
  132. #раскрываем подсеть
  133. $dhcp_conf{$subnet->{subnet}}->{network} = $dhcp_info->{network};
  134. $dhcp_conf{$subnet->{subnet}}->{masklen} = $dhcp_info->{masklen};
  135. $dhcp_conf{$subnet->{subnet}}->{first_ip} = $dhcp_info->{first_ip};
  136. $dhcp_conf{$subnet->{subnet}}->{last_ip} = $dhcp_info->{last_ip};
  137. $dhcp_conf{$subnet->{subnet}}->{first_ip_aton}=StrToIp($dhcp_info->{first_ip});
  138. $dhcp_conf{$subnet->{subnet}}->{last_ip_aton}=StrToIp($dhcp_info->{last_ip});
  139. }
  140. my $pm = Parallel::ForkManager->new($fork_count);
  141. foreach my $gate (@gateways) {
  142. next if (!$gate);
  143. my $gate_ident = $gate->{device_name}." [$gate->{ip}]:: ";
  144. $pm->start and next;
  145. $dbh = init_db();
  146. my @cmd_list=();
  147. $gate = netdev_set_auth($gate);
  148. $gate->{login}.='+ct400w';
  149. my $t = netdev_login($gate);
  150. if (!$t) {
  151. log_error($gate_ident."Login to $gate->{device_name} [$gate->{ip}] failed! Skip gateway.");
  152. $dbh->disconnect();
  153. $pm->finish;
  154. next;
  155. }
  156. my $router_name=$gate->{device_name};
  157. my $router_ip=$gate->{ip};
  158. my $shaper_enabled = $gate->{queue_enabled};
  159. my $connected_users_only = $gate->{connected_user_only};
  160. my @changed_ref=();
  161. #все сети роутера, которые к нему подключены по информации из БД - Patricia Object
  162. my $connected_users = new Net::Patricia;
  163. #сети, которые должен отдавать роутер по dhcp - simple hash
  164. my %connected_nets_hash;
  165. #исключения из авторизации хот-спота
  166. my %hotspot_exceptions;
  167. my @lan_int=();
  168. my @wan_int=();
  169. # настройки испольуземых l3-интерфейсов
  170. my %l3_interfaces;
  171. my @l3_int = get_records_sql($dbh,'SELECT * FROM device_l3_interfaces WHERE device_id=?',$gate->{'id'});
  172. foreach my $l3 (@l3_int) {
  173. $l3->{'name'}=~s/\"//g;
  174. $l3_interfaces{$l3->{'name'}}{type} = $l3->{'interface_type'};
  175. $l3_interfaces{$l3->{'name'}}{bandwidth} = 0;
  176. if ($l3->{'bandwidth'}) { $l3_interfaces{$l3->{'name'}}{bandwidth} = $l3->{'bandwidth'}; }
  177. if ($l3->{'interface_type'} eq '0') { push(@lan_int,$l3->{'name'}); }
  178. if ($l3->{'interface_type'} eq '1') { push(@wan_int,$l3->{'name'}); }
  179. }
  180. #формируем список подключенных к роутеру сетей
  181. 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'});
  182. if (@gw_subnets and scalar @gw_subnets) {
  183. foreach my $gw_subnet (@gw_subnets) {
  184. if ($gw_subnet and $gw_subnet->{'subnet'}) {
  185. $connected_users->add_string($gw_subnet->{'subnet'});
  186. $connected_nets_hash{$gw_subnet->{'subnet'}} = $gw_subnet;
  187. }
  188. }
  189. }
  190. #dhcp config
  191. if ($gate->{dhcp}) {
  192. #все сети роутера, которые к нему подключены напрямую фактически - Patricia Object
  193. my $fact_connected_nets = new Net::Patricia;
  194. #интерфейсы, которые будут использоваться для конфигурирования dhcp-сервера
  195. my @work_int=();
  196. #dhcp-сервер, обрабатывающий запросы от dhcp-relay
  197. my @relayed_dhcp = netdev_cmd($gate,$t,"/ip dhcp-server print terse without-paging where relay=255.255.255.255",1);
  198. my $relayed_dhcp_server;
  199. my $relayed_dhcp_interface;
  200. if (@relayed_dhcp and scalar @relayed_dhcp) {
  201. my $dhcp_server = $relayed_dhcp[0];
  202. if ($dhcp_server and $dhcp_server=~/name=(\S+)\s+/i) { $relayed_dhcp_server = $1; }
  203. if ($dhcp_server and $dhcp_server=~/interface=(\S+)\s+/i) { $relayed_dhcp_interface= $1; }
  204. }
  205. #ищем интерфейсы, на которых поднята необходимая для dhcp сервера сеть
  206. foreach my $int (@lan_int) { #interface loop
  207. next if (!$int);
  208. $int=trim($int);
  209. #get ip addr at interface
  210. my @int_addr=netdev_cmd($gate,$t,'/ip address print terse without-paging where interface='.$int,1);
  211. log_debug($gate_ident."Get interfaces: ".Dumper(\@int_addr));
  212. my $found_subnet;
  213. foreach my $row (@int_addr) {
  214. my $int_str = $parse_mikrotik_line->($row);
  215. next unless $int_str;
  216. if ($int_str=~/\s+address=(\S*)\s+/i) {
  217. my $gate_interface=$1;
  218. if ($gate_interface) {
  219. my $gate_ip=$gate_interface;
  220. my $gate_net = GetDhcpRange($gate_interface);
  221. $fact_connected_nets->add_string($gate_net->{network}."/".$gate_net->{masklen});
  222. $gate_ip=~s/\/.*$//;
  223. #search for first match
  224. $found_subnet=$dhcp_networks->match_string($gate_ip);
  225. last;
  226. }
  227. }
  228. }
  229. if (!$found_subnet) { db_log_verbose($dbh,$gate_ident."DHCP subnet for interface $int not found! Skip interface."); next; }
  230. my $dhcp_state;
  231. $dhcp_state->{subnet}=$found_subnet;
  232. $dhcp_state->{interface}=$int;
  233. #формируем список локальных интерфейсов, на котором есть dhcp-сеть
  234. push(@work_int,$dhcp_state);
  235. }
  236. #формируем список сетей, не подключенных к роутеру непосредтственно
  237. my @relayed_subnets=();
  238. foreach my $gw_subnet (keys %connected_nets_hash ) {
  239. next if (!$gw_subnet);
  240. next if ($fact_connected_nets->match_string($gw_subnet));
  241. push(@relayed_subnets,$gw_subnet);
  242. }
  243. if (scalar @relayed_subnets and $relayed_dhcp_interface) {
  244. my $dhcp_state;
  245. $dhcp_state->{interface} = $relayed_dhcp_interface;
  246. $dhcp_state->{subnet} = join(",",@relayed_subnets);
  247. push(@work_int,$dhcp_state);
  248. }
  249. #interface dhcp loop
  250. foreach my $dhcpd_int (@work_int) {
  251. my $found_subnet=$dhcpd_int->{subnet};
  252. my @dhcp_subnets = split(/\,/,$found_subnet);
  253. my $int=$dhcpd_int->{interface};
  254. db_log_verbose($dbh,$gate_ident."Analyze interface $int. Found: ".Dumper($dhcp_conf{$found_subnet}));
  255. #fetch current dhcp records
  256. my @ret_static_leases=netdev_cmd($gate,$t,'/ip dhcp-server lease print terse without-paging where server=dhcp-'.$int,1);
  257. log_debug($gate_ident."Get dhcp leases:".Dumper(\@ret_static_leases));
  258. my @current_static_leases=();
  259. foreach my $str (@ret_static_leases) {
  260. next if (!$str);
  261. $str=trim($str);
  262. if ($str=~/^\d/) {
  263. log_debug($gate_ident."Found current static lease record: ".$str);
  264. push(@current_static_leases,$str);
  265. }
  266. }
  267. #select users for this interface
  268. my @auth_records=();
  269. foreach my $dhcp_subnet (@dhcp_subnets) {
  270. next if (!$dhcp_subnet);
  271. next if (!exists $dhcp_conf{$dhcp_subnet});
  272. 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";
  273. 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);
  274. push(@auth_records,@tmp1);
  275. undef @tmp1;
  276. }
  277. my %leases;
  278. foreach my $lease (@auth_records) {
  279. next if (!$lease);
  280. next if (!$lease->{mac});
  281. next if (!$lease->{ip});
  282. my $found_subnet = $dhcp_networks->match_string($lease->{ip});
  283. next if (!$found_subnet);
  284. next if ($lease->{ip} eq $dhcp_conf{$found_subnet}->{relay_ip});
  285. $leases{$lease->{ip}}{ip}=$lease->{ip};
  286. $leases{$lease->{ip}}{description}=$lease->{id};
  287. $leases{$lease->{ip}}{id}=$lease->{id};
  288. $leases{$lease->{ip}}{dns_name}=$lease->{dns_name};
  289. if ($lease->{description}) { $leases{$lease->{ip}}{description}=translit($lease->{description}); }
  290. $leases{$lease->{ip}}{mac}=uc(mac_splitted($lease->{mac}));
  291. if ($lease->{dhcp_acl}) {
  292. $leases{$lease->{ip}}{acl}=trim($lease->{dhcp_acl});
  293. $leases{$lease->{ip}}{acl}=~s/;/,/g;
  294. if ($leases{$lease->{ip}}{acl}=~/hotspot\-free/) {
  295. $hotspot_exceptions{$leases{$lease->{ip}}{mac}}=$leases{$lease->{ip}}{mac};
  296. $hotspot_exceptions{$leases{$lease->{ip}}{mac}}=$leases{$lease->{ip}}{description} if ($leases{$lease->{ip}}{description});
  297. }
  298. }
  299. if ($lease->{dhcp_option_set}) {
  300. $leases{$lease->{ip}}{dhcp_option_set}=trim($lease->{dhcp_option_set});
  301. }
  302. $leases{$lease->{ip}}{acl}='' if (!$leases{$lease->{ip}}{acl});
  303. $leases{$lease->{ip}}{dhcp_option_set}='' if (!$leases{$lease->{ip}}{dhcp_option_set});
  304. }
  305. my %active_leases;
  306. foreach my $lease (@current_static_leases) {
  307. my @words = split(/\s+/,$lease);
  308. my %tmp_lease;
  309. if ($lease=~/^(\d*)\s+/) { $tmp_lease{id}=$1; };
  310. next if (!defined($tmp_lease{id}));
  311. foreach my $option (@words) {
  312. next if (!$option);
  313. $option=trim($option);
  314. next if (!$option);
  315. my @tmp = split(/\=/,$option);
  316. my $token = trim($tmp[0]);
  317. my $value = trim($tmp[1]);
  318. next if (!$token);
  319. next if (!$value);
  320. $value=~s/\"//g;
  321. if ($token=~/^address$/i) { $tmp_lease{ip}=GetIP($value); }
  322. if ($token=~/^mac-address$/i) { $tmp_lease{mac}=uc(mac_splitted($value)); }
  323. if ($token=~/^address-lists$/i) { $tmp_lease{acl}=$value; }
  324. if ($token=~/^dhcp-option-set$/i) { $tmp_lease{dhcp_option_set}=$value; }
  325. }
  326. next if (!$tmp_lease{ip});
  327. next if (!$tmp_lease{mac});
  328. next if ($lease=~/^(\d*)\s+D\s+/);
  329. $active_leases{$tmp_lease{ip}}{ip}=$tmp_lease{ip};
  330. $active_leases{$tmp_lease{ip}}{mac}=$tmp_lease{mac};
  331. $active_leases{$tmp_lease{ip}}{id}=$tmp_lease{id};
  332. $active_leases{$tmp_lease{ip}}{acl}='';
  333. $active_leases{$tmp_lease{ip}}{dhcp_option_set}='';
  334. if ($tmp_lease{acl}) {
  335. $active_leases{$tmp_lease{ip}}{acl}=$tmp_lease{acl};
  336. }
  337. if ($tmp_lease{dhcp_option_set}) {
  338. $active_leases{$tmp_lease{ip}}{dhcp_option_set}=$tmp_lease{dhcp_option_set};
  339. }
  340. }
  341. log_debug($gate_ident."Active leases: ".Dumper(\%active_leases));
  342. #sync state
  343. foreach my $ip (keys %active_leases) {
  344. if (!exists $leases{$ip}) {
  345. db_log_verbose($dbh,$gate_ident."Address $ip not found in stat. Remove 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}{mac}!~/$active_leases{$ip}{mac}/i) {
  352. 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.");
  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. if (!(!$leases{$ip}{acl} and !$active_leases{$ip}{acl}) and $leases{$ip}{acl} ne $active_leases{$ip}{acl}) {
  359. db_log_error($dbh,$gate_ident."Acl mismatch for ip $ip. stat: $leases{$ip}{acl} active: $active_leases{$ip}{acl}. Remove lease from router.");
  360. push(@cmd_list,':foreach i in [/ip dhcp-server lease find where address='.$ip.' ] do={/ip dhcp-server lease remove $i};');
  361. push(@cmd_list,'/ip dhcp-server lease remove [find address='.$ip.']');
  362. push(@cmd_list,'/ip arp remove [find address='.$ip.']');
  363. next;
  364. }
  365. 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}) {
  366. 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.");
  367. push(@cmd_list,':foreach i in [/ip dhcp-server lease find where address='.$ip.' ] do={/ip dhcp-server lease remove $i};');
  368. push(@cmd_list,'/ip dhcp-server lease remove [find address='.$ip.']');
  369. push(@cmd_list,'/ip arp remove [find address='.$ip.']');
  370. next;
  371. }
  372. }
  373. foreach my $ip (keys %leases) {
  374. my $acl='';
  375. if ($leases{$ip}{acl}) { $acl = 'address-lists='.$leases{$ip}{acl}; }
  376. my $dhcp_option_set='';
  377. if ($leases{$ip}{dhcp_option_set}) { $dhcp_option_set = 'dhcp-option-set='.$leases{$ip}{dhcp_option_set}; }
  378. my $description = $leases{$ip}{description};
  379. $description =~s/\=//g;
  380. my $dns_name='';
  381. if ($leases{$ip}{dns_name}) { $dns_name = $leases{$ip}{dns_name}; }
  382. $dns_name =~s/\=//g;
  383. if ($dns_name) { $description = 'comment="'.$dns_name." - ".$description.'"'; } else { $description = 'comment="'.$description.'"'; }
  384. if (!exists $active_leases{$ip}) {
  385. db_log_verbose($dbh,$gate_ident."Address $ip not found in router. 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}{mac}!~/$active_leases{$ip}{mac}/i) {
  399. 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.");
  400. #remove static and dynamic records for mac
  401. 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};');
  402. push(@cmd_list,'/ip dhcp-server lease remove [find mac-address='.uc($leases{$ip}{mac}).']');
  403. #remove current ip binding
  404. push(@cmd_list,':foreach i in [/ip dhcp-server lease find where address='.$ip.' ] do={/ip dhcp-server lease remove $i};');
  405. push(@cmd_list,'/ip dhcp-server lease remove [find address='.$ip.']');
  406. #add new bind
  407. push(@cmd_list,'/ip dhcp-server lease add address='.$ip.' mac-address='.$leases{$ip}{mac}.' '.$acl.' '.$dhcp_option_set.' server=dhcp-'.$int.' '.$description);
  408. #clear arp record
  409. push(@cmd_list,'/ip arp remove [find mac-address='.uc($leases{$ip}{mac}).']');
  410. next;
  411. }
  412. if (!(!$leases{$ip}{acl} and !$active_leases{$ip}{acl}) and $leases{$ip}{acl} ne $active_leases{$ip}{acl}) {
  413. db_log_error($dbh,$gate_ident."Acl mismatch for ip $ip. stat: $leases{$ip}{acl} active: $active_leases{$ip}{acl}. Create static lease record.");
  414. 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};');
  415. push(@cmd_list,'/ip dhcp-server lease remove [find mac-address='.uc($leases{$ip}{mac}).']');
  416. push(@cmd_list,'/ip dhcp-server lease add address='.$ip.' mac-address='.$leases{$ip}{mac}.' '.$acl.' '.$dhcp_option_set.' server=dhcp-'.$int.' '.$description);
  417. #clear arp record
  418. push(@cmd_list,'/ip arp remove [find mac-address='.uc($leases{$ip}{mac}).']');
  419. next;
  420. }
  421. 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}) {
  422. db_log_error($dbh,$gate_ident."Acl mismatch for ip $ip. stat: $leases{$ip}{acl} active: $active_leases{$ip}{acl}. Create static lease record.");
  423. 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};');
  424. push(@cmd_list,'/ip dhcp-server lease remove [find mac-address='.uc($leases{$ip}{mac}).']');
  425. push(@cmd_list,'/ip dhcp-server lease add address='.$ip.' mac-address='.$leases{$ip}{mac}.' '.$acl.' '.$dhcp_option_set.' server=dhcp-'.$int.' '.$description);
  426. #clear arp record
  427. push(@cmd_list,'/ip arp remove [find mac-address='.uc($leases{$ip}{mac}).']');
  428. next;
  429. }
  430. }
  431. }#end interface dhcp loop
  432. #check hotspot
  433. my @ret_hotspot = netdev_cmd($gate,$t,'/ip hotspot print terse where disabled=no',1);
  434. #if hotspot found - apply exception
  435. if (@ret_hotspot and scalar(@ret_hotspot)) {
  436. #hotspot exceptions
  437. my @ret_hotspot_bindings=netdev_cmd($gate,$t,'/ip hotspot ip-binding print terse without-paging where type=bypassed',1);
  438. my %actual_hotspot_bindings;
  439. foreach my $row (@ret_hotspot_bindings) {
  440. next if (!$row or $row !~ /^\s*\d/);
  441. my %data;
  442. # Используем регулярное выражение для извлечения пар ключ=значение
  443. while ($row =~/\b(\S+?)=([^\s=]+(?:\s(?!\S+=)[^\s=]+)*)/g) {
  444. my ($key, $value) = ($1, $2);
  445. $data{$key} = $value;
  446. }
  447. if (exists $data{'mac-address'}) {
  448. $actual_hotspot_bindings{$data{'mac-address'}} = $data{'mac-address'};
  449. $actual_hotspot_bindings{$data{'mac-address'}} = $data{description} if (exists $data{description});
  450. }
  451. }
  452. log_debug("Hotspot actual bindings:".Dumper(\%actual_hotspot_bindings));
  453. log_debug("Hotspot configuration exceptions:".Dumper(\%hotspot_exceptions));
  454. #update binding
  455. foreach my $actual_mac (keys %actual_hotspot_bindings) {
  456. if (!exists $hotspot_exceptions{$actual_mac}) {
  457. db_log_info($dbh,$gate_ident."Address $actual_mac removed from hotspot ip-binding");
  458. push(@cmd_list,':foreach i in [/ip hotspot ip-binding find where mac-address='.uc($actual_mac).' ] do={/ip hotspot ip-binding remove $i};');
  459. }
  460. }
  461. foreach my $actual_mac (keys %hotspot_exceptions) {
  462. if (!exists $actual_hotspot_bindings{$actual_mac}) {
  463. db_log_info($dbh,$gate_ident."Address $actual_mac added to hotspot ip-binding");
  464. push(@cmd_list,':foreach i in [/ip hotspot ip-binding find where mac-address='.uc($actual_mac).' ] do={/ip hotspot ip-binding remove $i};');
  465. push(@cmd_list,'/ip hotspot ip-binding add mac-address='.uc($actual_mac).' type=bypassed comment="'.$hotspot_exceptions{$actual_mac}.'"');
  466. }
  467. }
  468. }
  469. }#end dhcp config
  470. my %users;
  471. my %lists;
  472. my $group_sql = "SELECT DISTINCT filter_group_id FROM user_auth WHERE deleted = 0 ORDER BY filter_group_id;";
  473. my @grouplist_ref = get_records_sql($dbh,$group_sql);
  474. foreach my $row (@grouplist_ref) {
  475. $lists{'group_'.$row->{filter_group_id}}=1;
  476. }
  477. #full ip list
  478. $lists{'group_all'}=1;
  479. #access lists config
  480. if ($gate->{user_acl}) {
  481. db_log_verbose($dbh,$gate_ident."Sync user state at router $router_name [".$router_ip."] started.");
  482. #get userid list
  483. my $user_auth_sql="SELECT user_auth.ip, user_auth.filter_group_id, user_auth.id
  484. FROM user_auth, user_list
  485. WHERE user_auth.user_id = user_list.id
  486. AND user_auth.deleted =0
  487. AND user_auth.enabled =1
  488. AND user_auth.blocked =0
  489. AND user_list.blocked =0
  490. AND user_list.enabled =1
  491. AND user_auth.ou_id <> ?
  492. ORDER BY ip_int";
  493. my @authlist_ref = get_records_sql($dbh,$user_auth_sql,$default_hotspot_ou_id);
  494. foreach my $row (@authlist_ref) {
  495. if ($connected_users_only) { next if (!$connected_users->match_string($row->{ip})); }
  496. #skip not office ip's
  497. next if (!$office_networks->match_string($row->{ip}));
  498. #filter group acl's
  499. $users{'group_'.$row->{filter_group_id}}->{$row->{ip}}=1;
  500. $users{'group_all'}->{$row->{ip}}=1;
  501. }
  502. log_debug($gate_ident."Users status by ACL:".Dumper(\%users));
  503. my @filter_instances = get_records_sql($dbh,"SELECT * FROM filter_instances");
  504. my @filter_ipsets = get_records_sql($dbh,"SELECT * FROM ipset_list");
  505. my @filterlist_ref = get_records_sql($dbh,"SELECT * FROM filter_list WHERE filter_type=0");
  506. my %filters;
  507. my %dyn_filters;
  508. my $max_filter_rec = get_record_sql($dbh,"SELECT MAX(id) as max_filter FROM filter_list");
  509. my $max_filter_id = $max_filter_rec->{max_filter};
  510. my $dyn_filters_base = $max_filter_id+1000;
  511. my $dyn_filters_index = $dyn_filters_base;
  512. foreach my $row (@filterlist_ref) {
  513. if ($row->{ipset_id} && $row->{ipset_id}>0) {
  514. $filters{$row->{id}}->{id}=$row->{id};
  515. $filters{$row->{id}}->{proto}=$row->{proto};
  516. $filters{$row->{id}}->{dst}=undef;
  517. $filters{$row->{id}}->{ipset_id}=$row->{ipset_id};
  518. $filters{$row->{id}}->{dstport}=$row->{dstport};
  519. $filters{$row->{id}}->{srcport}=$row->{srcport};
  520. $filters{$row->{id}}->{dns_dst}=0;
  521. } else {
  522. if (is_ip($row->{dst})) {
  523. $filters{$row->{id}}->{id}=$row->{id};
  524. $filters{$row->{id}}->{ipset_id}=undef;
  525. $filters{$row->{id}}->{proto}=$row->{proto};
  526. $filters{$row->{id}}->{dst}=$row->{dst};
  527. $filters{$row->{id}}->{dstport}=$row->{dstport};
  528. $filters{$row->{id}}->{srcport}=$row->{srcport};
  529. $filters{$row->{id}}->{dns_dst}=0;
  530. } else {
  531. my @dns_record=ResolveNames($row->{dst},undef);
  532. my $resolved_ips = (scalar @dns_record>0);
  533. next if (!$resolved_ips);
  534. foreach my $resolved_ip (sort @dns_record) {
  535. next if (!$resolved_ip);
  536. $filters{$row->{id}}->{dns_dst}=1;
  537. $filters{$dyn_filters_index}->{id}=$row->{id};
  538. $filters{$dyn_filters_index}->{proto}=$row->{proto};
  539. $filters{$dyn_filters_index}->{dst}=$resolved_ip;
  540. $filters{$dyn_filters_index}->{ipset_id}=undef;
  541. $filters{$dyn_filters_index}->{dstport}=$row->{dstport};
  542. $filters{$dyn_filters_index}->{srcport}=$row->{srcport};
  543. $filters{$dyn_filters_index}->{dns_dst}=0;
  544. push(@{$dyn_filters{$row->{id}}},$dyn_filters_index);
  545. $dyn_filters_index++;
  546. }
  547. }
  548. }
  549. }
  550. log_debug($gate_ident."Filters status:". Dumper(\%filters));
  551. log_debug($gate_ident."DNS-filters status:". Dumper(\%dyn_filters));
  552. #clean unused filter records
  553. do_sql($dbh,"DELETE FROM group_filters WHERE group_id NOT IN (SELECT id FROM group_list)");
  554. do_sql($dbh,"DELETE FROM group_filters WHERE filter_id NOT IN (SELECT id FROM filter_list)");
  555. my @groups_list = get_records_sql($dbh,"SELECT * FROM group_list");
  556. my %groups;
  557. foreach my $group (@groups_list) { $groups{'group_'.$group->{id}}=$group; }
  558. 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");
  559. my %group_filters;
  560. my $index = 0;
  561. my $cur_group;
  562. foreach my $row (@grouplist_ref) {
  563. if (!$cur_group) { $cur_group = $row->{group_id}; }
  564. if ($cur_group != $row->{group_id}) {
  565. $index = 0;
  566. $cur_group = $row->{group_id};
  567. }
  568. #if dst dns filter not found
  569. if (!$filters{$row->{filter_id}}->{dns_dst}) {
  570. $group_filters{'group_'.$row->{group_id}}->{$index}->{filter_id}=$row->{filter_id};
  571. $group_filters{'group_'.$row->{group_id}}->{$index}->{action}=$row->{action};
  572. $index++;
  573. } else {
  574. #if found dns dst filters - add
  575. if (exists $dyn_filters{$row->{filter_id}}) {
  576. my @dyn_ips = @{$dyn_filters{$row->{filter_id}}};
  577. if (scalar @dyn_ips >0) {
  578. for (my $i = 0; $i < scalar @dyn_ips; $i++) {
  579. $group_filters{'group_'.$row->{group_id}}->{$index}->{filter_id}=$dyn_ips[$i];
  580. $group_filters{'group_'.$row->{group_id}}->{$index}->{action}=$row->{action};
  581. $index++;
  582. }
  583. }
  584. }
  585. }
  586. }
  587. log_debug($gate_ident."Group filters: ".Dumper(\%group_filters));
  588. my %cur_ipset_members;
  589. my %ipset_members;
  590. my %ipset_list;
  591. foreach my $ipset_row (@filter_ipsets) {
  592. next if (!$ipset_row);
  593. $ipset_list{$ipset_row->{id}} = $ipset_row->{name};
  594. my @filter_ipset_members = get_records_sql($dbh,"SELECT * FROM ipset_members WHERE ipset_id=?", $ipset_row->{id});
  595. foreach my $ip_row (@filter_ipset_members) { $ipset_members{$ipset_row->{name}}{$ip_row->{ip}} = 1; }
  596. log_verbose($gate_ident."Config ipset $ipset_row->{name} has ".scalar(@filter_ipset_members)." entries");
  597. }
  598. foreach my $ipset_row (@filter_ipsets) {
  599. my @address_lists=netdev_cmd($gate,$t,'/ip firewall address-list print terse without-paging where list='.$ipset_row->{name},1);
  600. log_debug($gate_ident."Get address lists $ipset_row->{name}:".Dumper(\@address_lists));
  601. foreach my $row (@address_lists) {
  602. $row=trim($row);
  603. next if (!$row);
  604. my @address=split(' ',$row);
  605. foreach my $row (@address) {
  606. if ($row=~/address\=(.*)/i) { $cur_ipset_members{$ipset_row->{name}}{$1}=1; }
  607. }
  608. }
  609. }
  610. #new-ips
  611. foreach my $ipset_name (keys %ipset_members) {
  612. foreach my $user_ip (keys %{$ipset_members{$ipset_name}}) {
  613. if (!exists($cur_ipset_members{$ipset_name}{$user_ip})) {
  614. db_log_verbose($dbh,$gate_ident."Add user with ip: $user_ip to access-list $ipset_name");
  615. push(@cmd_list,"/ip firewall address-list add address=".$user_ip." list=".$ipset_name);
  616. }
  617. }
  618. }
  619. #old-ips
  620. foreach my $ipset_name (keys %cur_ipset_members) {
  621. foreach my $user_ip (keys %{$cur_ipset_members{$ipset_name}}) {
  622. if (!exists($ipset_members{$ipset_name}{$user_ip})) {
  623. db_log_verbose($dbh,$gate_ident."Remove user with ip: $user_ip from access-list $ipset_name");
  624. push(@cmd_list,":foreach i in [/ip firewall address-list find where address=".$user_ip." and list=".$ipset_name."] do={/ip firewall address-list remove \$i};");
  625. }
  626. }
  627. }
  628. #sync firewall rules
  629. #sync group chains
  630. foreach my $filter_instance (@filter_instances) {
  631. my $instance_name = 'Users';
  632. if ($filter_instance->{id}>1) {
  633. $instance_name = 'Users-'.$filter_instance->{name};
  634. #check filter instance exist at gateway
  635. my $instance_ok = get_record_sql($dbh,"SELECT * FROM device_filter_instances WHERE device_id= ? AND instance_id=?", $gate->{'id'}, $filter_instance->{id});
  636. #skip insatnce if not found
  637. if (!$instance_ok) { next; }
  638. }
  639. my @chain_list=netdev_cmd($gate,$t,'/ip firewall filter print terse without-paging where chain='.$instance_name.' and action=jump',1);
  640. log_debug($gate_ident."Get firewall chains:".Dumper(\@chain_list));
  641. my %cur_chain;
  642. foreach my $jump_list (@chain_list) {
  643. next if (!$jump_list);
  644. $jump_list=trim($jump_list);
  645. if ($jump_list=~/jump-target=(\S*)\s+/i) {
  646. if ($1) { $cur_chain{$1}++; }
  647. }
  648. }
  649. #old chains
  650. foreach my $group_name (keys %cur_chain) {
  651. if (!exists($group_filters{$group_name}) or $groups{$group_name}->{instance_id} ne $filter_instance->{id}) {
  652. 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};");
  653. } else {
  654. if ($cur_chain{$group_name} != 2) {
  655. 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};");
  656. push (@cmd_list,"/ip firewall filter add chain=".$instance_name." action=jump jump-target=".$group_name." src-address-list=".$group_name);
  657. push (@cmd_list,"/ip firewall filter add chain=".$instance_name." action=jump jump-target=".$group_name." dst-address-list=".$group_name);
  658. }
  659. }
  660. }
  661. #new chains
  662. foreach my $group_name (keys %group_filters) {
  663. if (!exists($cur_chain{$group_name}) and $groups{$group_name}->{instance_id} eq $filter_instance->{id}) {
  664. push (@cmd_list,"/ip firewall filter add chain=".$instance_name." action=jump jump-target=".$group_name." src-address-list=".$group_name);
  665. push (@cmd_list,"/ip firewall filter add chain=".$instance_name." action=jump jump-target=".$group_name." dst-address-list=".$group_name);
  666. }
  667. }
  668. }
  669. my %chain_rules;
  670. foreach my $group_name (sort keys %group_filters) {
  671. next if (!$group_name);
  672. next if (!exists($group_filters{$group_name}));
  673. my %group_filter = %{$group_filters{$group_name}};
  674. foreach my $filter_index (sort keys %group_filter) {
  675. my $filter = $group_filter{$filter_index};
  676. my $filter_id=$filter->{filter_id};
  677. next if (!$filters{$filter_id});
  678. next if ($filters{$filter_id}->{dns_dst});
  679. my $src_rule='chain='.$group_name;
  680. my $dst_rule='chain='.$group_name;
  681. if ($filter->{action}) {
  682. $src_rule=$src_rule." action=accept";
  683. $dst_rule=$dst_rule." action=accept";
  684. } else {
  685. $src_rule=$src_rule." action=reject";
  686. $dst_rule=$dst_rule." action=reject";
  687. }
  688. if ($filters{$filter_id}->{proto} and ($filters{$filter_id}->{proto}!~/all/i)) {
  689. $src_rule=$src_rule." protocol=".$filters{$filter_id}->{proto};
  690. $dst_rule=$dst_rule." protocol=".$filters{$filter_id}->{proto};
  691. }
  692. if (defined $filters{$filter_id}->{ipset_id} && $filters{$filter_id}->{ipset_id}>0 && $ipset_list{$filters{$filter_id}->{ipset_id}}) {
  693. $src_rule .= " dst-address-list=".$ipset_list{$filters{$filter_id}->{ipset_id}};
  694. $dst_rule .= " src-address-list=".$ipset_list{$filters{$filter_id}->{ipset_id}};
  695. } else {
  696. my $dst = $filters{$filter_id}->{dst};
  697. if (defined $dst && $dst ne '' && $dst ne '0/0') {
  698. $src_rule=$src_rule." src-address=".trim($dst);
  699. $dst_rule=$dst_rule." dst-address=".trim($dst);
  700. }
  701. }
  702. #dstport and srcport
  703. if (!$filters{$filter_id}->{dstport}) { $filters{$filter_id}->{dstport}=0; }
  704. if (!$filters{$filter_id}->{srcport}) { $filters{$filter_id}->{srcport}=0; }
  705. if ($filters{$filter_id}->{dstport} ne '0' and $filters{$filter_id}->{srcport} ne '0') {
  706. $src_rule=$src_rule." dst-port=".trim($filters{$filter_id}->{srcport})." src-port=".trim($filters{$filter_id}->{dstport});
  707. $dst_rule=$dst_rule." src-port=".trim($filters{$filter_id}->{srcport})." dst-port=".trim($filters{$filter_id}->{dstport});
  708. }
  709. if ($filters{$filter_id}->{dstport} eq '0' and $filters{$filter_id}->{srcport} ne '0') {
  710. $src_rule=$src_rule." dst-port=".trim($filters{$filter_id}->{srcport});
  711. $dst_rule=$dst_rule." src-port=".trim($filters{$filter_id}->{srcport});
  712. }
  713. if ($filters{$filter_id}->{dstport} ne '0' and $filters{$filter_id}->{srcport} eq '0') {
  714. $src_rule=$src_rule." src-port=".trim($filters{$filter_id}->{dstport});
  715. $dst_rule=$dst_rule." dst-port=".trim($filters{$filter_id}->{dstport});
  716. }
  717. if ($src_rule ne $dst_rule) {
  718. push(@{$chain_rules{$group_name}},$src_rule);
  719. push(@{$chain_rules{$group_name}},$dst_rule);
  720. } else {
  721. push(@{$chain_rules{$group_name}},$src_rule);
  722. }
  723. }
  724. }
  725. #chain filters
  726. foreach my $group_name (sort keys %group_filters) {
  727. next if (!$group_name);
  728. my @get_filter=netdev_cmd($gate,$t,'/ip firewall filter print terse without-paging where chain='.$group_name,1);
  729. chomp(@get_filter);
  730. my @cur_filter=();
  731. my $chain_ok=1;
  732. foreach (my $f_index=0; $f_index<scalar(@get_filter); $f_index++) {
  733. my $filter_str=trim($get_filter[$f_index]);
  734. next if (!$filter_str);
  735. next if ($filter_str!~/^(\d{1,3})/);
  736. $filter_str=~s/[^[:ascii:]]//g;
  737. $filter_str=~s/^\d{1,3}\s+//;
  738. $filter_str=trim($filter_str);
  739. next if (!$filter_str);
  740. push(@cur_filter,$filter_str);
  741. }
  742. log_debug($gate_ident."Current filters:".Dumper(\@cur_filter));
  743. log_debug($gate_ident."New filters:".Dumper($chain_rules{$group_name}));
  744. #current state rules
  745. foreach (my $f_index=0; $f_index<scalar(@cur_filter); $f_index++) {
  746. my $filter_str=trim($cur_filter[$f_index]);
  747. if (!$chain_rules{$group_name}[$f_index] or $filter_str!~/$chain_rules{$group_name}[$f_index]/i) {
  748. print "Check chain $group_name error! $filter_str not found in new config. Recreate chain.\n";
  749. $chain_ok=0;
  750. last;
  751. }
  752. }
  753. #new rules
  754. if ($chain_ok and $chain_rules{$group_name} and scalar(@{$chain_rules{$group_name}})) {
  755. foreach (my $f_index=0; $f_index<scalar(@{$chain_rules{$group_name}}); $f_index++) {
  756. my $filter_str=trim($cur_filter[$f_index]);
  757. if (!$filter_str) {
  758. print "Check chain $group_name error! Not found: $chain_rules{$group_name}[$f_index]. Recreate chain.\n";
  759. $chain_ok=0;
  760. last;
  761. }
  762. $filter_str=~s/^\d//;
  763. $filter_str=trim($filter_str);
  764. if ($filter_str!~/$chain_rules{$group_name}[$f_index]/i) {
  765. print "Check chain $group_name error! Expected: $chain_rules{$group_name}[$f_index] Found: $filter_str. Recreate chain.\n";
  766. $chain_ok=0;
  767. last;
  768. }
  769. }
  770. }
  771. if (!$chain_ok) {
  772. push(@cmd_list,":foreach i in [/ip firewall filter find where chain=".$group_name." ] do={/ip firewall filter remove \$i};");
  773. foreach my $filter_str (@{$chain_rules{$group_name}}) {
  774. push(@cmd_list,'/ip firewall filter add '.$filter_str);
  775. }
  776. }
  777. }
  778. }#end access lists config
  779. SHAPER: {
  780. if ($shaper_enabled) {
  781. log_info($gate_ident . "Starting Shaper synchronization...");
  782. # --- 1. Получение списка пользователей (Auth List) ---
  783. my %users;
  784. eval {
  785. my $user_auth_sql = "SELECT ip, queue_id, id FROM user_auth WHERE user_auth.deleted = 0 AND user_auth.ou_id <> ? ORDER BY ip_int";
  786. my @authlist_ref = get_records_sql($dbh, $user_auth_sql, $default_hotspot_ou_id);
  787. foreach my $row (@authlist_ref) {
  788. next if (!$row->{ip});
  789. if ($connected_users_only) {
  790. next if (!$connected_users->match_string($row->{ip}));
  791. }
  792. next if (!$office_networks->match_string($row->{ip}));
  793. if ($row->{queue_id}) {
  794. $users{'queue_' . $row->{queue_id}}->{$row->{ip}} = 1;
  795. }
  796. }
  797. log_debug($gate_ident . "Loaded " . scalar(keys %users) . " user IP groups.");
  798. };
  799. if ($@) {
  800. log_error($gate_ident . "Failed to fetch user auth list: $@");
  801. last SHAPER;
  802. }
  803. # --- 2. Получение списка очередей из БД (Desired State) ---
  804. my %queues;
  805. my %lists;
  806. eval {
  807. my @queuelist_ref = get_records_sql($dbh, "SELECT * FROM queue_list");
  808. foreach my $row (@queuelist_ref) {
  809. next if (!$row->{id});
  810. $lists{'queue_' . $row->{id}} = 1;
  811. next if ((!$row->{download}) and !($row->{upload}));
  812. $queues{'queue_' . $row->{id}}{id} = $row->{id};
  813. $queues{'queue_' . $row->{id}}{down} = $row->{download};
  814. $queues{'queue_' . $row->{id}}{up} = $row->{upload};
  815. }
  816. log_debug($gate_ident . "Loaded " . scalar(keys %queues) . " queue definitions from DB.");
  817. };
  818. if ($@) {
  819. log_error($gate_ident . "Failed to fetch queue list from DB: $@");
  820. last SHAPER;
  821. }
  822. log_debug($gate_ident . "Queues desired status:" . Dumper(\%queues));
  823. # --- 3. Получение текущего состояния с роутера (Current State) ---
  824. my (%get_queue_root, %get_queue_type, %get_queue_tree, %get_filter_mangle);
  825. eval {
  826. # 3.1 Root Queues
  827. my @tmp = netdev_cmd($gate, $t, '/queue tree print terse without-paging where name~"(down|up)load_root"', 1);
  828. foreach my $row (@tmp) {
  829. my $clean = $parse_mikrotik_line->($row);
  830. next unless $clean;
  831. if ($clean =~ /name=(down|up)load_root_(\S*)\s+/i) {
  832. my $parent_device = $2;
  833. $get_queue_root{$parent_device}{name} = $parent_device;
  834. if ($clean =~ /\s+max-limit=(\S*)\s+/) {
  835. $get_queue_root{$parent_device}{bandwidth} = bitrate_to_kbps($1);
  836. } else {
  837. $get_queue_root{$parent_device}{bandwidth} = 0;
  838. }
  839. }
  840. }
  841. # 3.2 Queue Types (PCQ)
  842. @tmp = netdev_cmd($gate, $t, '/queue type print terse without-paging where name~"pcq_(down|up)load"', 1);
  843. foreach my $row (@tmp) {
  844. my $clean = $parse_mikrotik_line->($row);
  845. next unless $clean;
  846. if ($clean =~ /name=pcq_(down|up)load_(\d{1,3})\s+/i) {
  847. my $direct = $1;
  848. my $index = $2;
  849. $get_queue_type{$index}{$direct} = $clean;
  850. if ($clean =~ /pcq-rate=(\S*)\s+/) {
  851. my $rate = bitrate_to_kbps($1);
  852. $get_queue_type{$index}{$direct . "-rate"} = $rate;
  853. }
  854. if ($clean =~ /pcq-classifier=(\S*)\s+/) {
  855. $get_queue_type{$index}{$direct . "-classifier"} = $1;
  856. }
  857. }
  858. }
  859. # 3.3 Queue Tree (User queues)
  860. @tmp = netdev_cmd($gate, $t, '/queue tree print terse without-paging where parent~"(download|upload)_root"', 1);
  861. foreach my $row (@tmp) {
  862. my $clean = $parse_mikrotik_line->($row);
  863. next unless $clean;
  864. # Upload
  865. if ($clean =~ /name=queue_(\d{1,3})_(\S*)_out\s+/i) {
  866. my $index = $1;
  867. my $int_name = $2;
  868. $get_queue_tree{$index}{$int_name}{up} = $clean;
  869. $get_queue_tree{$index}{$int_name}{'up-parent'} = $1 if $clean =~ /parent=(\S*)\s+/;
  870. $get_queue_tree{$index}{$int_name}{'up-mark'} = $1 if $clean =~ /packet-mark=(\S*)\s+/;
  871. $get_queue_tree{$index}{$int_name}{'up-queue'} = $1 if $clean =~ /queue=(\S*)\s+/;
  872. }
  873. # Download
  874. if ($clean =~ /name=queue_(\d{1,3})_(\S*)_in\s+/i) {
  875. my $index = $1;
  876. my $int_name = $2;
  877. $get_queue_tree{$index}{$int_name}{down} = $clean;
  878. $get_queue_tree{$index}{$int_name}{'down-parent'} = $1 if $clean =~ /parent=(\S*)\s+/;
  879. $get_queue_tree{$index}{$int_name}{'down-mark'} = $1 if $clean =~ /packet-mark=(\S*)\s+/;
  880. $get_queue_tree{$index}{$int_name}{'down-queue'} = $1 if $clean =~ /queue=(\S*)\s+/;
  881. }
  882. }
  883. # 3.4 Firewall Mangle
  884. @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);
  885. foreach my $row (@tmp) {
  886. my $clean = $parse_mikrotik_line->($row);
  887. next unless $clean;
  888. if ($clean =~ /new-packet-mark=upload_(\d{1,3})_(\S*)\s+/i) {
  889. my $index = $1;
  890. my $int_name = $2;
  891. $get_filter_mangle{$index}{$int_name}{up} = $clean;
  892. $get_filter_mangle{$index}{$int_name}{'up-list'} = $1 if $clean =~ /src-address-list=(\S*)\s+/;
  893. $get_filter_mangle{$index}{$int_name}{'up-dev'} = $1 if $clean =~ /out-interface=(\S*)\s+/;
  894. $get_filter_mangle{$index}{$int_name}{'up-mark'} = $1 if $clean =~ /new-packet-mark=(\S*)\s+/;
  895. }
  896. if ($clean =~ /new-packet-mark=download_(\d{1,3})_(\S*)\s+/i) {
  897. my $index = $1;
  898. my $int_name = $2;
  899. $get_filter_mangle{$index}{$int_name}{down} = $clean;
  900. $get_filter_mangle{$index}{$int_name}{'down-list'} = $1 if $clean =~ /dst-address-list=(\S*)\s+/;
  901. $get_filter_mangle{$index}{$int_name}{'down-dev'} = $1 if $clean =~ /out-interface=(\S*)\s+/;
  902. $get_filter_mangle{$index}{$int_name}{'down-mark'} = $1 if $clean =~ /new-packet-mark=(\S*)\s+/;
  903. }
  904. }
  905. log_debug($gate_ident . "Status of the shapers on the router has been received.");
  906. };
  907. if ($@) {
  908. log_error($gate_ident . "Failed to get current router state: $@");
  909. last SHAPER;
  910. }
  911. # --- 4. Генерация команд синхронизации ---
  912. my @cmd_list;
  913. eval {
  914. # 4.1 Анализ и коррекция Root классов
  915. foreach my $l3_int (keys %l3_interfaces) {
  916. my $int_type = ($l3_interfaces{$l3_int}->{type}) ? 'upload' : 'download';
  917. my $root_name = "${int_type}_root_${l3_int}";
  918. my $desired_bw = $l3_interfaces{$l3_int}->{bandwidth};
  919. # Очистка мусорных рут-очередей на этом интерфейсе
  920. push(@cmd_list, "/queue tree remove [ find name!~\"${int_type}_root_${l3_int}\" and parent=${l3_int} ]");
  921. if (!exists $get_queue_root{$l3_int}) {
  922. log_info($gate_ident . "[CHANGE] Root queue '$root_name' missing. Creating with limit ${desired_bw}kbps.");
  923. push(@cmd_list, "/queue tree add max-limit=" . kbps_to_bitrate($desired_bw) . " name=$root_name parent=$l3_int queue=pcq-${int_type}-default");
  924. next;
  925. }
  926. my $current_bw = $get_queue_root{$l3_int}{bandwidth} || 0;
  927. if ($current_bw != $desired_bw) {
  928. log_info($gate_ident . "[CHANGE] Root queue '$root_name' bandwidth mismatch. Current: ${current_bw}, Desired: ${desired_bw}. Updating.");
  929. push(@cmd_list, "/queue tree set max-limit=" . kbps_to_bitrate($desired_bw) . " [ find name=$root_name ]");
  930. }
  931. }
  932. # 4.2 Генерация конфигурации очередей (Types, Tree, Mangle)
  933. foreach my $queue_name (keys %queues) {
  934. my $q_id = $queues{$queue_name}{id};
  935. my $q_up = $queues{$queue_name}{up};
  936. my $q_down = $queues{$queue_name}{down};
  937. # --- Queue Types ---
  938. my $type_up_str = "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";
  939. my $type_down_str = "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";
  940. # Check UP Type
  941. my $need_update_up = 0;
  942. if (!$get_queue_type{$q_id}{up}) {
  943. $need_update_up = 1;
  944. log_info($gate_ident . "[CHANGE] Queue Type 'pcq_upload_${q_id}' missing.");
  945. } else {
  946. my $curr_rate = $get_queue_type{$q_id}{'up-rate'} || 0;
  947. my $curr_class = $get_queue_type{$q_id}{'up-classifier'} || '';
  948. if (abs($q_up - $curr_rate) > 50) {
  949. $need_update_up = 1;
  950. log_info($gate_ident . "[CHANGE] Queue Type 'pcq_upload_${q_id}' rate mismatch: ${curr_rate} vs ${q_up}.");
  951. } elsif ($curr_class !~ /src-address/i) {
  952. $need_update_up = 1;
  953. log_info($gate_ident . "[CHANGE] Queue Type 'pcq_upload_${q_id}' classifier mismatch.");
  954. }
  955. }
  956. if ($need_update_up) {
  957. # Формируем понятное сообщение о причине изменения
  958. my $action_msg = !$get_queue_type{$q_id}{up}
  959. ? "Creating missing queue type"
  960. : "Updating queue type parameters (rate/classifier mismatch)";
  961. log_info($gate_ident . "[CHANGE] Queue Type 'pcq_upload_${q_id}': $action_msg.");
  962. log_debug($gate_ident . " -> New config: $type_up_str");
  963. # Команда удаления старых экземпляров (если есть мусорные дубликаты)
  964. push(@cmd_list, ":foreach i in [/queue type find where name=\"pcq_upload_${q_id}\"] do={/queue type remove \$i};");
  965. # Команда добавления новой конфигурации
  966. push(@cmd_list, "/queue type add $type_up_str");
  967. }
  968. # Check DOWN Type
  969. my $need_update_down = 0;
  970. if (!$get_queue_type{$q_id}{down}) {
  971. $need_update_down = 1;
  972. log_info($gate_ident . "[CHANGE] Queue Type 'pcq_download_${q_id}' missing.");
  973. } else {
  974. my $curr_rate = $get_queue_type{$q_id}{'down-rate'} || 0;
  975. my $curr_class = $get_queue_type{$q_id}{'down-classifier'} || '';
  976. if (abs($q_down - $curr_rate) > 50) {
  977. $need_update_down = 1;
  978. log_info($gate_ident . "[CHANGE] Queue Type 'pcq_download_${q_id}' rate mismatch: ${curr_rate} vs ${q_down}.");
  979. } elsif ($curr_class !~ /dst-address/i) {
  980. $need_update_down = 1;
  981. log_info($gate_ident . "[CHANGE] Queue Type 'pcq_download_${q_id}' classifier mismatch.");
  982. }
  983. }
  984. if ($need_update_down) {
  985. # Определяем причину изменения для лога
  986. my $action_msg = !$get_queue_type{$q_id}{down}
  987. ? "Creating missing queue type"
  988. : "Updating queue type parameters (rate/classifier mismatch)";
  989. log_info($gate_ident . "[CHANGE] Queue Type 'pcq_download_${q_id}': $action_msg.");
  990. log_debug($gate_ident . " -> New config: $type_down_str");
  991. # Удаляем старые/некорректные записи
  992. push(@cmd_list, ":foreach i in [/queue type find where name=\"pcq_download_${q_id}\"] do={/queue type remove \$i};");
  993. # Добавляем новую конфигурацию
  994. push(@cmd_list, "/queue type add $type_down_str");
  995. }
  996. # --- Upload Queue Tree & Mangle (per WAN interface) ---
  997. foreach my $int (@wan_int) {
  998. next unless $int;
  999. my $q_name = "queue_${q_id}_${int}_out";
  1000. my $p_mark = "upload_${q_id}_${int}";
  1001. my $p_list = "queue_${q_id}";
  1002. my $tree_up_str = "name=${q_name} parent=upload_root_${int} packet-mark=${p_mark} 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";
  1003. my $mangle_up_str = "chain=forward action=mark-packet new-packet-mark=${p_mark} passthrough=yes src-address-list=${p_list} out-interface=${int} log=no log-prefix=\"\"";
  1004. # Check Tree UP
  1005. my $fix_tree_up = 0;
  1006. if (!$get_queue_tree{$q_id}{$int}{up}) {
  1007. $fix_tree_up = 1;
  1008. log_info($gate_ident . "[CHANGE] Queue Tree '$q_name' missing.");
  1009. } else {
  1010. $fix_tree_up = 1 if ($get_queue_tree{$q_id}{$int}{'up-parent'} ne "upload_root_${int}");
  1011. $fix_tree_up = 1 if ($get_queue_tree{$q_id}{$int}{'up-mark'} ne $p_mark);
  1012. $fix_tree_up = 1 if ($get_queue_tree{$q_id}{$int}{'up-queue'} ne "pcq_upload_${q_id}");
  1013. log_info($gate_ident . "[CHANGE] Queue Tree '$q_name' parameters mismatch.") if $fix_tree_up;
  1014. }
  1015. if ($fix_tree_up) {
  1016. # Определяем причину изменения для лога
  1017. my $action_msg = !$get_queue_tree{$q_id}{$int}{up}
  1018. ? "Creating missing queue tree rule"
  1019. : "Updating queue tree parameters (parent/mark/queue mismatch)";
  1020. log_info($gate_ident . "[CHANGE] Queue Tree '${q_name}': $action_msg.");
  1021. log_debug($gate_ident . " -> New config: $tree_up_str");
  1022. # Удаляем старые/некорректные правила
  1023. push(@cmd_list, ":foreach i in [/queue tree find where name=\"${q_name}\"] do={/queue tree remove \$i};");
  1024. # Добавляем новое правило
  1025. push(@cmd_list, "/queue tree add $tree_up_str");
  1026. }
  1027. # Check Mangle UP
  1028. my $fix_mangle_up = 0;
  1029. if (!$get_filter_mangle{$q_id}{$int}{up}) {
  1030. $fix_mangle_up = 1;
  1031. log_info($gate_ident . "[CHANGE] Mangle rule for '$p_mark' missing.");
  1032. } else {
  1033. $fix_mangle_up = 1 if ($get_filter_mangle{$q_id}{$int}{'up-mark'} ne $p_mark);
  1034. $fix_mangle_up = 1 if ($get_filter_mangle{$q_id}{$int}{'up-list'} ne $p_list);
  1035. $fix_mangle_up = 1 if ($get_filter_mangle{$q_id}{$int}{'up-dev'} ne $int);
  1036. log_info($gate_ident . "[CHANGE] Mangle rule for '$p_mark' parameters mismatch.") if $fix_mangle_up;
  1037. }
  1038. if ($fix_mangle_up) {
  1039. # Определяем причину изменения для лога
  1040. my $action_msg = !$get_filter_mangle{$q_id}{$int}{up}
  1041. ? "Creating missing mangle rule"
  1042. : "Updating mangle rule parameters (mark/list/interface mismatch)";
  1043. log_info($gate_ident . "[CHANGE] Mangle Rule '${p_mark}': $action_msg.");
  1044. log_debug($gate_ident . " -> New config: $mangle_up_str");
  1045. # Удаляем старые/некорректные правила
  1046. # Примечание: используем точное совпадение new-packet-mark=, так как имя метки уникально
  1047. push(@cmd_list, ":foreach i in [/ip firewall mangle find where action=mark-packet and new-packet-mark=\"${p_mark}\"] do={/ip firewall mangle remove \$i};");
  1048. # Добавляем новое правило
  1049. push(@cmd_list, "/ip firewall mangle add $mangle_up_str");
  1050. }
  1051. }
  1052. # --- Download Queue Tree & Mangle (per LAN interface) ---
  1053. foreach my $int (@lan_int) {
  1054. next unless $int;
  1055. my $q_name = "queue_${q_id}_${int}_in";
  1056. my $p_mark = "download_${q_id}_${int}";
  1057. my $p_list = "queue_${q_id}";
  1058. my $tree_down_str = "name=${q_name} parent=download_root_${int} packet-mark=${p_mark} 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";
  1059. my $mangle_down_str = "chain=forward action=mark-packet new-packet-mark=${p_mark} passthrough=yes dst-address-list=${p_list} out-interface=${int} in-interface-list=WAN log=no log-prefix=\"\"";
  1060. # Check Tree DOWN
  1061. my $fix_tree_down = 0;
  1062. if (!$get_queue_tree{$q_id}{$int}{down}) {
  1063. $fix_tree_down = 1;
  1064. log_info($gate_ident . "[CHANGE] Queue Tree '$q_name' missing.");
  1065. } else {
  1066. $fix_tree_down = 1 if ($get_queue_tree{$q_id}{$int}{'down-parent'} ne "download_root_${int}");
  1067. $fix_tree_down = 1 if ($get_queue_tree{$q_id}{$int}{'down-mark'} ne $p_mark);
  1068. $fix_tree_down = 1 if ($get_queue_tree{$q_id}{$int}{'down-queue'} ne "pcq_download_${q_id}");
  1069. log_info($gate_ident . "[CHANGE] Queue Tree '$q_name' parameters mismatch.") if $fix_tree_down;
  1070. }
  1071. if ($fix_tree_down) {
  1072. push(@cmd_list, ":foreach i in [/queue tree find where name=\"${q_name}\"] do={/queue tree remove \$i};");
  1073. push(@cmd_list, "/queue tree add $tree_down_str");
  1074. }
  1075. # Check Mangle DOWN
  1076. my $fix_mangle_down = 0;
  1077. if (!$get_filter_mangle{$q_id}{$int}{down}) {
  1078. $fix_mangle_down = 1;
  1079. log_info($gate_ident . "[CHANGE] Mangle rule for '$p_mark' missing.");
  1080. } else {
  1081. $fix_mangle_down = 1 if ($get_filter_mangle{$q_id}{$int}{'down-mark'} ne $p_mark);
  1082. $fix_mangle_down = 1 if ($get_filter_mangle{$q_id}{$int}{'down-list'} ne $p_list);
  1083. $fix_mangle_down = 1 if ($get_filter_mangle{$q_id}{$int}{'down-dev'} ne $int);
  1084. log_info($gate_ident . "[CHANGE] Mangle rule for '$p_mark' parameters mismatch.") if $fix_mangle_down;
  1085. }
  1086. if ($fix_mangle_down) {
  1087. # Определяем причину изменения для лога
  1088. my $action_msg = !$get_filter_mangle{$q_id}{$int}{down}
  1089. ? "Creating missing mangle rule"
  1090. : "Updating mangle rule parameters (mark/list/interface mismatch)";
  1091. log_info($gate_ident . "[CHANGE] Mangle Rule '${p_mark}': $action_msg.");
  1092. log_debug($gate_ident . " -> New config: $mangle_down_str");
  1093. # Удаляем старые/некорректные правила
  1094. # Используем точное совпадение new-packet-mark, так как имя метки уникально
  1095. push(@cmd_list, ":foreach i in [/ip firewall mangle find where action=mark-packet and new-packet-mark=\"${p_mark}\"] do={/ip firewall mangle remove \$i};");
  1096. # Добавляем новое правило
  1097. push(@cmd_list, "/ip firewall mangle add $mangle_down_str");
  1098. }
  1099. }
  1100. }
  1101. };
  1102. if ($@) {
  1103. log_error($gate_ident . "Error during command generation logic: $@");
  1104. }
  1105. } # end shaper_enabled
  1106. }
  1107. # Analyze actual ACL
  1108. my %cur_users;
  1109. foreach my $group_name (keys %lists) {
  1110. my @address_lists=netdev_cmd($gate,$t,'/ip firewall address-list print terse without-paging where list='.$group_name,1);
  1111. log_debug($gate_ident."Get address lists:".Dumper(\@address_lists));
  1112. foreach my $row (@address_lists) {
  1113. $row=trim($row);
  1114. next if (!$row);
  1115. my @address=split(' ',$row);
  1116. foreach my $row (@address) {
  1117. if ($row=~/address\=(.*)/i) { $cur_users{$group_name}{$1}=1; }
  1118. }
  1119. }
  1120. }
  1121. #new-ips
  1122. foreach my $group_name (keys %users) {
  1123. foreach my $user_ip (keys %{$users{$group_name}}) {
  1124. if (!exists($cur_users{$group_name}{$user_ip})) {
  1125. db_log_verbose($dbh,$gate_ident."Add user with ip: $user_ip to access-list $group_name");
  1126. push(@cmd_list,"/ip firewall address-list add address=".$user_ip." list=".$group_name);
  1127. }
  1128. }
  1129. }
  1130. #old-ips
  1131. foreach my $group_name (keys %cur_users) {
  1132. foreach my $user_ip (keys %{$cur_users{$group_name}}) {
  1133. if (!exists($users{$group_name}{$user_ip})) {
  1134. db_log_verbose($dbh,$gate_ident."Remove user with ip: $user_ip from access-list $group_name");
  1135. 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};");
  1136. }
  1137. }
  1138. }
  1139. timestamp;
  1140. if (scalar(@cmd_list)) {
  1141. log_debug($gate_ident."Apply:");
  1142. if ($debug) { foreach my $cmd (@cmd_list) { log_debug($gate_ident."$cmd"); } }
  1143. eval {
  1144. netdev_cmd($gate,$t,\@cmd_list,1);
  1145. };
  1146. if ($@) {
  1147. $all_ok = 0;
  1148. log_debug($gate_ident."Error programming gateway! Err: ".$@);
  1149. }
  1150. }
  1151. db_log_verbose($dbh,$gate_ident."Sync user state stopped.");
  1152. $dbh->disconnect();
  1153. $pm->finish;
  1154. }
  1155. $pm->wait_all_children;
  1156. #clear changed
  1157. if ($all_ok) {
  1158. foreach my $row (@changes_found) {
  1159. do_sql($dbh,"UPDATE user_auth SET changed=0 WHERE id=?",$row->{id});
  1160. }
  1161. }
  1162. if (IsMyPID($SPID)) { Remove_PID($SPID); };
  1163. do_exit 0;