common.pm 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934
  1. package eyelib::common;
  2. #
  3. # Copyright (C) Roman Dmitriev, rnd@rajven.ru
  4. #
  5. use utf8;
  6. use open ":encoding(utf8)";
  7. use strict;
  8. use English;
  9. use FindBin '$Bin';
  10. use lib "/opt/Eye/scripts";
  11. use base 'Exporter';
  12. use vars qw(@EXPORT @ISA);
  13. use eyelib::config;
  14. use eyelib::main;
  15. use Net::Patricia;
  16. use eyelib::net_utils;
  17. use Data::Dumper;
  18. use eyelib::database;
  19. use DateTime;
  20. use DateTime::Format::Strptime;
  21. use POSIX qw(mktime ctime strftime);
  22. use File::Temp qw(tempfile);
  23. use DBI;
  24. our @ISA = qw(Exporter);
  25. our @EXPORT = qw(
  26. apply_device_lock
  27. create_dns_cname
  28. create_dns_hostname
  29. create_dns_ptr
  30. delete_device
  31. delete_dns_cname
  32. delete_dns_hostname
  33. delete_dns_ptr
  34. delete_user
  35. delete_user_auth
  36. find_mac_in_subnet
  37. get_default_ou
  38. get_device_by_ip
  39. get_dns_name
  40. get_dynamic_ou
  41. get_ip_subnet
  42. get_new_user_id
  43. GetNowTime
  44. get_subnets_ref
  45. GetTimeStrByUnixTime
  46. GetUnixTimeByStr
  47. is_ad_computer
  48. is_default_ou
  49. is_dynamic_ou
  50. new_auth
  51. new_user
  52. process_dhcp_request
  53. recalc_quotes
  54. record_to_txt
  55. resurrection_auth
  56. set_changed
  57. set_lock_discovery
  58. unbind_ports
  59. unblock_user
  60. unset_lock_discovery
  61. update_dns_record
  62. update_dns_record_by_dhcp
  63. get_creation_method
  64. );
  65. BEGIN
  66. {
  67. #---------------------------------------------------------------------------------------------------------------
  68. sub unbind_ports {
  69. my ($db, $device_id) = @_;
  70. return unless $db && defined $device_id && $device_id =~ /^\d+$/;
  71. # Получаем все порты устройства
  72. my @target = get_records_sql($db,
  73. "SELECT target_port_id, id FROM device_ports WHERE device_id = ?",
  74. $device_id
  75. );
  76. foreach my $row (@target) {
  77. # Обнуляем ссылки НА этот порт (кто ссылается на него)
  78. do_sql($db, "UPDATE device_ports SET target_port_id = 0 WHERE target_port_id = ?", $row->{id});
  79. # Обнуляем ссылку С этого порта (куда он ссылался)
  80. do_sql($db, "UPDATE device_ports SET target_port_id = 0 WHERE id = ?", $row->{id});
  81. }
  82. }
  83. #---------------------------------------------------------------------------------------------------------------
  84. sub get_dns_name {
  85. my ($db, $id) = @_;
  86. return unless $db && defined $id;
  87. return unless $id =~ /^\d+$/ && $id > 0;
  88. my $auth_record = get_record_sql(
  89. $db,
  90. "SELECT dns_name FROM user_auth WHERE deleted = 0 AND id = ?",
  91. $id
  92. );
  93. return $auth_record && $auth_record->{dns_name}
  94. ? $auth_record->{dns_name}
  95. : undef;
  96. }
  97. #---------------------------------------------------------------------------------------------------------------
  98. sub record_to_txt {
  99. my ($db, $table, $id) = @_;
  100. return unless $db && defined $table && defined $id;
  101. # Валидация имени таблицы: только буквы, цифры, подчёркивания
  102. return unless $table =~ /^[a-zA-Z_][a-zA-Z0-9_]*$/;
  103. # Валидация ID: должно быть положительное целое число
  104. return unless $id =~ /^\d+$/ && $id > 0;
  105. my $record = get_record_sql(
  106. $db,
  107. "SELECT * FROM $table WHERE id = ?",
  108. $id
  109. );
  110. return hash_to_text($record);
  111. }
  112. #---------------------------------------------------------------------------------------------------------------
  113. sub delete_user_auth {
  114. my ($db, $id) = @_;
  115. return 0 unless $db && defined $id;
  116. return 0 unless $id =~ /^\d+$/ && $id > 0;
  117. my $record = get_record_sql($db, "SELECT * FROM user_auth WHERE id = ?", $id);
  118. return 0 unless $record;
  119. my @aliases = get_records_sql($db, "SELECT * FROM user_auth_alias WHERE auth_id = ?", $id);
  120. foreach my $alias (@aliases) {
  121. my $alias_id = $alias->{id};
  122. next unless defined $alias_id && $alias_id =~ /^\d+$/;
  123. delete_record($db, 'user_auth_alias', 'id = ?', $alias_id);
  124. }
  125. # --- Удаляем соединения ---
  126. do_sql($db, "DELETE FROM connections WHERE auth_id = ?", $id);
  127. # --- Удаляем основную запись ---
  128. my $changes = delete_record($db, "user_auth", "id = ?", $id);
  129. return $changes;
  130. }
  131. #---------------------------------------------------------------------------------------------------------------
  132. sub unblock_user {
  133. my ($db, $user_id) = @_;
  134. return 0 unless $db && defined $user_id;
  135. return 0 unless $user_id =~ /^\d+$/ && $user_id > 0;
  136. my $user_record = get_record_sql($db, "SELECT * FROM user_list WHERE id = ?", $user_id);
  137. return 0 unless $user_record;
  138. my $user_ident = 'id:' . ($user_record->{id} // '') . ' ' . ($user_record->{login} // '');
  139. if ($user_record->{description}) {
  140. $user_ident .= '[' . $user_record->{description} . ']';
  141. }
  142. my $msg = "Amnistuyemo blocked by traffic user $user_ident\nInternet access for the user's IP address has been restored:\n";
  143. my $send_alert = 0;
  144. my $any_updated = 0;
  145. my @user_auth = get_records_sql($db, "SELECT * FROM user_auth WHERE deleted = 0 AND user_id = ?", $user_id);
  146. foreach my $record (@user_auth) {
  147. next unless $record->{id} && $record->{id} =~ /^\d+$/;
  148. $send_alert ||= isNotifyUpdate(get_notify_subnet($db, $record->{ip}));
  149. my $auth_ident = $record->{ip} // '';
  150. if ($record->{dns_name}) {
  151. $auth_ident .= '[' . $record->{dns_name} . ']';
  152. }
  153. if ($record->{description}) {
  154. $auth_ident .= ' :: ' . $record->{description};
  155. }
  156. my $new = {
  157. blocked => 0,
  158. changed => 1,
  159. };
  160. if (update_record($db, 'user_auth', $new, 'id = ?', $record->{id})) {
  161. $msg .= "\n" . $auth_ident;
  162. $any_updated = 1;
  163. }
  164. }
  165. my $user_update = { blocked => 0 };
  166. my $ret_id = update_record($db, 'user_list', $user_update, 'id = ?', $user_id);
  167. if ($ret_id) {
  168. db_log_info($db, $msg);
  169. sendEmail("WARN! " . get_first_line($msg), $msg, 1) if $send_alert;
  170. }
  171. return $ret_id;
  172. }
  173. #---------------------------------------------------------------------------------------------------------------
  174. sub delete_user {
  175. my ($db, $id) = @_;
  176. return 0 unless $db && defined $id;
  177. return 0 unless $id =~ /^\d+$/ && $id > 0;
  178. my $changes = delete_record($db, "user_list", "permanent = 0 AND id = ?", $id);
  179. return 0 unless $changes;
  180. my @user_auth_records = get_records_sql($db, "SELECT id FROM user_auth WHERE user_id = ?", $id);
  181. foreach my $row (@user_auth_records) {
  182. next unless defined $row->{id} && $row->{id} =~ /^\d+$/;
  183. delete_user_auth($db, $row->{id});
  184. }
  185. my $device = get_record_sql($db, "SELECT id FROM devices WHERE user_id = ?", $id);
  186. if ($device && defined $device->{id} && $device->{id} =~ /^\d+$/) {
  187. delete_device($db, $device->{id});
  188. }
  189. do_sql($db, "DELETE FROM auth_rules WHERE user_id = ?", $id);
  190. return $changes;
  191. }
  192. #---------------------------------------------------------------------------------------------------------------
  193. sub delete_device {
  194. my ($db, $id) = @_;
  195. return 0 unless $db && defined $id;
  196. return 0 unless $id =~ /^\d+$/ && $id > 0;
  197. my $changes = delete_record($db, "devices", "id = ?", $id);
  198. return 0 unless $changes;
  199. # Отвязываем порты
  200. unbind_ports($db, $id);
  201. do_sql($db, "DELETE FROM connections WHERE device_id = ?", $id);
  202. do_sql($db, "DELETE FROM device_l3_interfaces WHERE device_id = ?", $id);
  203. do_sql($db, "DELETE FROM device_ports WHERE device_id = ?", $id);
  204. do_sql($db, "DELETE FROM device_filter_instances WHERE device_id = ?", $id);
  205. do_sql($db, "DELETE FROM gateway_subnets WHERE device_id = ?", $id);
  206. return $changes;
  207. }
  208. #---------------------------------------------------------------------------------------------------------------
  209. sub get_new_user_id {
  210. my ($db, $ip, $mac, $hostname) = @_;
  211. return unless $db;
  212. my $result = {
  213. ip => $ip,
  214. mac => defined $mac ? mac_splitted(mac_simplify($mac)) : undef,
  215. dhcp_hostname => $hostname,
  216. ou_id => undef,
  217. user_id => undef,
  218. };
  219. # --- Hotspot ---
  220. my @hotspot_rules = get_records_sql($db,
  221. "SELECT * FROM subnets WHERE hotspot = 1 AND LENGTH(subnet) > 0"
  222. );
  223. if (@hotspot_rules) {
  224. my $hotspot_pat = Net::Patricia->new;
  225. foreach my $row (@hotspot_rules) {
  226. next unless defined $row->{subnet};
  227. eval { $hotspot_pat->add_string($row->{subnet}, $default_hotspot_ou_id); 1 } or next;
  228. }
  229. if (defined $ip) {
  230. my $ou_id = $hotspot_pat->match_string($ip);
  231. if ($ou_id) { $result->{ou_id} = $ou_id; return $result; }
  232. }
  233. }
  234. # --- Поиск user_id по IP/MAC/hostname ---
  235. if (defined $ip && $ip) {
  236. my @rules = get_records_sql($db,
  237. "SELECT rule, user_id FROM auth_rules WHERE rule_type = 1 AND LENGTH(rule) > 0 AND user_id IS NOT NULL"
  238. );
  239. my $pat = Net::Patricia->new;
  240. foreach my $r (@rules) {
  241. next unless defined $r->{rule};
  242. eval { $pat->add_string($r->{rule}, $r->{user_id}); 1 } or next;
  243. }
  244. if (my $user_id = $pat->match_string($ip)) {
  245. $result->{user_id} = $user_id;
  246. return $result;
  247. }
  248. }
  249. if (defined $mac && $mac) {
  250. my @rules = get_records_sql($db,
  251. "SELECT rule, user_id FROM auth_rules WHERE rule_type = 2 AND LENGTH(rule) > 0 AND user_id IS NOT NULL"
  252. );
  253. foreach my $r (@rules) {
  254. next unless defined $r->{rule};
  255. my $rule_clean = mac_simplify($r->{rule});
  256. # Защита от битых регулярок
  257. eval {
  258. if ($mac =~ /\Q$rule_clean\E/i) { # \Q...\E — экранируем спецсимволы!
  259. $result->{user_id} = $r->{user_id};
  260. return $result;
  261. }
  262. 1;
  263. } or do {
  264. log_debug("Invalid MAC rule: '$r->{rule}'");
  265. next;
  266. };
  267. }
  268. }
  269. if (defined $hostname && $hostname) {
  270. my @rules = get_records_sql($db,
  271. "SELECT rule, user_id FROM auth_rules WHERE rule_type = 3 AND LENGTH(rule) > 0 AND user_id IS NOT NULL"
  272. );
  273. foreach my $r (@rules) {
  274. next unless defined $r->{rule};
  275. eval {
  276. if ($hostname =~ /$r->{rule}/i) {
  277. $result->{user_id} = $r->{user_id};
  278. return $result;
  279. }
  280. 1;
  281. } or do {
  282. log_debug("Invalid hostname rule: '$r->{rule}'");
  283. next;
  284. };
  285. }
  286. }
  287. # --- Поиск ou_id по IP/MAC/hostname ---
  288. if (defined $ip && $ip) {
  289. my @rules = get_records_sql($db,
  290. "SELECT rule, ou_id FROM auth_rules WHERE rule_type = 1 AND LENGTH(rule) > 0 AND ou_id IS NOT NULL"
  291. );
  292. my $pat = Net::Patricia->new;
  293. foreach my $r (@rules) {
  294. next unless defined $r->{rule};
  295. eval { $pat->add_string($r->{rule}, $r->{ou_id}); 1 } or next;
  296. }
  297. if (my $ou_id = $pat->match_string($ip)) {
  298. $result->{ou_id} = $ou_id;
  299. return $result;
  300. }
  301. }
  302. if (defined $mac && $mac) {
  303. my @rules = get_records_sql($db,
  304. "SELECT rule, ou_id FROM auth_rules WHERE rule_type = 2 AND LENGTH(rule) > 0 AND ou_id IS NOT NULL"
  305. );
  306. foreach my $r (@rules) {
  307. next unless defined $r->{rule};
  308. my $rule_clean = mac_simplify($r->{rule});
  309. eval {
  310. if ($mac =~ /\Q$rule_clean\E/i) {
  311. $result->{ou_id} = $r->{ou_id};
  312. return $result;
  313. }
  314. 1;
  315. } or do {
  316. log_debug("Invalid MAC rule: '$r->{rule}'");
  317. next;
  318. };
  319. }
  320. }
  321. if (defined $hostname && $hostname) {
  322. my @rules = get_records_sql($db,
  323. "SELECT rule, ou_id FROM auth_rules WHERE rule_type = 3 AND LENGTH(rule) > 0 AND ou_id IS NOT NULL"
  324. );
  325. foreach my $r (@rules) {
  326. next unless defined $r->{rule};
  327. eval {
  328. if ($hostname =~ /$r->{rule}/i) {
  329. $result->{ou_id} = $r->{ou_id};
  330. return $result;
  331. }
  332. 1;
  333. } or do {
  334. log_debug("Invalid hostname rule: '$r->{rule}'");
  335. next;
  336. };
  337. }
  338. }
  339. $result->{ou_id} //= $default_user_ou_id;
  340. return $result;
  341. }
  342. #---------------------------------------------------------------------------------------------------------------
  343. sub set_changed {
  344. my ($db, $id) = @_;
  345. return unless $db && defined $id;
  346. return unless $id =~ /^\d+$/;
  347. my $update_record = { changed => 1 };
  348. update_record($db, 'user_auth', $update_record, 'id = ?', $id);
  349. }
  350. #---------------------------------------------------------------------------------------------------------------
  351. sub update_dns_record {
  352. my ($hdb, $auth_id) = @_;
  353. # === 1. Базовые проверки ===
  354. return unless $config_ref{enable_dns_updates};
  355. return unless defined $auth_id;
  356. # Валидация: auth_id должен быть положительным целым числом
  357. return unless $auth_id =~ /^\d+$/ && $auth_id > 0;
  358. # Переподключение к БД при необходимости
  359. if (!$hdb || !$hdb->ping) {
  360. $hdb = init_db();
  361. }
  362. return unless $hdb;
  363. # === 2. Получение настроек DNS ===
  364. my $ad_zone = get_option($hdb, 33); # DNS-зона (например, 'example.com')
  365. my $ad_dns = get_option($hdb, 3); # DNS-сервер
  366. my $enable_ad_dns_update = ($ad_zone && $ad_dns && $config_ref{enable_dns_updates});
  367. log_debug("Auth id: $auth_id");
  368. log_debug("enable_ad_dns_update: " . ($enable_ad_dns_update ? '1' : '0'));
  369. log_debug("DNS update flags - zone: $ad_zone, dns: $ad_dns, enable_ad_dns_update: " . ($enable_ad_dns_update ? '1' : '0'));
  370. # === 3. Получение задач из очереди DNS ===
  371. # Используем != '' вместо > '' для совместимости
  372. my @dns_queue = get_records_sql(
  373. $hdb,
  374. "SELECT * FROM dns_queue
  375. WHERE auth_id = ?
  376. AND value != ''
  377. AND value NOT LIKE '%.'
  378. ORDER BY id ASC",
  379. $auth_id
  380. );
  381. return unless @dns_queue;
  382. # === 4. Обработка каждой DNS-команды ===
  383. foreach my $dns_cmd (@dns_queue) {
  384. my $fqdn = '';
  385. my $fqdn_ip = '';
  386. my $fqdn_parent = '';
  387. my $static_exists = 0;
  388. my $static_ref = '';
  389. my $static_ok = 0;
  390. eval {
  391. # === Обработка CNAME записей ===
  392. if (lc($dns_cmd->{name_type}) eq 'cname') {
  393. # Пропускаем домены с завершающей точкой (уже FQDN)
  394. if ($dns_cmd->{name} =~ /\.$/ || $dns_cmd->{value} =~ /\.$/) {
  395. next;
  396. }
  397. $fqdn = lc($dns_cmd->{name});
  398. $fqdn =~ s/\.$ad_zone$//i; # Убираем зону из имени
  399. $fqdn .= ".$ad_zone"; # Добавляем зону для FQDN
  400. if ($dns_cmd->{value}) {
  401. $fqdn_parent = lc($dns_cmd->{value});
  402. $fqdn_parent =~ s/\.$ad_zone$//i;
  403. $fqdn_parent .= ".$ad_zone";
  404. }
  405. # Удаление CNAME
  406. if ($dns_cmd->{operation_type} eq 'del') {
  407. delete_dns_cname($fqdn_parent, $fqdn, $ad_zone, $ad_dns, $hdb);
  408. }
  409. # Создание CNAME
  410. elsif ($dns_cmd->{operation_type} eq 'add') {
  411. create_dns_cname($fqdn_parent, $fqdn, $ad_zone, $ad_dns, $hdb);
  412. }
  413. }
  414. # === Обработка A-записей ===
  415. elsif (lc($dns_cmd->{name_type}) eq 'a') {
  416. # Пропускаем уже FQDN-имена
  417. if ($dns_cmd->{name} =~ /\.$/ || $dns_cmd->{value} =~ /\.$/) {
  418. next;
  419. }
  420. $fqdn = lc($dns_cmd->{name});
  421. $fqdn =~ s/\.$ad_zone$//i;
  422. $fqdn .= ".$ad_zone";
  423. # Проверка IP-адреса
  424. if (!$dns_cmd->{value}) {
  425. next;
  426. }
  427. $fqdn_ip = lc($dns_cmd->{value});
  428. # Проверка: разрешено ли обновление DNS для этой сети?
  429. my $maybe_update_dns = ($enable_ad_dns_update && $office_networks->match_string($fqdn_ip));
  430. if (!$maybe_update_dns) {
  431. db_log_info($hdb, "FOUND Auth_id: $auth_id. DNS update disabled.");
  432. next;
  433. }
  434. # Получение алиасов для текущего auth_id
  435. my @aliases = get_records_sql(
  436. $hdb,
  437. "SELECT alias, description FROM user_auth_alias WHERE auth_id = ?",
  438. $auth_id
  439. );
  440. # Удаление A/PTR записей
  441. if ($dns_cmd->{operation_type} eq 'del') {
  442. # Удаляем алиасы (CNAME и A-записи)
  443. for my $alias (@aliases) {
  444. if ($alias->{alias} && $alias->{alias} ne '') {
  445. delete_dns_cname($fqdn, $alias->{alias}, $ad_zone, $ad_dns, $hdb);
  446. delete_dns_hostname($fqdn, $alias->{alias}, $ad_zone, $ad_dns, $hdb);
  447. }
  448. }
  449. # Удаляем основные записи
  450. delete_dns_hostname($fqdn, $fqdn_ip, $ad_zone, $ad_dns, $hdb);
  451. delete_dns_ptr($fqdn, $fqdn_ip, $ad_zone, $ad_dns, $hdb);
  452. }
  453. # Создание A/PTR записей
  454. elsif ($dns_cmd->{operation_type} eq 'add') {
  455. # Проверяем существующие DNS-записи
  456. my @dns_record = ResolveNames($fqdn, $dns_server);
  457. $static_exists = (@dns_record > 0);
  458. if ($static_exists) {
  459. $static_ref = join(' ', @dns_record);
  460. # Проверяем, совпадает ли IP
  461. for my $dns_a (@dns_record) {
  462. if ($dns_a eq $fqdn_ip) {
  463. $static_ok = 1;
  464. last;
  465. }
  466. }
  467. db_log_debug($hdb, "Dns record for static record $fqdn: $static_ref");
  468. }
  469. # Пропускаем, если запись уже корректна
  470. if ($static_ok) {
  471. db_log_debug($hdb, "Static record for $fqdn [$fqdn_ip] correct.");
  472. next;
  473. }
  474. # Создаём основные записи
  475. create_dns_hostname($fqdn, $fqdn_ip, $ad_zone, $ad_dns, $hdb);
  476. create_dns_ptr($fqdn, $fqdn_ip, $ad_zone, $ad_dns, $hdb);
  477. # Создаём алиасы
  478. for my $alias (@aliases) {
  479. if ($alias->{alias} && $alias->{alias} ne '') {
  480. create_dns_cname($fqdn, $alias->{alias}, $ad_zone, $ad_dns, $hdb);
  481. }
  482. }
  483. }
  484. }
  485. # === Обработка PTR записей ===
  486. elsif (lc($dns_cmd->{name_type}) eq 'ptr') {
  487. $fqdn = lc($dns_cmd->{name});
  488. $fqdn =~ s/\.$ad_zone$//i;
  489. $fqdn .= ".$ad_zone";
  490. if (!$dns_cmd->{value}) {
  491. next;
  492. }
  493. $fqdn_ip = lc($dns_cmd->{value});
  494. # Пропускаем FQDN
  495. if ($fqdn =~ /\.$/) {
  496. next;
  497. }
  498. # Проверка разрешения обновления
  499. my $maybe_update_dns = ($enable_ad_dns_update && $office_networks->match_string($fqdn_ip));
  500. if (!$maybe_update_dns) {
  501. db_log_info($hdb, "FOUND Auth_id: $auth_id. DNS update disabled.");
  502. next;
  503. }
  504. # Удаление PTR
  505. if ($dns_cmd->{operation_type} eq 'del') {
  506. delete_dns_ptr($fqdn, $fqdn_ip, $ad_zone, $ad_dns, $hdb);
  507. }
  508. # Создание PTR
  509. elsif ($dns_cmd->{operation_type} eq 'add') {
  510. create_dns_ptr($fqdn, $fqdn_ip, $ad_zone, $ad_dns, $hdb);
  511. }
  512. }
  513. };
  514. if ($@) {
  515. log_error("Error processing DNS command for auth_id=$auth_id: $@");
  516. }
  517. }
  518. }
  519. #---------------------------------------------------------------------------------------------------------------
  520. sub is_ad_computer {
  521. my ($hdb, $computer_name) = @_;
  522. return 0 unless $hdb;
  523. return 0 if !$computer_name || $computer_name =~ /UNDEFINED/i;
  524. my $ad_check = get_option($hdb, 73);
  525. return 1 unless $ad_check;
  526. my $ad_zone = get_option($hdb, 33);
  527. # Проверка домена (если указан)
  528. if (defined $ad_zone && $ad_zone ne '' && $computer_name =~ /\./) {
  529. if ($computer_name !~ /\Q$ad_zone\E$/i) {
  530. db_log_verbose($hdb, "The domain of the computer $computer_name does not match the domain of the organization $ad_zone. Skip update.");
  531. return 0;
  532. }
  533. }
  534. # Извлекаем NetBIOS-имя (до первой точки)
  535. my $netbios_name = $computer_name;
  536. $netbios_name = $1 if $computer_name =~ /^([^\.]+)/;
  537. # Валидация NetBIOS-имени
  538. if (!$netbios_name || $netbios_name !~ /^[a-zA-Z0-9][a-zA-Z0-9_\-\$]{0,14}$/) {
  539. db_log_verbose($hdb, "Invalid computer name format: '$computer_name'");
  540. return 0;
  541. }
  542. # Проверяем кэш
  543. my $name_in_cache = get_record_sql($hdb, "SELECT * FROM ad_comp_cache WHERE name = ?", $netbios_name);
  544. return 1 if $name_in_cache;
  545. # Ищем в AD
  546. my $ad_computer_name = $netbios_name . '$';
  547. my $safe_name = quotemeta($ad_computer_name);
  548. my %name_found = do_exec_ref("/usr/bin/getent passwd $safe_name");
  549. if (!$name_found{output} || $name_found{status} ne 0) {
  550. db_log_verbose($hdb, "The computer " . uc($ad_computer_name) . " was not found in the domain $ad_zone. Skip update.");
  551. return 0;
  552. }
  553. # Кэшируем
  554. do_sql($hdb, "INSERT INTO ad_comp_cache (name) VALUES (?) ON DUPLICATE KEY UPDATE name = ?",
  555. $netbios_name, $netbios_name);
  556. return 1;
  557. }
  558. #---------------------------------------------------------------------------------------------------------------
  559. sub escape_like {
  560. my ($str) = @_;
  561. return '' unless defined $str;
  562. $str =~ s/([%_\\])/\\$1/g;
  563. return $str;
  564. }
  565. #---------------------------------------------------------------------------------------------------------------
  566. sub update_dns_record_by_dhcp {
  567. my $hdb = shift;
  568. my $dhcp_record = shift;
  569. my $auth_record = shift;
  570. return if (!$config_ref{enable_dns_updates});
  571. my $ad_zone = get_option($hdb,33);
  572. my $ad_dns = get_option($hdb,3);
  573. $update_hostname_from_dhcp = get_option($hdb,46) || 0;
  574. my $subnets_dhcp = get_subnets_ref($hdb);
  575. my $enable_ad_dns_update = ($ad_zone and $ad_dns and $update_hostname_from_dhcp);
  576. log_debug("Dhcp record: ".Dumper($dhcp_record));
  577. log_debug("Subnets: ".Dumper($subnets_dhcp->{$dhcp_record->{network}->{subnet}}));
  578. log_debug("enable_ad_dns_update: ".$enable_ad_dns_update);
  579. log_debug("DNS update flags - zone: ".$ad_zone.",dns: ".$ad_dns.", update_hostname_from_dhcp: ".$update_hostname_from_dhcp.", enable_ad_dns_update: " .
  580. $enable_ad_dns_update. ", network dns-update enabled: ".$subnets_dhcp->{$dhcp_record->{network}->{subnet}}->{dhcp_update_hostname});
  581. my $maybe_update_dns=($enable_ad_dns_update and $subnets_dhcp->{$dhcp_record->{network}->{subnet}}->{dhcp_update_hostname} and
  582. (is_ad_computer($hdb,$dhcp_record->{hostname_utf8}) and ($dhcp_record->{type}=~/add/i or $dhcp_record->{type}=~/old/i)));
  583. if (!$maybe_update_dns) {
  584. db_log_debug($hdb,"FOUND Auth_id: $auth_record->{id}. DNS update don't needed.");
  585. return 0;
  586. }
  587. log_debug("DNS update enabled.");
  588. #update dns block
  589. my $fqdn_static;
  590. if ($auth_record->{dns_name}) {
  591. $fqdn_static=lc($auth_record->{dns_name});
  592. if ($fqdn_static!~/\.$ad_zone$/i) {
  593. $fqdn_static=~s/\.$//;
  594. $fqdn_static=lc($fqdn_static.'.'.$ad_zone);
  595. }
  596. }
  597. my $fqdn=lc(trim($dhcp_record->{hostname_utf8}));
  598. if ($fqdn!~/\.$ad_zone$/i) {
  599. $fqdn=~s/\.$//;
  600. $fqdn=lc($fqdn.'.'.$ad_zone);
  601. }
  602. db_log_debug($hdb,"FOUND Auth_id: $auth_record->{id} dns_name: $fqdn_static dhcp_hostname: $fqdn");
  603. #check exists static dns name
  604. my $static_exists = 0;
  605. my $dynamic_exists = 0;
  606. my $static_ok = 0;
  607. my $dynamic_ok = 0;
  608. my $static_ref;
  609. my $dynamic_ref;
  610. if ($fqdn_static ne '') {
  611. my @dns_record=ResolveNames($fqdn_static,$dns_server);
  612. $static_exists = (scalar @dns_record>0);
  613. if ($static_exists) {
  614. $static_ref = join(' ',@dns_record);
  615. foreach my $dns_a (@dns_record) {
  616. if ($dns_a=~/^$dhcp_record->{ip}$/) { $static_ok = $dns_a; }
  617. }
  618. }
  619. } else { $static_ok = 1; }
  620. if ($fqdn ne '') {
  621. my @dns_record=ResolveNames($fqdn,$dns_server);
  622. $dynamic_exists = (scalar @dns_record>0);
  623. if ($dynamic_exists) {
  624. $dynamic_ref = join(' ',@dns_record);
  625. foreach my $dns_a (@dns_record) {
  626. if ($dns_a=~/^$dhcp_record->{ip}$/) { $dynamic_ok = $dns_a; }
  627. }
  628. }
  629. }
  630. db_log_debug($hdb,"Dns record for static record $fqdn_static: $static_ok");
  631. db_log_debug($hdb,"Dns record for dhcp-hostname $fqdn: $dynamic_ok");
  632. if ($fqdn_static ne '') {
  633. if (!$static_ok) {
  634. db_log_info($hdb,"Static record mismatch! Expected $fqdn_static => $dhcp_record->{ip}, recivied: $static_ref");
  635. if (!$static_exists) {
  636. db_log_info($hdb,"Static dns hostname defined but not found. Create it ($fqdn_static => $dhcp_record->{ip})!");
  637. create_dns_hostname($fqdn_static,$dhcp_record->{ip},$ad_zone,$ad_dns,$hdb);
  638. }
  639. } else {
  640. db_log_debug($hdb,"Static record for $fqdn_static [$static_ok] correct.");
  641. }
  642. }
  643. if ($fqdn ne '' and $dynamic_ok ne '') { db_log_debug($hdb,"Dynamic record for $fqdn [$dynamic_ok] correct. No changes required."); }
  644. if ($fqdn ne '' and !$dynamic_ok) {
  645. log_error("Dynamic record mismatch! Expected: $fqdn => $dhcp_record->{ip}, recivied: $dynamic_ref. Checking the status.");
  646. #check exists hostname
  647. my $another_hostname_exists = 0;
  648. my @conditions;
  649. my @params;
  650. # Первое условие: по hostname_utf8
  651. my $prefix1 = lc($dhcp_record->{hostname_utf8} // '');
  652. if ($prefix1 ne '') {
  653. push @conditions, 'LOWER(dns_name) LIKE ? ';
  654. push @params, $prefix1 . '%';
  655. }
  656. # Второе условие: по dns_name (если нужно)
  657. if ($fqdn_static ne '' && $fqdn !~ /\Q$fqdn_static\E/) {
  658. my $prefix2 = lc($auth_record->{dns_name} // '');
  659. if ($prefix2 ne '') {
  660. push @conditions, 'LOWER(dns_name) LIKE ? ';
  661. push @params, $prefix2 . '%';
  662. }
  663. }
  664. return unless @conditions;
  665. my $cond_sql = join(' OR ', @conditions);
  666. my $filter_sql = "SELECT * FROM user_auth WHERE id <> ? AND deleted = 0 AND ($cond_sql) ORDER BY last_found DESC";
  667. unshift @params, $auth_record->{id};
  668. db_log_debug($hdb, "Search by DNS name prefixes: $cond_sql with params: [" . join(', ', map { "'$_'" } @params) . "]");
  669. my $name_record = get_record_sql($hdb, $filter_sql, @params);
  670. if ($name_record->{dns_name} =~/^$fqdn$/i or $name_record->{dns_name} =~/^$dhcp_record->{hostname_utf8}$/i) {
  671. $another_hostname_exists = 1;
  672. }
  673. if (!$another_hostname_exists) {
  674. if ($fqdn_static and $fqdn_static ne '') {
  675. if ($fqdn_static!~/$fqdn/) {
  676. db_log_info($hdb,"Hostname from dhcp request $fqdn differs from static dns hostname $fqdn_static. Ignore dynamic binding!");
  677. # delete_dns_hostname($fqdn,$dhcp_record->{ip},$ad_zone,$ad_dns,$hdb);
  678. # create_dns_hostname($fqdn,$dhcp_record->{ip},$ad_zone,$ad_dns,$hdb);
  679. }
  680. } else {
  681. db_log_info($hdb,"Rewrite aliases if exists for $fqdn => $dhcp_record->{ip}");
  682. #get and remove aliases
  683. my @aliases = get_records_sql($hdb, "SELECT * FROM user_auth_alias WHERE auth_id = ?", $auth_record->{id});
  684. if (@aliases and scalar @aliases) {
  685. foreach my $alias (@aliases) {
  686. delete_dns_cname($fqdn_static,$alias->{alias},$ad_zone,$ad_dns,$hdb) if ($alias->{alias});
  687. }
  688. }
  689. db_log_info($hdb,"Static dns hostname not defined. Create dns record by dhcp request. $fqdn => $dhcp_record->{ip}");
  690. create_dns_hostname($fqdn,$dhcp_record->{ip},$ad_zone,$ad_dns,$hdb);
  691. if (@aliases and scalar @aliases) {
  692. foreach my $alias (@aliases) {
  693. create_dns_cname($fqdn_static,$alias->{alias},$ad_zone,$ad_dns,$hdb) if ($alias->{alias});
  694. }
  695. }
  696. }
  697. } else {
  698. db_log_error($hdb,"Found another record with some hostname id: $name_record->{id} ip: $name_record->{ip} hostname: $name_record->{dns_name}. Skip update.");
  699. }
  700. }
  701. #end update dns block
  702. }
  703. #------------------------------------------------------------------------------------------------------------
  704. sub apply_device_lock {
  705. my $db = shift;
  706. my $device_id = shift;
  707. my $iteration = shift || 0;
  708. $iteration++;
  709. if ($iteration > 2) { return 0; }
  710. my $dev = get_record_sql($db, "SELECT discovery_locked, locked_timestamp FROM devices WHERE id = ?", $device_id);
  711. if (!$dev) { return 0; }
  712. if (!$dev->{'discovery_locked'}) {
  713. return set_lock_discovery($db, $device_id);
  714. }
  715. my $ts_str = $dev->{'locked_timestamp'};
  716. # Если locked_timestamp NULL или пустой — устанавливаем блокировку
  717. if (!defined $ts_str || $ts_str eq '' || $ts_str eq '0000-00-00 00:00:00') {
  718. return set_lock_discovery($db, $device_id);
  719. }
  720. # Удаляем микросекунды (PostgreSQL) для совместимости с форматом
  721. $ts_str =~ s/\.\d+$//;
  722. # Парсим строку в DateTime
  723. my $parser = DateTime::Format::Strptime->new(
  724. pattern => '%Y-%m-%d %H:%M:%S',
  725. on_error => 'croak',
  726. );
  727. my $dt;
  728. eval {
  729. $dt = $parser->parse_datetime($ts_str);
  730. };
  731. if ($@ || !$dt) {
  732. # Ошибка парсинга — считаем блокировку недействительной
  733. return set_lock_discovery($db, $device_id);
  734. }
  735. # Получаем Unix timestamp
  736. my $u_locked_timestamp = $dt->epoch;
  737. # Ждём окончания блокировки (30 секунд)
  738. my $wait_time = ($u_locked_timestamp + 30) - time();
  739. if ($wait_time <= 0) {
  740. return set_lock_discovery($db, $device_id);
  741. }
  742. sleep($wait_time);
  743. return apply_device_lock($db, $device_id, $iteration);
  744. }
  745. #------------------------------------------------------------------------------------------------------------
  746. sub set_lock_discovery {
  747. my $db = shift;
  748. my $device_id = shift;
  749. my $new;
  750. $new->{'discovery_locked'} = 1;
  751. $new->{'locked_timestamp'} = GetNowTime();
  752. if (update_record($db,'devices',$new,'id=?', $device_id)) { return 1; }
  753. return 0;
  754. }
  755. #------------------------------------------------------------------------------------------------------------
  756. sub unset_lock_discovery {
  757. my $db = shift;
  758. my $device_id = shift;
  759. my $new;
  760. $new->{'discovery_locked'} = 0;
  761. $new->{'locked_timestamp'} = GetNowTime();
  762. if (update_record($db,'devices',$new,'id=?',$device_id)) { return 1; }
  763. return 0;
  764. }
  765. #------------------------------------------------------------------------------------------------------------
  766. sub create_dns_cname {
  767. my $fqdn = shift;
  768. my $alias = shift;
  769. my $zone = shift;
  770. my $server = shift;
  771. my $db = shift;
  772. #skip update domain controllers
  773. if (!$db) {
  774. log_info("DNS-UPDATE: Add => Zone $zone Server: $server CNAME: $alias for $fqdn");
  775. } else {
  776. db_log_info($db,"DNS-UPDATE: Add => Zone $zone Server: $server CNAME: $alias for $fqdn ");
  777. }
  778. my $ad_zone = get_option($db,33);
  779. my $nsupdate_file = "/tmp/".$fqdn."-nsupdate";
  780. my @add_dns;
  781. if ($config_ref{dns_server_type}=~/windows/i) {
  782. push(@add_dns,"gsstsig");
  783. push(@add_dns,"server $server");
  784. push(@add_dns,"zone $zone");
  785. push(@add_dns,"update add $alias 3600 cname $fqdn.");
  786. push(@add_dns,"send");
  787. write_to_file($nsupdate_file,\@add_dns);
  788. do_exec('/usr/bin/kinit -k -t /opt/Eye/scripts/cfg/dns_updater.keytab dns_updater@'.uc($ad_zone).' && /usr/bin/nsupdate "'.$nsupdate_file.'"');
  789. }
  790. if ($config_ref{dns_server_type}=~/bind/i) {
  791. push(@add_dns,"server $server");
  792. push(@add_dns,"zone $zone");
  793. push(@add_dns,"update add $alias 3600 cname $fqdn.");
  794. push(@add_dns,"send");
  795. write_to_file($nsupdate_file,\@add_dns);
  796. do_exec('/usr/bin/nsupdate -k /etc/bind/rndc.key "'.$nsupdate_file.'"');
  797. }
  798. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  799. }
  800. #---------------------------------------------------------------------------------------------------------------
  801. sub delete_dns_cname {
  802. my $fqdn = shift;
  803. my $alias = shift;
  804. my $zone = shift;
  805. my $server = shift;
  806. my $db = shift;
  807. if (!$db) {
  808. log_info("DNS-UPDATE: Delete => Zone $zone Server: $server CNAME: $alias for $fqdn ");
  809. } else {
  810. db_log_info($db,"DNS-UPDATE: Delete => Zone $zone Server: $server CNAME: $alias for $fqdn");
  811. }
  812. my $ad_zone = get_option($db,33);
  813. my $nsupdate_file = "/tmp/".$fqdn."-nsupdate";
  814. my @add_dns;
  815. if ($config_ref{dns_server_type}=~/windows/i) {
  816. push(@add_dns,"gsstsig");
  817. push(@add_dns,"server $server");
  818. push(@add_dns,"zone $zone");
  819. push(@add_dns,"update delete $alias cname ");
  820. push(@add_dns,"send");
  821. write_to_file($nsupdate_file,\@add_dns);
  822. do_exec('/usr/bin/kinit -k -t /opt/Eye/scripts/cfg/dns_updater.keytab dns_updater@'.uc($ad_zone).' && /usr/bin/nsupdate "'.$nsupdate_file.'"');
  823. }
  824. if ($config_ref{dns_server_type}=~/bind/i) {
  825. push(@add_dns,"server $server");
  826. push(@add_dns,"zone $zone");
  827. push(@add_dns,"update delete $alias cname");
  828. push(@add_dns,"send");
  829. write_to_file($nsupdate_file,\@add_dns);
  830. do_exec('/usr/bin/nsupdate -k /etc/bind/rndc.key "'.$nsupdate_file.'"');
  831. }
  832. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  833. }
  834. #------------------------------------------------------------------------------------------------------------
  835. sub create_dns_hostname {
  836. my $fqdn = shift;
  837. my $ip = shift;
  838. my $zone = shift;
  839. my $server = shift;
  840. my $db = shift;
  841. #skip update domain controllers
  842. if ($fqdn=~/^dc[0-9]{1,2}\./i) { return; }
  843. if (!$db) {
  844. log_info("DNS-UPDATE: Add => Zone $zone Server: $server A: $fqdn IP: $ip");
  845. } else {
  846. db_log_info($db,"DNS-UPDATE: Add => Zone $zone Server: $server A: $fqdn IP: $ip");
  847. }
  848. my $ad_zone = get_option($db,33);
  849. my $nsupdate_file = "/tmp/".$fqdn."-nsupdate";
  850. my @add_dns;
  851. if ($config_ref{dns_server_type}=~/windows/i) {
  852. push(@add_dns,"gsstsig");
  853. push(@add_dns,"server $server");
  854. push(@add_dns,"zone $zone");
  855. push(@add_dns,"update add $fqdn 3600 A $ip");
  856. push(@add_dns,"send");
  857. write_to_file($nsupdate_file,\@add_dns);
  858. do_exec('/usr/bin/kinit -k -t /opt/Eye/scripts/cfg/dns_updater.keytab dns_updater@'.uc($ad_zone).' && /usr/bin/nsupdate "'.$nsupdate_file.'"');
  859. }
  860. if ($config_ref{dns_server_type}=~/bind/i) {
  861. push(@add_dns,"server $server");
  862. push(@add_dns,"zone $zone");
  863. push(@add_dns,"update add $fqdn 3600 A $ip");
  864. push(@add_dns,"send");
  865. write_to_file($nsupdate_file,\@add_dns);
  866. do_exec('/usr/bin/nsupdate -k /etc/bind/rndc.key "'.$nsupdate_file.'"');
  867. }
  868. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  869. }
  870. #---------------------------------------------------------------------------------------------------------------
  871. sub delete_dns_hostname {
  872. my $fqdn = shift;
  873. my $ip = shift;
  874. my $zone = shift;
  875. my $server = shift;
  876. my $db = shift;
  877. #skip update domain controllers
  878. if ($fqdn=~/^dc[0-9]{1,2}\./i) { return; }
  879. if (!$db) {
  880. log_info("DNS-UPDATE: Delete => Zone $zone Server: $server A: $fqdn IP: $ip");
  881. } else {
  882. db_log_info($db,"DNS-UPDATE: Delete => Zone $zone Server: $server A: $fqdn IP: $ip");
  883. }
  884. my $ad_zone = get_option($db,33);
  885. my $nsupdate_file = "/tmp/".$fqdn."-nsupdate";
  886. my @add_dns;
  887. if ($config_ref{dns_server_type}=~/windows/i) {
  888. push(@add_dns,"gsstsig");
  889. push(@add_dns,"server $server");
  890. push(@add_dns,"zone $zone");
  891. push(@add_dns,"update delete $fqdn A");
  892. push(@add_dns,"send");
  893. write_to_file($nsupdate_file,\@add_dns);
  894. do_exec('/usr/bin/kinit -k -t /opt/Eye/scripts/cfg/dns_updater.keytab dns_updater@'.uc($ad_zone).' && /usr/bin/nsupdate "'.$nsupdate_file.'"');
  895. }
  896. if ($config_ref{dns_server_type}=~/bind/i) {
  897. push(@add_dns,"server $server");
  898. push(@add_dns,"zone $zone");
  899. push(@add_dns,"update delete $fqdn A");
  900. push(@add_dns,"send");
  901. write_to_file($nsupdate_file,\@add_dns);
  902. do_exec('/usr/bin/nsupdate -k /etc/bind/rndc.key "'.$nsupdate_file.'"');
  903. }
  904. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  905. }
  906. #---------------------------------------------------------------------------------------------------------------
  907. sub create_dns_ptr {
  908. my $fqdn = shift;
  909. my $ip = shift;
  910. my $ad_zone = shift;
  911. my $server = shift;
  912. my $db = shift;
  913. my $radr;
  914. my $zone;
  915. #skip update domain controllers
  916. if ($fqdn=~/^dc[0-9]{1,2}\./i) { return; }
  917. if ($ip =~ /([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})(\/[0-9]{1,2}){0,1}/) {
  918. return 0 if($1 > 255 || $2 > 255 || $3 > 255 || $4 > 255);
  919. $radr = "$4.$3.$2.$1.in-addr.arpa";
  920. $zone = "$3.$2.$1.in-addr.arpa";
  921. }
  922. if (!$radr or !$zone) { return 0; }
  923. if (!$db) { return 0; }
  924. db_log_info($db,"DNS-UPDATE: Zone $zone Server: $server A: $fqdn PTR: $ip");
  925. my $nsupdate_file = "/tmp/".$radr."-nsupdate";
  926. my @add_dns;
  927. if ($config_ref{dns_server_type}=~/windows/i) {
  928. push(@add_dns,"gsstsig");
  929. push(@add_dns,"server $server");
  930. push(@add_dns,"zone $zone");
  931. push(@add_dns,"update add $radr 3600 PTR $fqdn.");
  932. push(@add_dns,"send");
  933. write_to_file($nsupdate_file,\@add_dns);
  934. my $run_cmd = '/usr/bin/kinit -k -t /opt/Eye/scripts/cfg/dns_updater.keytab dns_updater@'.uc($ad_zone).' && /usr/bin/nsupdate "'.$nsupdate_file.'"';
  935. do_exec($run_cmd);
  936. }
  937. if ($config_ref{dns_server_type}=~/bind/i) {
  938. push(@add_dns,"server $server");
  939. push(@add_dns,"zone $zone");
  940. push(@add_dns,"update add $radr 3600 PTR $fqdn.");
  941. push(@add_dns,"send");
  942. write_to_file($nsupdate_file,\@add_dns);
  943. my $run_cmd = '/usr/bin/nsupdate -k /etc/bind/rndc.key "'.$nsupdate_file.'"';
  944. do_exec($run_cmd);
  945. }
  946. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  947. }
  948. #---------------------------------------------------------------------------------------------------------------
  949. sub delete_dns_ptr {
  950. my $fqdn = shift;
  951. my $ip = shift;
  952. my $ad_zone = shift;
  953. my $server = shift;
  954. my $db = shift;
  955. my $radr;
  956. my $zone;
  957. #skip update domain controllers
  958. if ($fqdn=~/^dc[0-9]{1,2}\./i) { return; }
  959. if ($ip =~ /([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})(\/[0-9]{1,2}){0,1}/) {
  960. return 0 if($1 > 255 || $2 > 255 || $3 > 255 || $4 > 255);
  961. $radr = "$4.$3.$2.$1.in-addr.arpa";
  962. $zone = "$3.$2.$1.in-addr.arpa";
  963. }
  964. if (!$radr or !$zone) { return 0; }
  965. if (!$db) { return 0; }
  966. db_log_info($db,"DNS-UPDATE: Delete => Zone $zone Server: $server A: $fqdn PTR: $ip");
  967. my $nsupdate_file = "/tmp/".$radr."-nsupdate";
  968. my @add_dns;
  969. if ($config_ref{dns_server_type}=~/windows/i) {
  970. push(@add_dns,"gsstsig");
  971. push(@add_dns,"server $server");
  972. push(@add_dns,"zone $zone");
  973. push(@add_dns,"update delete $radr PTR");
  974. push(@add_dns,"send");
  975. write_to_file($nsupdate_file,\@add_dns);
  976. my $run_cmd = '/usr/bin/kinit -k -t /opt/Eye/scripts/cfg/dns_updater.keytab dns_updater@'.uc($ad_zone).' && /usr/bin/nsupdate "'.$nsupdate_file.'"';
  977. do_exec($run_cmd);
  978. }
  979. if ($config_ref{dns_server_type}=~/bind/i) {
  980. push(@add_dns,"server $server");
  981. push(@add_dns,"zone $zone");
  982. push(@add_dns,"update delete $radr PTR");
  983. push(@add_dns,"send");
  984. write_to_file($nsupdate_file,\@add_dns);
  985. my $run_cmd = '/usr/bin/nsupdate -k /etc/bind/rndc.key "'.$nsupdate_file.'"';
  986. do_exec($run_cmd);
  987. }
  988. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  989. }
  990. #---------------------------------------------------------------------------------------------------------------
  991. sub new_user {
  992. my ($db, $user_info) = @_;
  993. return 0 unless $db && $user_info;
  994. my $user = {};
  995. # Формируем login: MAC приоритетен, иначе IP
  996. if ($user_info->{mac}) {
  997. $user->{login} = mac_splitted($user_info->{mac});
  998. } else {
  999. $user->{login} = $user_info->{ip} || 'unknown';
  1000. }
  1001. # Формируем description с указанием источника
  1002. my $base_desc = $user_info->{dhcp_hostname} || $user->{login};
  1003. if ($debug) {
  1004. $user->{description} = $base_desc. '['. get_creation_method() . ']';
  1005. } else {
  1006. $user->{description} = $base_desc;
  1007. }
  1008. # Генерация уникального логина
  1009. my $base_login = $user->{login};
  1010. my $like_pattern = $base_login . '%';
  1011. my $count_sql = "SELECT COUNT(*) AS rec_cnt FROM user_list WHERE login LIKE ? OR login = ?";
  1012. my $count_record = get_record_sql($db, $count_sql, $like_pattern, $base_login);
  1013. my $login_count = $count_record ? ($count_record->{rec_cnt} || 0) : 0;
  1014. if ($login_count > 0) {
  1015. $user->{login} = $base_login . '(' . ($login_count + 1) . ')';
  1016. }
  1017. # OU info
  1018. $user->{ou_id} = $user_info->{ou_id};
  1019. my $ou_info;
  1020. if ($user_info->{ou_id}) {
  1021. $ou_info = get_record_sql($db, "SELECT * FROM ou WHERE id = ?", $user_info->{ou_id});
  1022. }
  1023. if ($ou_info) {
  1024. $user->{enabled} = $ou_info->{enabled};
  1025. $user->{queue_id} = $ou_info->{queue_id};
  1026. $user->{filter_group_id} = $ou_info->{filter_group_id};
  1027. }
  1028. # Создаём пользователя
  1029. my $result = insert_record($db, "user_list", $user);
  1030. # Авто-правило по MAC
  1031. if ($result && $config_ref{auto_mac_rule} && $user_info->{mac}) {
  1032. insert_record($db, "auth_rules", {
  1033. user_id => $result,
  1034. rule_type => 2,
  1035. rule => mac_splitted($user_info->{mac}),
  1036. });
  1037. }
  1038. return $result;
  1039. }
  1040. #---------------------------------------------------------------------------------------------------------------
  1041. sub get_ip_subnet {
  1042. my ($db, $ip) = @_;
  1043. return unless $db && defined $ip && $ip ne '';
  1044. my $ip_aton = StrToIp($ip);
  1045. return unless defined $ip_aton && $ip_aton > 0;
  1046. my $user_subnet = get_record_sql($db,
  1047. "SELECT * FROM subnets WHERE (hotspot = 1 OR office = 1) AND ? BETWEEN ip_int_start AND ip_int_stop",
  1048. $ip_aton
  1049. );
  1050. return $user_subnet;
  1051. }
  1052. #---------------------------------------------------------------------------------------------------------------
  1053. sub find_mac_in_subnet {
  1054. my ($db, $ip, $mac) = @_;
  1055. return unless $db && defined $ip && defined $mac && $ip ne '' && $mac ne '';
  1056. my $ip_subnet = get_ip_subnet($db, $ip);
  1057. return unless $ip_subnet
  1058. && exists $ip_subnet->{ip_int_start}
  1059. && exists $ip_subnet->{ip_int_stop};
  1060. my @t_auth = get_records_sql($db,
  1061. "SELECT * FROM user_auth
  1062. WHERE ip_int BETWEEN ? AND ?
  1063. AND mac = ?
  1064. AND deleted = 0
  1065. ORDER BY id",
  1066. $ip_subnet->{ip_int_start},
  1067. $ip_subnet->{ip_int_stop},
  1068. $mac
  1069. );
  1070. # Если ничего не найдено — вернуть undef
  1071. return unless @t_auth;
  1072. # Формируем результат в требуемом формате
  1073. my $result = { count => 0, items => {} };
  1074. for my $i (0 .. $#t_auth) {
  1075. my $row = $t_auth[$i];
  1076. my $n = $i + 1;
  1077. $result->{count} = $n;
  1078. $result->{items}{$n} = $row;
  1079. }
  1080. return $result;
  1081. }
  1082. #---------------------------------------------------------------------------------------------------------------
  1083. sub get_creation_method {
  1084. my $script_name = $config_ref{my_name} // (split('/', $0))[-1];
  1085. return 'dhcp' if $script_name eq 'dhcp-log.pl';
  1086. return 'netflow' if $script_name eq 'eye-statd.pl';
  1087. return 'arp' if $script_name eq 'fetch_new_arp.pl';
  1088. # По умолчанию — имя скрипта без расширения
  1089. $script_name =~ s/\.pl$//;
  1090. return $script_name || 'unknown';
  1091. }
  1092. #---------------------------------------------------------------------------------------------------------------
  1093. sub resurrection_auth {
  1094. my ($db, $ip_record) = @_;
  1095. return 0 unless $db && ref $ip_record eq 'HASH';
  1096. my $ip = $ip_record->{ip} // '';
  1097. my $mac = $ip_record->{mac} // '';
  1098. my $action = $ip_record->{type} // '';
  1099. my $hostname= $ip_record->{hostname_utf8} // '';
  1100. my $client_id = $ip_record->{client_id} // '';
  1101. return 0 if !$ip || !$mac;
  1102. # Подготавливаем ip_aton и hotspot
  1103. $ip_record->{ip_aton} //= StrToIp($ip);
  1104. $ip_record->{hotspot} //= is_hotspot($db, $ip);
  1105. my $auth_ident = "Found new ip-address: $ip";
  1106. $auth_ident .= " [$mac]" if $mac;
  1107. $auth_ident .= " :: $hostname" if $hostname;
  1108. my $ip_aton = $ip_record->{ip_aton};
  1109. return 0 unless defined $ip_aton;
  1110. my $timestamp = GetNowTime();
  1111. # --- Ищем существующую запись по IP+MAC ---
  1112. my $record = get_record_sql($db,
  1113. "SELECT * FROM user_auth WHERE deleted = 0 AND ip_int = ? AND mac = ?",
  1114. $ip_aton, $mac
  1115. );
  1116. my $new_record = {
  1117. last_found => $timestamp,
  1118. arp_found => $timestamp,
  1119. };
  1120. if ($client_id) { $new_record->{client_id} = $client_id; }
  1121. # Если нашли — обновляем
  1122. if ($record && $record->{user_id}) {
  1123. if ($action =~ /^(add|old|del)$/i) {
  1124. $new_record->{dhcp_action} = $action;
  1125. $new_record->{created_by} = 'dhcp';
  1126. $new_record->{dhcp_time} = $timestamp;
  1127. $new_record->{dhcp_hostname} = $hostname if $hostname;
  1128. } else {
  1129. $new_record->{created_by} = $action // get_creation_method();
  1130. }
  1131. update_record($db, 'user_auth', $new_record, 'id = ?', $record->{id});
  1132. return $record->{id};
  1133. }
  1134. my $send_alert_create = isNotifyCreate(get_notify_subnet($db, $ip));
  1135. # --- Проверка статической подсети ---
  1136. my $user_subnet = $office_networks->match_string($ip);
  1137. if ($user_subnet && $user_subnet->{static}) {
  1138. my $msg = "Found new unknown ip+mac in static subnet! Abort create record for this: $ip [$mac]";
  1139. db_log_warning($db, $msg);
  1140. sendEmail("WARN! " . get_first_line($msg), $msg, 1) if $send_alert_create;
  1141. return 0;
  1142. }
  1143. my $send_alert_update = isNotifyUpdate(get_notify_subnet($db, $ip));
  1144. # --- Ищем другие записи с этим MAC в той же подсети ---
  1145. my $mac_exists = find_mac_in_subnet($db, $ip, $mac);
  1146. # --- Ищем запись с тем же IP (но другим MAC) ---
  1147. my $ip_record_same = get_record_sql($db,
  1148. "SELECT * FROM user_auth WHERE ip_int = ? AND deleted = 0",
  1149. $ip_aton
  1150. );
  1151. if ($ip_record_same && $ip_record_same->{id}) {
  1152. if (!$ip_record_same->{mac}) {
  1153. # Обновляем запись без MAC
  1154. $new_record->{mac} = $mac;
  1155. if ($mac_exists && $mac_exists->{count}>=1) {
  1156. # выключаем dhcp если есть записи в этой же подсети с другим ip и этим маком
  1157. $new_record->{dhcp} = 0;
  1158. }
  1159. if ($action =~ /^(add|old|del)$/i) {
  1160. $new_record->{dhcp_action} = $action;
  1161. $new_record->{dhcp_time} = $timestamp;
  1162. $new_record->{created_by} = 'dhcp';
  1163. $new_record->{dhcp_hostname} = $hostname if $hostname;
  1164. } else {
  1165. $new_record->{created_by} = $action // get_creation_method();
  1166. }
  1167. update_record($db, 'user_auth', $new_record, 'id = ?', $ip_record_same->{id});
  1168. return $ip_record_same->{id};
  1169. } elsif ($ip_record_same->{mac}) {
  1170. # MAC изменился — удаляем старую запись
  1171. if (!$ip_record->{hotspot}) {
  1172. my $msg = "For ip: $ip mac change detected! Old mac: [$ip_record_same->{mac}] New mac: [$mac]. Disable old auth_id: $ip_record_same->{id}";
  1173. db_log_warning($db, $msg, $ip_record_same->{id});
  1174. sendEmail("WARN! " . get_first_line($msg), $msg, 1) if $send_alert_update;
  1175. }
  1176. delete_user_auth($db, $ip_record_same->{id});
  1177. }
  1178. }
  1179. # --- Создаём нового пользователя, если нужно ---
  1180. my $new_user_info = get_new_user_id($db, $ip, $mac, $hostname);
  1181. my $new_user_id = $new_user_info->{user_id} // new_user($db, $new_user_info);
  1182. # --- Удаляем дубли с dynamic=1 ---
  1183. if ($mac_exists && $mac_exists->{items}) {
  1184. for my $dup_id (keys %{$mac_exists->{items}}) {
  1185. my $dup = $mac_exists->{items}{$dup_id};
  1186. next unless $dup && $dup->{dynamic};
  1187. delete_user_auth($db, $dup->{id});
  1188. }
  1189. }
  1190. # --- Повторная проверка ---
  1191. $mac_exists = find_mac_in_subnet($db, $ip, $mac);
  1192. if ($mac_exists && $mac_exists->{count}>=1) {
  1193. $new_record->{dhcp} = 0
  1194. }
  1195. # --- Готовим полную запись ---
  1196. $new_record->{ip_int} = $ip_aton;
  1197. $new_record->{ip} = $ip;
  1198. $new_record->{mac} = $mac;
  1199. $new_record->{user_id} = $new_user_id;
  1200. $new_record->{save_traf} = $save_detail;
  1201. $new_record->{deleted} = 0;
  1202. if ($action =~ /^(add|old|del)$/i) {
  1203. $new_record->{dhcp_action} = $action;
  1204. $new_record->{dhcp_time} = $timestamp;
  1205. $new_record->{created_by} = 'dhcp';
  1206. } else {
  1207. $new_record->{created_by} = $action // get_creation_method();
  1208. }
  1209. # --- Проверяем, существует ли уже такая запись ---
  1210. my $auth_exists = get_record_sql($db,
  1211. "SELECT id FROM user_auth WHERE ip_int = ? AND mac = ? LIMIT 1",
  1212. $ip_aton, $mac
  1213. );
  1214. my $cur_auth_id;
  1215. my $msg = '';
  1216. if ($auth_exists && $auth_exists->{id}) {
  1217. # Воскрешаем старую запись
  1218. $cur_auth_id = $auth_exists->{id};
  1219. $msg = "$auth_ident Resurrection auth_id: $cur_auth_id with ip: $ip and mac: $mac";
  1220. if (!$ip_record->{hotspot}) { db_log_warning($db, $msg); } else { db_log_info($db, $msg); }
  1221. update_record($db, 'user_auth', $new_record, 'id = ?', $cur_auth_id);
  1222. } else {
  1223. # Создаём новую
  1224. $cur_auth_id = insert_record($db, 'user_auth', $new_record);
  1225. if ($cur_auth_id) {
  1226. $msg = $auth_ident;
  1227. if (!$ip_record->{hotspot}) { db_log_warning($db, $msg); } else { db_log_info($db, $msg); }
  1228. }
  1229. }
  1230. return 0 unless $cur_auth_id;
  1231. # --- Дополняем данными из user_list и OU ---
  1232. my $user_record = get_record_sql($db, "SELECT * FROM user_list WHERE id = ?", $new_user_id);
  1233. if ($user_record) {
  1234. my $ou_info = get_record_sql($db, "SELECT * FROM ou WHERE id = ?", $user_record->{ou_id});
  1235. if ($ou_info && $ou_info->{dynamic}) {
  1236. my $life_duration = $ou_info->{life_duration} // 24;
  1237. my $hours = int($life_duration);
  1238. my $minutes = ($life_duration - $hours) * 60;
  1239. my $now = DateTime->now(time_zone => 'local');
  1240. my $end_life = $now->clone->add(hours => $hours, minutes => $minutes);
  1241. $new_record->{dynamic} = 1;
  1242. $new_record->{end_life} = $end_life->strftime('%Y-%m-%d %H:%M:%S');
  1243. }
  1244. $new_record->{ou_id} = $user_record->{ou_id};
  1245. $new_record->{description} = $user_record->{description};
  1246. $new_record->{filter_group_id} = $user_record->{filter_group_id};
  1247. $new_record->{queue_id} = $user_record->{queue_id};
  1248. $new_record->{enabled} = $user_record->{enabled} // 0;
  1249. update_record($db, 'user_auth', $new_record, 'id = ?', $cur_auth_id);
  1250. }
  1251. my $final_record = get_record_sql($db, "SELECT * FROM user_auth WHERE id = ?", $cur_auth_id);
  1252. my $changed_msg = prepare_audit_message($db, 'user_auth', undef, $final_record , $cur_auth_id, 'insert');
  1253. $msg .= "\n". $changed_msg;
  1254. db_log_warning($db, $msg, $cur_auth_id);
  1255. sendEmail("WARN! " . get_first_line($msg), $msg , 1) if $send_alert_create;
  1256. return $cur_auth_id;
  1257. }
  1258. #---------------------------------------------------------------------------------------------------------------
  1259. sub new_auth {
  1260. my ($db, $ip) = @_;
  1261. return 0 unless $db && defined $ip && $ip ne '';
  1262. my $ip_aton = StrToIp($ip);
  1263. return 0 unless defined $ip_aton;
  1264. # Проверяем, существует ли уже запись с таким IP
  1265. my $record = get_record_sql($db,
  1266. "SELECT id FROM user_auth WHERE deleted = 0 AND ip_int = ?",
  1267. $ip_aton
  1268. );
  1269. return $record->{id} if $record && $record->{id};
  1270. # Получаем информацию о пользователе/OU
  1271. my $new_user_info = get_new_user_id($db, $ip, undef, undef);
  1272. return 0 unless $new_user_info;
  1273. my $new_user_id;
  1274. if ($new_user_info->{user_id}) {
  1275. $new_user_id = $new_user_info->{user_id};
  1276. } elsif ($new_user_info->{ou_id}) {
  1277. $new_user_id = new_user($db, $new_user_info);
  1278. }
  1279. return 0 unless $new_user_id;
  1280. my $send_alert = isNotifyCreate(get_notify_subnet($db, $ip));
  1281. # Получаем данные пользователя БЕЗОПАСНО
  1282. my $user_record = get_record_sql($db,
  1283. "SELECT * FROM user_list WHERE id = ?",
  1284. $new_user_id
  1285. );
  1286. return 0 unless $user_record;
  1287. my $timestamp = GetNowTime();
  1288. my $new_record = {
  1289. ip_int => $ip_aton,
  1290. ip => $ip,
  1291. user_id => $new_user_id,
  1292. save_traf => $save_detail,
  1293. deleted => 0,
  1294. created_by => get_creation_method(),
  1295. ou_id => $user_record->{ou_id},
  1296. filter_group_id => $user_record->{filter_group_id},
  1297. queue_id => $user_record->{queue_id},
  1298. enabled => $user_record->{enabled} // 0,
  1299. };
  1300. $new_record->{description} = $user_record->{description} if $user_record->{description};
  1301. my $cur_auth_id = insert_record($db, 'user_auth', $new_record);
  1302. return $cur_auth_id;
  1303. }
  1304. #--------------------------------------------------------------------------------------------------------------
  1305. sub get_dynamic_ou {
  1306. my $db = shift;
  1307. my @dynamic=();
  1308. my @ou_list = get_records_sql($db,"SELECT id FROM ou WHERE dynamic = 1");
  1309. foreach my $group (@ou_list) {
  1310. next if (!$group);
  1311. push(@dynamic,$group->{id});
  1312. }
  1313. return wantarray ? @dynamic : \@dynamic;
  1314. }
  1315. #--------------------------------------------------------------------------------------------------------------
  1316. sub get_default_ou {
  1317. my $db = shift;
  1318. my @dynamic=();
  1319. my $ou = get_record_sql($db,"SELECT id FROM ou WHERE default_users = 1");
  1320. if (!$ou) { push(@dynamic,0); } else { push(@dynamic,$ou->{'id'}); }
  1321. $ou = get_record_sql($db,"SELECT id FROM ou WHERE default_hotspot = 1");
  1322. if ($ou) { push(@dynamic,$ou->{id}); }
  1323. return wantarray ? @dynamic : \@dynamic;
  1324. }
  1325. #--------------------------------------------------------------------------------------------------------------
  1326. sub is_dynamic_ou {
  1327. my $db = shift;
  1328. my $ou_id = shift;
  1329. my @dynamic=get_dynamic_ou($db);
  1330. if (in_array(\@dynamic,$ou_id)) { return 1; }
  1331. return 0;
  1332. }
  1333. #--------------------------------------------------------------------------------------------------------------
  1334. sub is_default_ou {
  1335. my $db = shift;
  1336. my $ou_id = shift;
  1337. my @dynamic=get_default_ou($db);
  1338. if (in_array(\@dynamic,$ou_id)) { return 1; }
  1339. return 0;
  1340. }
  1341. #---------------------------------------------------------------------------------------------------------------
  1342. sub get_subnets_ref {
  1343. my $db = shift;
  1344. my @list=get_records_sql($db,'SELECT * FROM subnets ORDER BY ip_int_start');
  1345. my $list_ref;
  1346. foreach my $net (@list) {
  1347. next if (!$net->{subnet});
  1348. $list_ref->{$net->{subnet}}=$net;
  1349. }
  1350. return $list_ref;
  1351. }
  1352. #---------------------------------------------------------------------------------------------------------------
  1353. sub get_device_by_ip {
  1354. my ($db, $ip) = @_;
  1355. return unless $db && defined $ip && $ip ne '';
  1356. # Ищем устройство напрямую по IP
  1357. my $netdev = get_record_sql($db, "SELECT * FROM devices WHERE ip = ?", $ip);
  1358. return $netdev if $netdev && $netdev->{id} > 0;
  1359. # Ищем user_id по IP в user_auth
  1360. my $auth_rec = get_record_sql($db,
  1361. "SELECT user_id FROM user_auth WHERE ip = ? AND deleted = 0",
  1362. $ip
  1363. );
  1364. if ($auth_rec && defined $auth_rec->{user_id} && $auth_rec->{user_id} > 0) {
  1365. $netdev = get_record_sql($db,
  1366. "SELECT * FROM devices WHERE user_id = ?",
  1367. $auth_rec->{user_id}
  1368. );
  1369. return $netdev;
  1370. }
  1371. return;
  1372. }
  1373. #---------------------------------------------------------------------------------------------------------------
  1374. sub recalc_quotes {
  1375. my ($db, $calc_id) = @_;
  1376. $calc_id //= $$;
  1377. return unless get_option($db, 54);
  1378. clean_variables($db);
  1379. return if Get_Variable($db, 'RECALC');
  1380. my $timeshift = get_option($db, 55);
  1381. Set_Variable($db, 'RECALC', $calc_id, time() + $timeshift * 60);
  1382. # --- Готовим временные метки ---
  1383. my $now = DateTime->now(time_zone => 'local');
  1384. my $day_start = $now->clone->truncate(to => 'day');
  1385. my $day_stop = $day_start->clone->add(days => 1);
  1386. my $month_start = $now->clone->truncate(to => 'month');
  1387. my $month_stop = $month_start->clone->add(months => 1);
  1388. # --- Получаем список авторизаций ---
  1389. my $user_auth_list_sql = q{
  1390. SELECT A.id as auth_id, U.id, U.day_quota, U.month_quota,
  1391. A.day_quota as auth_day, A.month_quota as auth_month
  1392. FROM user_auth AS A
  1393. JOIN user_list AS U ON A.user_id = U.id
  1394. WHERE A.deleted = 0
  1395. ORDER BY user_id
  1396. };
  1397. my @authlist_ref = get_records_sql($db, $user_auth_list_sql);
  1398. my %user_stats;
  1399. my %auth_info;
  1400. foreach my $row (@authlist_ref) {
  1401. $auth_info{$row->{auth_id}}{user_id} = $row->{id};
  1402. $auth_info{$row->{auth_id}}{day_limit} = $row->{auth_day} // 0;
  1403. $auth_info{$row->{auth_id}}{month_limit} = $row->{auth_month} // 0;
  1404. $auth_info{$row->{auth_id}}{day} = 0;
  1405. $auth_info{$row->{auth_id}}{month} = 0;
  1406. $user_stats{$row->{id}}{day_limit} = $row->{day_quota} // 0;
  1407. $user_stats{$row->{id}}{month_limit} = $row->{month_quota} // 0;
  1408. $user_stats{$row->{id}}{day} = 0;
  1409. $user_stats{$row->{id}}{month} = 0;
  1410. }
  1411. # --- Считаем дневной трафик ---
  1412. my @day_stats = get_records_sql($db,
  1413. "SELECT auth_id, SUM(byte_in + byte_out) AS traf_all
  1414. FROM user_stats
  1415. WHERE ts >= ? AND ts < ?
  1416. GROUP BY auth_id",
  1417. $day_start->strftime('%Y-%m-%d %H:%M:%S'),
  1418. $day_stop->strftime('%Y-%m-%d %H:%M:%S')
  1419. );
  1420. foreach my $row (@day_stats) {
  1421. my $user_id = $auth_info{$row->{auth_id}}{user_id};
  1422. $auth_info{$row->{auth_id}}{day} = $row->{traf_all} // 0;
  1423. $user_stats{$user_id}{day} += $row->{traf_all} // 0;
  1424. }
  1425. # --- Считаем месячный трафик ---
  1426. my @month_stats = get_records_sql($db,
  1427. "SELECT auth_id, SUM(byte_in + byte_out) AS traf_all
  1428. FROM user_stats
  1429. WHERE ts >= ? AND ts < ?
  1430. GROUP BY auth_id",
  1431. $month_start->strftime('%Y-%m-%d %H:%M:%S'),
  1432. $month_stop->strftime('%Y-%m-%d %H:%M:%S')
  1433. );
  1434. foreach my $row (@month_stats) {
  1435. my $user_id = $auth_info{$row->{auth_id}}{user_id};
  1436. $auth_info{$row->{auth_id}}{month} = $row->{traf_all} // 0;
  1437. $user_stats{$user_id}{month} += $row->{traf_all} // 0;
  1438. }
  1439. # --- Блокировка по квотам для auth_id ---
  1440. foreach my $auth_id (keys %auth_info) {
  1441. next unless $auth_info{$auth_id}{day_limit} || $auth_info{$auth_id}{month_limit};
  1442. my $day_limit = ($auth_info{$auth_id}{day_limit} // 0) * $KB * $KB;
  1443. my $month_limit = ($auth_info{$auth_id}{month_limit} // 0) * $KB * $KB;
  1444. my $blocked_d = $auth_info{$auth_id}{day} > $day_limit;
  1445. my $blocked_m = $auth_info{$auth_id}{month} > $month_limit;
  1446. if ($blocked_d || $blocked_m) {
  1447. my $history_msg;
  1448. if ($blocked_d) {
  1449. $history_msg = sprintf "Day quota limit found for auth_id: %d - Current: %d Max: %d",
  1450. $auth_id, $auth_info{$auth_id}{day}, $day_limit;
  1451. }
  1452. if ($blocked_m) {
  1453. $history_msg = sprintf "Month quota limit found for auth_id: %d - Current: %d Max: %d",
  1454. $auth_id, $auth_info{$auth_id}{month}, $month_limit;
  1455. }
  1456. do_sql($db, "UPDATE user_auth SET blocked = 1, changed = 1 WHERE id = ?", $auth_id);
  1457. db_log_verbose($db, $history_msg);
  1458. }
  1459. }
  1460. # --- Блокировка по квотам для user_id ---
  1461. foreach my $user_id (keys %user_stats) {
  1462. next unless $user_stats{$user_id}{day_limit} || $user_stats{$user_id}{month_limit};
  1463. my $day_limit = ($user_stats{$user_id}{day_limit} // 0) * $KB * $KB;
  1464. my $month_limit = ($user_stats{$user_id}{month_limit} // 0) * $KB * $KB;
  1465. my $blocked_d = $user_stats{$user_id}{day} > $day_limit;
  1466. my $blocked_m = $user_stats{$user_id}{month} > $month_limit;
  1467. if ($blocked_d || $blocked_m) {
  1468. my $history_msg;
  1469. if ($blocked_d) {
  1470. $history_msg = sprintf "Day quota limit found for user_id: %d - Current: %d Max: %d",
  1471. $user_id, $user_stats{$user_id}{day}, $day_limit;
  1472. }
  1473. if ($blocked_m) {
  1474. $history_msg = sprintf "Month quota limit found for user_id: %d - Current: %d Max: %d",
  1475. $user_id, $user_stats{$user_id}{month}, $month_limit;
  1476. }
  1477. # Исправлено: user_list вместо User_user
  1478. do_sql($db, "UPDATE user_list SET blocked = 1 WHERE id = ?", $user_id);
  1479. do_sql($db, "UPDATE user_auth SET blocked = 1, changed = 1 WHERE user_id = ?", $user_id);
  1480. db_log_verbose($db, $history_msg);
  1481. }
  1482. }
  1483. Del_Variable($db, 'RECALC');
  1484. }
  1485. #--------------------------------------------------------------------------------
  1486. sub process_dhcp_request {
  1487. my ($db, $type, $mac, $ip, $hostname, $client_id, $circuit_id, $remote_id) = @_;
  1488. return unless $type && $type =~ /^(old|add|del)$/i;
  1489. my $client_hostname = '';
  1490. if ($hostname && $hostname ne 'undef' && $hostname !~ /UNDEFINED/i) {
  1491. $client_hostname = $hostname;
  1492. }
  1493. my $auth_network = $office_networks->match_string($ip);
  1494. if (!$auth_network) {
  1495. log_error("Unknown network in dhcp request! IP: $ip");
  1496. return;
  1497. }
  1498. $circuit_id //= '';
  1499. $client_id //= '';
  1500. $remote_id //= '';
  1501. my $timestamp = time();
  1502. my $ip_aton = StrToIp($ip);
  1503. return unless defined $ip_aton;
  1504. $mac = mac_splitted($mac);
  1505. my $dhcp_event_time = GetNowTime($timestamp);
  1506. my $dhcp_record = {
  1507. mac => $mac,
  1508. ip => $ip,
  1509. ip_aton => $ip_aton,
  1510. hostname => $client_hostname,
  1511. network => $auth_network,
  1512. type => $type,
  1513. hostname_utf8 => $client_hostname,
  1514. ts => $timestamp,
  1515. last_time => time(),
  1516. circuit_id => $circuit_id,
  1517. client_id => $client_id,
  1518. remote_id => $remote_id,
  1519. hotspot => is_hotspot($db, $ip),
  1520. };
  1521. # --- Ищем существующую запись ---
  1522. my $auth_record = get_record_sql($db,"SELECT * FROM user_auth WHERE ip = ? AND mac = ? AND deleted = 0 ORDER BY last_found DESC", $ip, $mac );
  1523. # Если запись не найдена и тип 'del' — выходим
  1524. if (!$auth_record && $type eq 'del') {
  1525. db_log_info($db, "Auth recrod for ip: $ip mac: $mac not found. Dhcp request type: $type");
  1526. return;
  1527. }
  1528. # Если запись не найдена и тип 'add'/'old' — создаём
  1529. if (!$auth_record && ($type eq 'add' || $type eq 'old')) {
  1530. my $res_id = resurrection_auth($db, $dhcp_record);
  1531. if (!$res_id) {
  1532. db_log_error($db, "Error creating an ip address record for ip=$ip and mac=$mac!");
  1533. return;
  1534. }
  1535. $auth_record = get_record_sql($db, "SELECT * FROM user_auth WHERE id = ?", $res_id);
  1536. db_log_info($db, "Check for new auth. Found id: $res_id", $res_id);
  1537. }
  1538. if (!$auth_record || !$auth_record->{id}) {
  1539. db_log_error($db, "Record not found/created for ip: $ip mac: $mac not found. Dhcp request type: $type!");
  1540. return;
  1541. }
  1542. my $auth_id = $auth_record->{id};
  1543. my $auth_ou_id = $auth_record->{ou_id};
  1544. $dhcp_record->{auth_id} = $auth_id;
  1545. $dhcp_record->{auth_ou_id} = $auth_ou_id;
  1546. update_dns_record_by_dhcp($db, $dhcp_record, $auth_record);
  1547. # --- Обработка ADD ---
  1548. if ($type eq 'add' && $dhcp_record->{hostname_utf8}) {
  1549. my $auth_rec = {
  1550. dhcp_hostname => $dhcp_record->{hostname_utf8},
  1551. dhcp_time => $dhcp_event_time,
  1552. arp_found => $dhcp_event_time,
  1553. created_by => 'dhcp',
  1554. };
  1555. db_log_verbose($db, "Add lease by dhcp event for dynamic clients id: $auth_id ip: $ip", $auth_id);
  1556. update_record($db, 'user_auth', $auth_rec, 'id = ?', $auth_id);
  1557. }
  1558. # --- Обработка OLD ---
  1559. if ($type eq 'old') {
  1560. my $auth_rec = {
  1561. dhcp_action => $type,
  1562. dhcp_time => $dhcp_event_time,
  1563. created_by => 'dhcp',
  1564. arp_found => $dhcp_event_time,
  1565. };
  1566. db_log_verbose($db, "Update lease by dhcp event for dynamic clients id: $auth_id ip: $ip", $auth_id);
  1567. update_record($db, 'user_auth', $auth_rec, 'id = ?', $auth_id);
  1568. }
  1569. # --- Обработка DEL ---
  1570. if ($type eq 'del' && $auth_id) {
  1571. if ($auth_record->{dhcp_time} =~ /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/) {
  1572. my $d_time = mktime($6, $5, $4, $3, $2 - 1, $1 - 1900);
  1573. if (time() - $d_time > 60 && (is_dynamic_ou($db, $auth_ou_id) || is_default_ou($db, $auth_ou_id))) {
  1574. db_log_info($db, "Remove user ip record by dhcp release event for dynamic clients id: $auth_id ip: $ip", $auth_id);
  1575. my $auth_rec = {
  1576. dhcp_action => $type,
  1577. dhcp_time => $dhcp_event_time,
  1578. };
  1579. update_record($db, 'user_auth', $auth_rec, 'id = ?', $auth_id);
  1580. # Удаляем запись, если она из динамического или дефолтного пула
  1581. if (is_default_ou($db, $auth_ou_id) || (is_dynamic_ou($db, $auth_ou_id) && $auth_record->{dynamic})) {
  1582. delete_user_auth($db, $auth_id);
  1583. # Проверяем, остались ли другие записи у пользователя
  1584. my $u_count = get_record_sql($db,
  1585. "SELECT COUNT(*) AS cnt FROM user_auth WHERE deleted = 0 AND user_id = ?",
  1586. $auth_record->{user_id}
  1587. );
  1588. if ($u_count && $u_count->{cnt} == 0) {
  1589. delete_user($db, $auth_record->{user_id});
  1590. }
  1591. }
  1592. }
  1593. }
  1594. }
  1595. # --- Пропуск логирования для hotspot или ignore_update_dhcp_event ---
  1596. if ($dhcp_record->{hotspot} && $ignore_hotspot_dhcp_log) {
  1597. return $dhcp_record;
  1598. }
  1599. if ($ignore_update_dhcp_event && $type eq 'old') {
  1600. return $dhcp_record;
  1601. }
  1602. # --- Логируем событие ---
  1603. my $dhcp_log = {
  1604. auth_id => $auth_id // 0,
  1605. ip => $ip,
  1606. ip_int => $ip_aton,
  1607. mac => $mac,
  1608. action => $type,
  1609. dhcp_hostname => $client_hostname,
  1610. ts => $dhcp_event_time,
  1611. circuit_id => $circuit_id,
  1612. client_id => $client_id,
  1613. remote_id => $remote_id,
  1614. };
  1615. insert_record($db, 'dhcp_log', $dhcp_log);
  1616. return $dhcp_record;
  1617. }
  1618. 1;
  1619. }