common.pm 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943
  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 eyelib::logconfig;
  20. use DateTime;
  21. use DateTime::Format::Strptime;
  22. use POSIX qw(mktime ctime strftime);
  23. use File::Temp qw(tempfile);
  24. use DBI;
  25. our @ISA = qw(Exporter);
  26. our @EXPORT = qw(
  27. apply_device_lock
  28. create_dns_cname
  29. create_dns_hostname
  30. create_dns_ptr
  31. delete_device
  32. delete_dns_cname
  33. delete_dns_hostname
  34. delete_dns_ptr
  35. delete_user
  36. delete_user_auth
  37. find_mac_in_subnet
  38. get_default_ou
  39. get_device_by_ip
  40. get_dns_name
  41. get_dynamic_ou
  42. get_ip_subnet
  43. get_new_user_id
  44. GetNowTime
  45. get_subnets_ref
  46. GetTimeStrByUnixTime
  47. GetUnixTimeByStr
  48. is_ad_computer
  49. is_default_ou
  50. is_dynamic_ou
  51. new_auth
  52. new_user
  53. process_dhcp_request
  54. recalc_quotes
  55. record_to_txt
  56. resurrection_auth
  57. set_changed
  58. set_lock_discovery
  59. unbind_ports
  60. unblock_user
  61. unset_lock_discovery
  62. update_dns_record
  63. update_dns_record_by_dhcp
  64. get_creation_method
  65. );
  66. BEGIN
  67. {
  68. #---------------------------------------------------------------------------------------------------------------
  69. sub unbind_ports {
  70. my ($db, $device_id) = @_;
  71. return unless $db && defined $device_id && $device_id =~ /^\d+$/;
  72. # Получаем все порты устройства
  73. my @target = get_records_sql($db,
  74. "SELECT target_port_id, id FROM device_ports WHERE device_id = ?",
  75. $device_id
  76. );
  77. foreach my $row (@target) {
  78. # Обнуляем ссылки НА этот порт (кто ссылается на него)
  79. do_sql($db, "UPDATE device_ports SET target_port_id = 0 WHERE target_port_id = ?", $row->{id});
  80. # Обнуляем ссылку С этого порта (куда он ссылался)
  81. do_sql($db, "UPDATE device_ports SET target_port_id = 0 WHERE id = ?", $row->{id});
  82. }
  83. }
  84. #---------------------------------------------------------------------------------------------------------------
  85. sub get_dns_name {
  86. my ($db, $id) = @_;
  87. return unless $db && defined $id;
  88. return unless $id =~ /^\d+$/ && $id > 0;
  89. my $auth_record = get_record_sql(
  90. $db,
  91. "SELECT dns_name FROM user_auth WHERE deleted = 0 AND id = ?",
  92. $id
  93. );
  94. return $auth_record && $auth_record->{dns_name}
  95. ? $auth_record->{dns_name}
  96. : undef;
  97. }
  98. #---------------------------------------------------------------------------------------------------------------
  99. sub record_to_txt {
  100. my ($db, $table, $id) = @_;
  101. return unless $db && defined $table && defined $id;
  102. # Валидация имени таблицы: только буквы, цифры, подчёркивания
  103. return unless $table =~ /^[a-zA-Z_][a-zA-Z0-9_]*$/;
  104. # Валидация ID: должно быть положительное целое число
  105. return unless $id =~ /^\d+$/ && $id > 0;
  106. my $record = get_record_sql(
  107. $db,
  108. "SELECT * FROM $table WHERE id = ?",
  109. $id
  110. );
  111. return hash_to_text($record);
  112. }
  113. #---------------------------------------------------------------------------------------------------------------
  114. sub delete_user_auth {
  115. my ($db, $id) = @_;
  116. return 0 unless $db && defined $id;
  117. return 0 unless $id =~ /^\d+$/ && $id > 0;
  118. my $record = get_record_sql($db, "SELECT * FROM user_auth WHERE id = ?", $id);
  119. return 0 unless $record;
  120. my @aliases = get_records_sql($db, "SELECT * FROM user_auth_alias WHERE auth_id = ?", $id);
  121. foreach my $alias (@aliases) {
  122. my $alias_id = $alias->{id};
  123. next unless defined $alias_id && $alias_id =~ /^\d+$/;
  124. delete_record($db, 'user_auth_alias', 'id = ?', $alias_id);
  125. }
  126. # --- Удаляем соединения ---
  127. do_sql($db, "DELETE FROM connections WHERE auth_id = ?", $id);
  128. # --- Удаляем основную запись ---
  129. my $changes = delete_record($db, "user_auth", "id = ?", $id);
  130. return $changes;
  131. }
  132. #---------------------------------------------------------------------------------------------------------------
  133. sub unblock_user {
  134. my ($db, $user_id) = @_;
  135. return 0 unless $db && defined $user_id;
  136. return 0 unless $user_id =~ /^\d+$/ && $user_id > 0;
  137. my $user_record = get_record_sql($db, "SELECT * FROM user_list WHERE id = ?", $user_id);
  138. return 0 unless $user_record;
  139. my $user_ident = 'id:' . ($user_record->{id} // '') . ' ' . ($user_record->{login} // '');
  140. if ($user_record->{description}) {
  141. $user_ident .= '[' . $user_record->{description} . ']';
  142. }
  143. my $msg = "Amnistuyemo blocked by traffic user $user_ident\nInternet access for the user's IP address has been restored:\n";
  144. my $send_alert = 0;
  145. my $any_updated = 0;
  146. my @user_auth = get_records_sql($db, "SELECT * FROM user_auth WHERE deleted = 0 AND user_id = ?", $user_id);
  147. foreach my $record (@user_auth) {
  148. next unless $record->{id} && $record->{id} =~ /^\d+$/;
  149. $send_alert ||= isNotifyUpdate(get_notify_subnet($db, $record->{ip}));
  150. my $auth_ident = $record->{ip} // '';
  151. if ($record->{dns_name}) {
  152. $auth_ident .= '[' . $record->{dns_name} . ']';
  153. }
  154. if ($record->{description}) {
  155. $auth_ident .= ' :: ' . $record->{description};
  156. }
  157. my $new = {
  158. blocked => 0,
  159. changed => 1,
  160. };
  161. if (update_record($db, 'user_auth', $new, 'id = ?', $record->{id})) {
  162. $msg .= "\n" . $auth_ident;
  163. $any_updated = 1;
  164. }
  165. }
  166. my $user_update = { blocked => 0 };
  167. my $ret_id = update_record($db, 'user_list', $user_update, 'id = ?', $user_id);
  168. if ($ret_id) {
  169. db_log_info($db, $msg);
  170. sendEmail("WARN! " . get_first_line($msg), $msg, 1) if $send_alert;
  171. }
  172. return $ret_id;
  173. }
  174. #---------------------------------------------------------------------------------------------------------------
  175. sub delete_user {
  176. my ($db, $id) = @_;
  177. return 0 unless $db && defined $id;
  178. return 0 unless $id =~ /^\d+$/ && $id > 0;
  179. my $changes = delete_record($db, "user_list", "permanent = 0 AND id = ?", $id);
  180. return 0 unless $changes;
  181. my @user_auth_records = get_records_sql($db, "SELECT id FROM user_auth WHERE user_id = ?", $id);
  182. foreach my $row (@user_auth_records) {
  183. next unless defined $row->{id} && $row->{id} =~ /^\d+$/;
  184. delete_user_auth($db, $row->{id});
  185. }
  186. my $device = get_record_sql($db, "SELECT id FROM devices WHERE user_id = ?", $id);
  187. if ($device && defined $device->{id} && $device->{id} =~ /^\d+$/) {
  188. delete_device($db, $device->{id});
  189. }
  190. do_sql($db, "DELETE FROM auth_rules WHERE user_id = ?", $id);
  191. return $changes;
  192. }
  193. #---------------------------------------------------------------------------------------------------------------
  194. sub delete_device {
  195. my ($db, $id) = @_;
  196. return 0 unless $db && defined $id;
  197. return 0 unless $id =~ /^\d+$/ && $id > 0;
  198. my $changes = delete_record($db, "devices", "id = ?", $id);
  199. return 0 unless $changes;
  200. # Отвязываем порты
  201. unbind_ports($db, $id);
  202. do_sql($db, "DELETE FROM connections WHERE device_id = ?", $id);
  203. do_sql($db, "DELETE FROM device_l3_interfaces WHERE device_id = ?", $id);
  204. do_sql($db, "DELETE FROM device_ports WHERE device_id = ?", $id);
  205. do_sql($db, "DELETE FROM device_filter_instances WHERE device_id = ?", $id);
  206. do_sql($db, "DELETE FROM gateway_subnets WHERE device_id = ?", $id);
  207. return $changes;
  208. }
  209. #---------------------------------------------------------------------------------------------------------------
  210. sub get_new_user_id {
  211. my ($db, $ip, $mac, $hostname) = @_;
  212. return unless $db;
  213. my $result = {
  214. ip => $ip,
  215. mac => defined $mac ? mac_splitted(mac_simplify($mac)) : undef,
  216. dhcp_hostname => $hostname,
  217. ou_id => undef,
  218. user_id => undef,
  219. };
  220. # --- Hotspot ---
  221. my @hotspot_rules = get_records_sql($db,
  222. "SELECT * FROM subnets WHERE hotspot = 1 AND LENGTH(subnet) > 0"
  223. );
  224. if (@hotspot_rules) {
  225. my $hotspot_pat = Net::Patricia->new;
  226. foreach my $row (@hotspot_rules) {
  227. next unless defined $row->{subnet};
  228. eval { $hotspot_pat->add_string($row->{subnet}, $default_hotspot_ou_id); 1 } or next;
  229. }
  230. if (defined $ip) {
  231. my $ou_id = $hotspot_pat->match_string($ip);
  232. if ($ou_id) { $result->{ou_id} = $ou_id; return $result; }
  233. }
  234. }
  235. # --- Поиск user_id по IP/MAC/hostname ---
  236. if (defined $ip && $ip) {
  237. my @rules = get_records_sql($db,
  238. "SELECT rule, user_id FROM auth_rules WHERE rule_type = 1 AND LENGTH(rule) > 0 AND user_id IS NOT NULL"
  239. );
  240. my $pat = Net::Patricia->new;
  241. foreach my $r (@rules) {
  242. next unless defined $r->{rule};
  243. eval { $pat->add_string($r->{rule}, $r->{user_id}); 1 } or next;
  244. }
  245. if (my $user_id = $pat->match_string($ip)) {
  246. $result->{user_id} = $user_id;
  247. return $result;
  248. }
  249. }
  250. if (defined $mac && $mac) {
  251. my @rules = get_records_sql($db,
  252. "SELECT rule, user_id FROM auth_rules WHERE rule_type = 2 AND LENGTH(rule) > 0 AND user_id IS NOT NULL"
  253. );
  254. foreach my $r (@rules) {
  255. next unless defined $r->{rule};
  256. my $rule_clean = mac_simplify($r->{rule});
  257. # Защита от битых регулярок
  258. eval {
  259. if ($mac =~ /\Q$rule_clean\E/i) { # \Q...\E — экранируем спецсимволы!
  260. $result->{user_id} = $r->{user_id};
  261. return $result;
  262. }
  263. 1;
  264. } or do {
  265. log_debug("Invalid MAC rule: '$r->{rule}'");
  266. next;
  267. };
  268. }
  269. }
  270. if (defined $hostname && $hostname) {
  271. my @rules = get_records_sql($db,
  272. "SELECT rule, user_id FROM auth_rules WHERE rule_type = 3 AND LENGTH(rule) > 0 AND user_id IS NOT NULL"
  273. );
  274. foreach my $r (@rules) {
  275. next unless defined $r->{rule};
  276. eval {
  277. if ($hostname =~ /$r->{rule}/i) {
  278. $result->{user_id} = $r->{user_id};
  279. return $result;
  280. }
  281. 1;
  282. } or do {
  283. log_debug("Invalid hostname rule: '$r->{rule}'");
  284. next;
  285. };
  286. }
  287. }
  288. # --- Поиск ou_id по IP/MAC/hostname ---
  289. if (defined $ip && $ip) {
  290. my @rules = get_records_sql($db,
  291. "SELECT rule, ou_id FROM auth_rules WHERE rule_type = 1 AND LENGTH(rule) > 0 AND ou_id IS NOT NULL"
  292. );
  293. my $pat = Net::Patricia->new;
  294. foreach my $r (@rules) {
  295. next unless defined $r->{rule};
  296. eval { $pat->add_string($r->{rule}, $r->{ou_id}); 1 } or next;
  297. }
  298. if (my $ou_id = $pat->match_string($ip)) {
  299. $result->{ou_id} = $ou_id;
  300. return $result;
  301. }
  302. }
  303. if (defined $mac && $mac) {
  304. my @rules = get_records_sql($db,
  305. "SELECT rule, ou_id FROM auth_rules WHERE rule_type = 2 AND LENGTH(rule) > 0 AND ou_id IS NOT NULL"
  306. );
  307. foreach my $r (@rules) {
  308. next unless defined $r->{rule};
  309. my $rule_clean = mac_simplify($r->{rule});
  310. eval {
  311. if ($mac =~ /\Q$rule_clean\E/i) {
  312. $result->{ou_id} = $r->{ou_id};
  313. return $result;
  314. }
  315. 1;
  316. } or do {
  317. log_debug("Invalid MAC rule: '$r->{rule}'");
  318. next;
  319. };
  320. }
  321. }
  322. if (defined $hostname && $hostname) {
  323. my @rules = get_records_sql($db,
  324. "SELECT rule, ou_id FROM auth_rules WHERE rule_type = 3 AND LENGTH(rule) > 0 AND ou_id IS NOT NULL"
  325. );
  326. foreach my $r (@rules) {
  327. next unless defined $r->{rule};
  328. eval {
  329. if ($hostname =~ /$r->{rule}/i) {
  330. $result->{ou_id} = $r->{ou_id};
  331. return $result;
  332. }
  333. 1;
  334. } or do {
  335. log_debug("Invalid hostname rule: '$r->{rule}'");
  336. next;
  337. };
  338. }
  339. }
  340. $result->{ou_id} //= $default_user_ou_id;
  341. return $result;
  342. }
  343. #---------------------------------------------------------------------------------------------------------------
  344. sub set_changed {
  345. my ($db, $id) = @_;
  346. return unless $db && defined $id;
  347. return unless $id =~ /^\d+$/;
  348. my $update_record = { changed => 1 };
  349. update_record($db, 'user_auth', $update_record, 'id = ?', $id);
  350. }
  351. #---------------------------------------------------------------------------------------------------------------
  352. sub update_dns_record {
  353. my ($hdb, $auth_id) = @_;
  354. # === 1. Базовые проверки ===
  355. return unless $config_ref{enable_dns_updates};
  356. return unless defined $auth_id;
  357. # Валидация: auth_id должен быть положительным целым числом
  358. return unless $auth_id =~ /^\d+$/ && $auth_id > 0;
  359. # Переподключение к БД при необходимости
  360. if (!$hdb || !$hdb->ping) {
  361. $hdb = init_db();
  362. }
  363. return unless $hdb;
  364. # === 2. Получение настроек DNS ===
  365. my $ad_zone = get_option($hdb, 33); # DNS-зона (например, 'example.com')
  366. my $ad_dns = get_option($hdb, 3); # DNS-сервер
  367. my $enable_ad_dns_update = ($ad_zone && $ad_dns && $config_ref{enable_dns_updates});
  368. log_debug("Auth id: $auth_id");
  369. log_debug("enable_ad_dns_update: " . ($enable_ad_dns_update ? '1' : '0'));
  370. log_debug("DNS update flags - zone: $ad_zone, dns: $ad_dns, enable_ad_dns_update: " . ($enable_ad_dns_update ? '1' : '0'));
  371. # === 3. Получение задач из очереди DNS ===
  372. # Используем != '' вместо > '' для совместимости
  373. my @dns_queue = get_records_sql(
  374. $hdb,
  375. "SELECT * FROM dns_queue
  376. WHERE auth_id = ?
  377. AND value != ''
  378. AND value NOT LIKE '%.'
  379. ORDER BY id ASC",
  380. $auth_id
  381. );
  382. return unless @dns_queue;
  383. # === 4. Обработка каждой DNS-команды ===
  384. foreach my $dns_cmd (@dns_queue) {
  385. my $fqdn = '';
  386. my $fqdn_ip = '';
  387. my $fqdn_parent = '';
  388. my $static_exists = 0;
  389. my $static_ref = '';
  390. my $static_ok = 0;
  391. eval {
  392. # === Обработка CNAME записей ===
  393. if (lc($dns_cmd->{name_type}) eq 'cname') {
  394. # Пропускаем домены с завершающей точкой (уже FQDN)
  395. if ($dns_cmd->{name} =~ /\.$/ || $dns_cmd->{value} =~ /\.$/) {
  396. next;
  397. }
  398. $fqdn = lc($dns_cmd->{name});
  399. $fqdn =~ s/\.$ad_zone$//i; # Убираем зону из имени
  400. $fqdn .= ".$ad_zone"; # Добавляем зону для FQDN
  401. if ($dns_cmd->{value}) {
  402. $fqdn_parent = lc($dns_cmd->{value});
  403. $fqdn_parent =~ s/\.$ad_zone$//i;
  404. $fqdn_parent .= ".$ad_zone";
  405. }
  406. # Удаление CNAME
  407. if ($dns_cmd->{operation_type} eq 'del') {
  408. delete_dns_cname($fqdn_parent, $fqdn, $ad_zone, $ad_dns, $hdb);
  409. }
  410. # Создание CNAME
  411. elsif ($dns_cmd->{operation_type} eq 'add') {
  412. create_dns_cname($fqdn_parent, $fqdn, $ad_zone, $ad_dns, $hdb);
  413. }
  414. }
  415. # === Обработка A-записей ===
  416. elsif (lc($dns_cmd->{name_type}) eq 'a') {
  417. # Пропускаем уже FQDN-имена
  418. if ($dns_cmd->{name} =~ /\.$/ || $dns_cmd->{value} =~ /\.$/) {
  419. next;
  420. }
  421. $fqdn = lc($dns_cmd->{name});
  422. $fqdn =~ s/\.$ad_zone$//i;
  423. $fqdn .= ".$ad_zone";
  424. # Проверка IP-адреса
  425. if (!$dns_cmd->{value}) {
  426. next;
  427. }
  428. $fqdn_ip = lc($dns_cmd->{value});
  429. # Проверка: разрешено ли обновление DNS для этой сети?
  430. my $maybe_update_dns = ($enable_ad_dns_update && $office_networks->match_string($fqdn_ip));
  431. if (!$maybe_update_dns) {
  432. db_log_info($hdb, "FOUND Auth_id: $auth_id. DNS update disabled.");
  433. next;
  434. }
  435. # Получение алиасов для текущего auth_id
  436. my @aliases = get_records_sql(
  437. $hdb,
  438. "SELECT alias, description FROM user_auth_alias WHERE auth_id = ?",
  439. $auth_id
  440. );
  441. # Удаление A/PTR записей
  442. if ($dns_cmd->{operation_type} eq 'del') {
  443. # Удаляем алиасы (CNAME и A-записи)
  444. for my $alias (@aliases) {
  445. if ($alias->{alias} && $alias->{alias} ne '') {
  446. delete_dns_cname($fqdn, $alias->{alias}, $ad_zone, $ad_dns, $hdb);
  447. delete_dns_hostname($fqdn, $alias->{alias}, $ad_zone, $ad_dns, $hdb);
  448. }
  449. }
  450. # Удаляем основные записи
  451. delete_dns_hostname($fqdn, $fqdn_ip, $ad_zone, $ad_dns, $hdb);
  452. delete_dns_ptr($fqdn, $fqdn_ip, $ad_zone, $ad_dns, $hdb);
  453. }
  454. # Создание A/PTR записей
  455. elsif ($dns_cmd->{operation_type} eq 'add') {
  456. # Проверяем существующие DNS-записи
  457. my @dns_record = ResolveNames($fqdn, $dns_server);
  458. $static_exists = (@dns_record > 0);
  459. if ($static_exists) {
  460. $static_ref = join(' ', @dns_record);
  461. # Проверяем, совпадает ли IP
  462. for my $dns_a (@dns_record) {
  463. if ($dns_a eq $fqdn_ip) {
  464. $static_ok = 1;
  465. last;
  466. }
  467. }
  468. db_log_debug($hdb, "Dns record for static record $fqdn: $static_ref");
  469. }
  470. # Пропускаем, если запись уже корректна
  471. if ($static_ok) {
  472. db_log_debug($hdb, "Static record for $fqdn [$fqdn_ip] correct.");
  473. next;
  474. }
  475. # Создаём основные записи
  476. create_dns_hostname($fqdn, $fqdn_ip, $ad_zone, $ad_dns, $hdb);
  477. create_dns_ptr($fqdn, $fqdn_ip, $ad_zone, $ad_dns, $hdb);
  478. # Создаём алиасы
  479. for my $alias (@aliases) {
  480. if ($alias->{alias} && $alias->{alias} ne '') {
  481. create_dns_cname($fqdn, $alias->{alias}, $ad_zone, $ad_dns, $hdb);
  482. }
  483. }
  484. }
  485. }
  486. # === Обработка PTR записей ===
  487. elsif (lc($dns_cmd->{name_type}) eq 'ptr') {
  488. $fqdn = lc($dns_cmd->{name});
  489. $fqdn =~ s/\.$ad_zone$//i;
  490. $fqdn .= ".$ad_zone";
  491. if (!$dns_cmd->{value}) {
  492. next;
  493. }
  494. $fqdn_ip = lc($dns_cmd->{value});
  495. # Пропускаем FQDN
  496. if ($fqdn =~ /\.$/) {
  497. next;
  498. }
  499. # Проверка разрешения обновления
  500. my $maybe_update_dns = ($enable_ad_dns_update && $office_networks->match_string($fqdn_ip));
  501. if (!$maybe_update_dns) {
  502. db_log_info($hdb, "FOUND Auth_id: $auth_id. DNS update disabled.");
  503. next;
  504. }
  505. # Удаление PTR
  506. if ($dns_cmd->{operation_type} eq 'del') {
  507. delete_dns_ptr($fqdn, $fqdn_ip, $ad_zone, $ad_dns, $hdb);
  508. }
  509. # Создание PTR
  510. elsif ($dns_cmd->{operation_type} eq 'add') {
  511. create_dns_ptr($fqdn, $fqdn_ip, $ad_zone, $ad_dns, $hdb);
  512. }
  513. }
  514. };
  515. if ($@) {
  516. log_error("Error processing DNS command for auth_id=$auth_id: $@");
  517. }
  518. }
  519. }
  520. #---------------------------------------------------------------------------------------------------------------
  521. sub is_ad_computer {
  522. my ($hdb, $computer_name) = @_;
  523. return 0 unless $hdb;
  524. return 0 if !$computer_name || $computer_name =~ /UNDEFINED/i;
  525. my $ad_check = get_option($hdb, 73);
  526. return 1 unless $ad_check;
  527. my $ad_zone = get_option($hdb, 33);
  528. # Проверка домена (если указан)
  529. if (defined $ad_zone && $ad_zone ne '' && $computer_name =~ /\./) {
  530. if ($computer_name !~ /\Q$ad_zone\E$/i) {
  531. db_log_warning($hdb, "The domain of the computer $computer_name does not match the domain of the organization $ad_zone. Skip update.");
  532. return 0;
  533. }
  534. }
  535. # Извлекаем NetBIOS-имя (до первой точки)
  536. my $netbios_name = $computer_name;
  537. $netbios_name = $1 if $computer_name =~ /^([^\.]+)/;
  538. # Валидация NetBIOS-имени
  539. if (!$netbios_name || $netbios_name !~ /^[a-zA-Z0-9][a-zA-Z0-9_\-\$]{0,14}$/) {
  540. db_log_info($hdb, "Invalid computer name format: '$computer_name'");
  541. return 0;
  542. }
  543. # Проверяем кэш
  544. my $name_in_cache = get_record_sql($hdb, "SELECT * FROM ad_comp_cache WHERE name = ?", $netbios_name);
  545. return 1 if $name_in_cache;
  546. # Ищем в AD
  547. my $ad_computer_name = $netbios_name . '$';
  548. my $safe_name = quotemeta($ad_computer_name);
  549. my %name_found = do_exec_ref("/usr/bin/getent passwd $safe_name");
  550. if (!$name_found{output} || $name_found{status} ne 0) {
  551. db_log_info($hdb, "The computer " . uc($ad_computer_name) . " was not found in the domain $ad_zone. Skip update.");
  552. return 0;
  553. }
  554. # Кэшируем
  555. do_sql($hdb, "INSERT INTO ad_comp_cache (name) VALUES (?) ON DUPLICATE KEY UPDATE name = ?",
  556. $netbios_name, $netbios_name);
  557. return 1;
  558. }
  559. #---------------------------------------------------------------------------------------------------------------
  560. sub escape_like {
  561. my ($str) = @_;
  562. return '' unless defined $str;
  563. $str =~ s/([%_\\])/\\$1/g;
  564. return $str;
  565. }
  566. #---------------------------------------------------------------------------------------------------------------
  567. sub update_dns_record_by_dhcp {
  568. my $hdb = shift;
  569. my $dhcp_record = shift;
  570. my $auth_record = shift;
  571. return if (!$config_ref{enable_dns_updates});
  572. my $ad_zone = get_option($hdb,33);
  573. my $ad_dns = get_option($hdb,3);
  574. $update_hostname_from_dhcp = get_option($hdb,46) || 0;
  575. my $subnets_dhcp = get_subnets_ref($hdb);
  576. my $enable_ad_dns_update = ($ad_zone and $ad_dns and $update_hostname_from_dhcp);
  577. log_debug("Dhcp record: ".Dumper($dhcp_record));
  578. log_debug("Subnets: ".Dumper($subnets_dhcp->{$dhcp_record->{network}->{subnet}}));
  579. log_debug("enable_ad_dns_update: ".$enable_ad_dns_update);
  580. log_debug("DNS update flags - zone: ".$ad_zone.",dns: ".$ad_dns.", update_hostname_from_dhcp: ".$update_hostname_from_dhcp.", enable_ad_dns_update: " .
  581. $enable_ad_dns_update. ", network dns-update enabled: ".$subnets_dhcp->{$dhcp_record->{network}->{subnet}}->{dhcp_update_hostname});
  582. my $maybe_update_dns=($enable_ad_dns_update and $subnets_dhcp->{$dhcp_record->{network}->{subnet}}->{dhcp_update_hostname} and
  583. (is_ad_computer($hdb,$dhcp_record->{hostname_utf8}) and ($dhcp_record->{type}=~/add/i or $dhcp_record->{type}=~/old/i)));
  584. if (!$maybe_update_dns) {
  585. db_log_debug($hdb,"FOUND Auth_id: $auth_record->{id}. DNS update don't needed for this host/subnet/domain.");
  586. return 0;
  587. }
  588. log_debug("DNS update enabled.");
  589. #update dns block
  590. my $fqdn_static;
  591. if ($auth_record->{dns_name}) {
  592. $fqdn_static=lc($auth_record->{dns_name});
  593. if ($fqdn_static!~/\.$ad_zone$/i) {
  594. $fqdn_static=~s/\.$//;
  595. $fqdn_static=lc($fqdn_static.'.'.$ad_zone);
  596. }
  597. }
  598. my $fqdn=lc(trim($dhcp_record->{hostname_utf8}));
  599. if ($fqdn!~/\.$ad_zone$/i) {
  600. $fqdn=~s/\.$//;
  601. $fqdn=lc($fqdn.'.'.$ad_zone);
  602. }
  603. db_log_debug($hdb,"DNS :: FOUND Auth_id: $auth_record->{id} dns_name from systemd: $fqdn_static dhcp_hostname from request: $fqdn");
  604. #check exists static dns name
  605. my $static_exists = 0;
  606. my $dynamic_exists = 0;
  607. my $static_ok = 0;
  608. my $dynamic_ok = 0;
  609. my $static_ref;
  610. my $dynamic_ref;
  611. if ($fqdn_static ne '') {
  612. my @dns_record=ResolveNames($fqdn_static,$dns_server);
  613. $static_exists = (scalar @dns_record>0);
  614. if ($static_exists) {
  615. $static_ref = join(' ',@dns_record);
  616. foreach my $dns_a (@dns_record) {
  617. if ($dns_a=~/^$dhcp_record->{ip}$/) { $static_ok = $dns_a; }
  618. }
  619. }
  620. } else { $static_ok = 1; }
  621. if ($fqdn ne '') {
  622. my @dns_record=ResolveNames($fqdn,$dns_server);
  623. $dynamic_exists = (scalar @dns_record>0);
  624. if ($dynamic_exists) {
  625. $dynamic_ref = join(' ',@dns_record);
  626. foreach my $dns_a (@dns_record) {
  627. if ($dns_a=~/^$dhcp_record->{ip}$/) { $dynamic_ok = $dns_a; }
  628. }
  629. }
  630. }
  631. db_log_debug($hdb,"Dns record for static record $fqdn_static: $static_ok :: for dhcp-hostname $fqdn: $dynamic_ok");
  632. if ($fqdn_static ne '') {
  633. if (!$static_ok) {
  634. db_log_info($hdb,"DNS :: Static record mismatch! Expected $fqdn_static => $dhcp_record->{ip}, recivied: $static_ref");
  635. if (!$static_exists) {
  636. db_log_info($hdb,"DNS :: 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,"DNS :: Dynamic record for $fqdn [$dynamic_ok] correct. No changes required."); }
  644. if ($fqdn ne '' and !$dynamic_ok) {
  645. log_error("DNS :: 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,"DNS :: 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,"DNS :: 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,"DNS :: 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,"DNS :: 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. $auth_ident .= " :: client-id = $client_id" if $client_id;
  1109. my $ip_aton = $ip_record->{ip_aton};
  1110. return 0 unless defined $ip_aton;
  1111. my $timestamp = GetNowTime();
  1112. # --- Ищем существующую запись по IP+MAC ---
  1113. my $record = get_record_sql($db,
  1114. "SELECT * FROM user_auth WHERE deleted = 0 AND ip_int = ? AND mac = ?",
  1115. $ip_aton, $mac
  1116. );
  1117. my $new_record = {
  1118. last_found => $timestamp,
  1119. arp_found => $timestamp,
  1120. };
  1121. if ($client_id) { $new_record->{client_id} = $client_id; }
  1122. # Если нашли — обновляем
  1123. if ($record && $record->{user_id}) {
  1124. if ($action =~ /^(add|old|del)$/i) {
  1125. $new_record->{dhcp_action} = $action;
  1126. $new_record->{created_by} = 'dhcp';
  1127. $new_record->{dhcp_time} = $timestamp;
  1128. $new_record->{dhcp_hostname} = $hostname if $hostname;
  1129. } else {
  1130. $new_record->{created_by} = $action // get_creation_method();
  1131. }
  1132. update_record($db, 'user_auth', $new_record, 'id = ?', $record->{id});
  1133. return $record->{id};
  1134. }
  1135. my $send_alert_create = isNotifyCreate(get_notify_subnet($db, $ip));
  1136. # --- Проверка статической подсети ---
  1137. my $user_subnet = $office_networks->match_string($ip);
  1138. if ($user_subnet && $user_subnet->{static}) {
  1139. my $msg = "Found new unknown ip+mac in static subnet! Abort create record for this: $ip [$mac]";
  1140. db_log_warning($db, $msg);
  1141. sendEmail("WARN! " . get_first_line($msg), $msg, 1) if $send_alert_create;
  1142. return 0;
  1143. }
  1144. my $send_alert_update = isNotifyUpdate(get_notify_subnet($db, $ip));
  1145. # --- Ищем другие записи с этим MAC в той же подсети ---
  1146. my $mac_exists = find_mac_in_subnet($db, $ip, $mac);
  1147. # --- Ищем запись с тем же IP (но другим MAC) ---
  1148. my $ip_record_same = get_record_sql($db,
  1149. "SELECT * FROM user_auth WHERE ip_int = ? AND deleted = 0",
  1150. $ip_aton
  1151. );
  1152. if ($ip_record_same && $ip_record_same->{id}) {
  1153. if (!$ip_record_same->{mac}) {
  1154. # Обновляем запись без MAC
  1155. $new_record->{mac} = $mac;
  1156. if ($mac_exists && $mac_exists->{count}>=1) {
  1157. # выключаем dhcp если есть записи в этой же подсети с другим ip и этим маком
  1158. $new_record->{dhcp} = 0;
  1159. }
  1160. if ($action =~ /^(add|old|del)$/i) {
  1161. $new_record->{dhcp_action} = $action;
  1162. $new_record->{dhcp_time} = $timestamp;
  1163. $new_record->{created_by} = 'dhcp';
  1164. $new_record->{dhcp_hostname} = $hostname if $hostname;
  1165. } else {
  1166. $new_record->{created_by} = $action // get_creation_method();
  1167. }
  1168. update_record($db, 'user_auth', $new_record, 'id = ?', $ip_record_same->{id});
  1169. return $ip_record_same->{id};
  1170. } elsif ($ip_record_same->{mac}) {
  1171. # MAC изменился — удаляем старую запись
  1172. if (!$ip_record->{hotspot}) {
  1173. 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}";
  1174. db_log_warning($db, $msg, $ip_record_same->{id});
  1175. sendEmail("WARN! " . get_first_line($msg), $msg, 1) if $send_alert_update;
  1176. }
  1177. delete_user_auth($db, $ip_record_same->{id});
  1178. }
  1179. }
  1180. # --- Создаём нового пользователя, если нужно ---
  1181. my $new_user_info = get_new_user_id($db, $ip, $mac, $hostname);
  1182. my $new_user_id = $new_user_info->{user_id} // new_user($db, $new_user_info);
  1183. # --- Удаляем дубли с dynamic=1 ---
  1184. if ($mac_exists && $mac_exists->{items}) {
  1185. for my $dup_id (keys %{$mac_exists->{items}}) {
  1186. my $dup = $mac_exists->{items}{$dup_id};
  1187. next unless $dup && $dup->{dynamic};
  1188. delete_user_auth($db, $dup->{id});
  1189. }
  1190. }
  1191. # --- Повторная проверка ---
  1192. $mac_exists = find_mac_in_subnet($db, $ip, $mac);
  1193. if ($mac_exists && $mac_exists->{count}>=1) {
  1194. $new_record->{dhcp} = 0
  1195. }
  1196. # --- Готовим полную запись ---
  1197. $new_record->{ip_int} = $ip_aton;
  1198. $new_record->{ip} = $ip;
  1199. $new_record->{mac} = $mac;
  1200. $new_record->{user_id} = $new_user_id;
  1201. $new_record->{save_traf} = $save_detail;
  1202. $new_record->{deleted} = 0;
  1203. if ($action =~ /^(add|old|del)$/i) {
  1204. $new_record->{dhcp_action} = $action;
  1205. $new_record->{dhcp_time} = $timestamp;
  1206. $new_record->{created_by} = 'dhcp';
  1207. } else {
  1208. $new_record->{created_by} = $action // get_creation_method();
  1209. }
  1210. # --- Проверяем, существует ли уже такая запись ---
  1211. my $auth_exists = get_record_sql($db,
  1212. "SELECT id FROM user_auth WHERE ip_int = ? AND mac = ? LIMIT 1",
  1213. $ip_aton, $mac
  1214. );
  1215. my $cur_auth_id;
  1216. my $msg = '';
  1217. if ($auth_exists && $auth_exists->{id}) {
  1218. # Воскрешаем старую запись
  1219. $cur_auth_id = $auth_exists->{id};
  1220. $msg = "$auth_ident Resurrection auth_id: $cur_auth_id with ip: $ip and mac: $mac";
  1221. if (!$ip_record->{hotspot}) { db_log_warning($db, $msg); } else { db_log_info($db, $msg); }
  1222. update_record($db, 'user_auth', $new_record, 'id = ?', $cur_auth_id);
  1223. } else {
  1224. # Создаём новую
  1225. $cur_auth_id = insert_record($db, 'user_auth', $new_record);
  1226. if ($cur_auth_id) {
  1227. $msg = $auth_ident;
  1228. if (!$ip_record->{hotspot}) { db_log_warning($db, $msg); } else { db_log_info($db, $msg); }
  1229. }
  1230. }
  1231. return 0 unless $cur_auth_id;
  1232. # --- Дополняем данными из user_list и OU ---
  1233. my $user_record = get_record_sql($db, "SELECT * FROM user_list WHERE id = ?", $new_user_id);
  1234. if ($user_record) {
  1235. my $ou_info = get_record_sql($db, "SELECT * FROM ou WHERE id = ?", $user_record->{ou_id});
  1236. if ($ou_info && $ou_info->{dynamic}) {
  1237. my $life_duration = $ou_info->{life_duration} // 24;
  1238. my $hours = int($life_duration);
  1239. my $minutes = ($life_duration - $hours) * 60;
  1240. my $now = DateTime->now(time_zone => 'local');
  1241. my $end_life = $now->clone->add(hours => $hours, minutes => $minutes);
  1242. $new_record->{dynamic} = 1;
  1243. $new_record->{end_life} = $end_life->strftime('%Y-%m-%d %H:%M:%S');
  1244. }
  1245. $new_record->{ou_id} = $user_record->{ou_id};
  1246. $new_record->{description} = $user_record->{description};
  1247. $new_record->{filter_group_id} = $user_record->{filter_group_id};
  1248. $new_record->{queue_id} = $user_record->{queue_id};
  1249. $new_record->{enabled} = $user_record->{enabled} // 0;
  1250. update_record($db, 'user_auth', $new_record, 'id = ?', $cur_auth_id);
  1251. }
  1252. my $final_record = get_record_sql($db, "SELECT * FROM user_auth WHERE id = ?", $cur_auth_id);
  1253. my $changed_msg = prepare_audit_message($db, 'user_auth', undef, $final_record , $cur_auth_id, 'insert');
  1254. $msg .= "\n". $changed_msg;
  1255. db_log_warning($db, $msg, $cur_auth_id);
  1256. sendEmail("WARN! " . get_first_line($msg), $msg , 1) if $send_alert_create;
  1257. return $cur_auth_id;
  1258. }
  1259. #---------------------------------------------------------------------------------------------------------------
  1260. sub new_auth {
  1261. my ($db, $ip) = @_;
  1262. return 0 unless $db && defined $ip && $ip ne '';
  1263. my $ip_aton = StrToIp($ip);
  1264. return 0 unless defined $ip_aton;
  1265. # Проверяем, существует ли уже запись с таким IP
  1266. my $record = get_record_sql($db,
  1267. "SELECT id FROM user_auth WHERE deleted = 0 AND ip_int = ?",
  1268. $ip_aton
  1269. );
  1270. return $record->{id} if $record && $record->{id};
  1271. # Получаем информацию о пользователе/OU
  1272. my $new_user_info = get_new_user_id($db, $ip, undef, undef);
  1273. return 0 unless $new_user_info;
  1274. my $new_user_id;
  1275. if ($new_user_info->{user_id}) {
  1276. $new_user_id = $new_user_info->{user_id};
  1277. } elsif ($new_user_info->{ou_id}) {
  1278. $new_user_id = new_user($db, $new_user_info);
  1279. }
  1280. return 0 unless $new_user_id;
  1281. # --- Дополняем данными из user_list и OU ---
  1282. my $user_record = get_record_sql($db, "SELECT * FROM user_list WHERE id = ?", $new_user_id);
  1283. return 0 unless $user_record;
  1284. my $timestamp = GetNowTime();
  1285. my $new_record = {
  1286. ip_int => $ip_aton,
  1287. ip => $ip,
  1288. user_id => $new_user_id,
  1289. save_traf => $save_detail,
  1290. deleted => 0,
  1291. created_by => get_creation_method(),
  1292. ou_id => $user_record->{ou_id},
  1293. filter_group_id => $user_record->{filter_group_id},
  1294. queue_id => $user_record->{queue_id},
  1295. enabled => $user_record->{enabled} // 0,
  1296. description => $user_record->{description} // '',
  1297. };
  1298. my $ou_info = get_record_sql($db, "SELECT * FROM ou WHERE id = ?", $user_record->{ou_id});
  1299. return 0 unless $ou_info;
  1300. if ($ou_info && $ou_info->{dynamic}) {
  1301. my $life_duration = $ou_info->{life_duration} // 24;
  1302. my $hours = int($life_duration);
  1303. my $minutes = ($life_duration - $hours) * 60;
  1304. my $now = DateTime->now(time_zone => 'local');
  1305. my $end_life = $now->clone->add(hours => $hours, minutes => $minutes);
  1306. $new_record->{dynamic} = 1;
  1307. $new_record->{end_life} = $end_life->strftime('%Y-%m-%d %H:%M:%S');
  1308. }
  1309. my $cur_auth_id = insert_record($db, 'user_auth', $new_record);
  1310. return $cur_auth_id;
  1311. }
  1312. #--------------------------------------------------------------------------------------------------------------
  1313. sub get_dynamic_ou {
  1314. my $db = shift;
  1315. my @dynamic=();
  1316. my @ou_list = get_records_sql($db,"SELECT id FROM ou WHERE dynamic = 1");
  1317. foreach my $group (@ou_list) {
  1318. next if (!$group);
  1319. push(@dynamic,$group->{id});
  1320. }
  1321. return wantarray ? @dynamic : \@dynamic;
  1322. }
  1323. #--------------------------------------------------------------------------------------------------------------
  1324. sub get_default_ou {
  1325. my $db = shift;
  1326. my @dynamic=();
  1327. my $ou = get_record_sql($db,"SELECT id FROM ou WHERE default_users = 1");
  1328. if (!$ou) { push(@dynamic,0); } else { push(@dynamic,$ou->{'id'}); }
  1329. $ou = get_record_sql($db,"SELECT id FROM ou WHERE default_hotspot = 1");
  1330. if ($ou) { push(@dynamic,$ou->{id}); }
  1331. return wantarray ? @dynamic : \@dynamic;
  1332. }
  1333. #--------------------------------------------------------------------------------------------------------------
  1334. sub is_dynamic_ou {
  1335. my $db = shift;
  1336. my $ou_id = shift;
  1337. my @dynamic=get_dynamic_ou($db);
  1338. if (in_array(\@dynamic,$ou_id)) { return 1; }
  1339. return 0;
  1340. }
  1341. #--------------------------------------------------------------------------------------------------------------
  1342. sub is_default_ou {
  1343. my $db = shift;
  1344. my $ou_id = shift;
  1345. my @dynamic=get_default_ou($db);
  1346. if (in_array(\@dynamic,$ou_id)) { return 1; }
  1347. return 0;
  1348. }
  1349. #---------------------------------------------------------------------------------------------------------------
  1350. sub get_subnets_ref {
  1351. my $db = shift;
  1352. my @list=get_records_sql($db,'SELECT * FROM subnets ORDER BY ip_int_start');
  1353. my $list_ref;
  1354. foreach my $net (@list) {
  1355. next if (!$net->{subnet});
  1356. $list_ref->{$net->{subnet}}=$net;
  1357. }
  1358. return $list_ref;
  1359. }
  1360. #---------------------------------------------------------------------------------------------------------------
  1361. sub get_device_by_ip {
  1362. my ($db, $ip) = @_;
  1363. return unless $db && defined $ip && $ip ne '';
  1364. # Ищем устройство напрямую по IP
  1365. my $netdev = get_record_sql($db, "SELECT * FROM devices WHERE ip = ?", $ip);
  1366. return $netdev if $netdev && $netdev->{id} > 0;
  1367. # Ищем user_id по IP в user_auth
  1368. my $auth_rec = get_record_sql($db,
  1369. "SELECT user_id FROM user_auth WHERE ip = ? AND deleted = 0",
  1370. $ip
  1371. );
  1372. if ($auth_rec && defined $auth_rec->{user_id} && $auth_rec->{user_id} > 0) {
  1373. $netdev = get_record_sql($db,
  1374. "SELECT * FROM devices WHERE user_id = ?",
  1375. $auth_rec->{user_id}
  1376. );
  1377. return $netdev;
  1378. }
  1379. return;
  1380. }
  1381. #---------------------------------------------------------------------------------------------------------------
  1382. sub recalc_quotes {
  1383. my ($db, $calc_id) = @_;
  1384. $calc_id //= $$;
  1385. return unless get_option($db, 54);
  1386. clean_variables($db);
  1387. return if Get_Variable($db, 'RECALC');
  1388. my $timeshift = get_option($db, 55);
  1389. Set_Variable($db, 'RECALC', $calc_id, time() + $timeshift * 60);
  1390. # --- Готовим временные метки ---
  1391. my $now = DateTime->now(time_zone => 'local');
  1392. my $day_start = $now->clone->truncate(to => 'day');
  1393. my $day_stop = $day_start->clone->add(days => 1);
  1394. my $month_start = $now->clone->truncate(to => 'month');
  1395. my $month_stop = $month_start->clone->add(months => 1);
  1396. # --- Получаем список авторизаций ---
  1397. my $user_auth_list_sql = q{
  1398. SELECT A.id as auth_id, U.id, U.day_quota, U.month_quota,
  1399. A.day_quota as auth_day, A.month_quota as auth_month
  1400. FROM user_auth AS A
  1401. JOIN user_list AS U ON A.user_id = U.id
  1402. WHERE A.deleted = 0
  1403. ORDER BY user_id
  1404. };
  1405. my @authlist_ref = get_records_sql($db, $user_auth_list_sql);
  1406. my %user_stats;
  1407. my %auth_info;
  1408. foreach my $row (@authlist_ref) {
  1409. $auth_info{$row->{auth_id}}{user_id} = $row->{id};
  1410. $auth_info{$row->{auth_id}}{day_limit} = $row->{auth_day} // 0;
  1411. $auth_info{$row->{auth_id}}{month_limit} = $row->{auth_month} // 0;
  1412. $auth_info{$row->{auth_id}}{day} = 0;
  1413. $auth_info{$row->{auth_id}}{month} = 0;
  1414. $user_stats{$row->{id}}{day_limit} = $row->{day_quota} // 0;
  1415. $user_stats{$row->{id}}{month_limit} = $row->{month_quota} // 0;
  1416. $user_stats{$row->{id}}{day} = 0;
  1417. $user_stats{$row->{id}}{month} = 0;
  1418. }
  1419. # --- Считаем дневной трафик ---
  1420. my @day_stats = get_records_sql($db,
  1421. "SELECT auth_id, SUM(byte_in + byte_out) AS traf_all
  1422. FROM user_stats
  1423. WHERE ts >= ? AND ts < ?
  1424. GROUP BY auth_id",
  1425. $day_start->strftime('%Y-%m-%d %H:%M:%S'),
  1426. $day_stop->strftime('%Y-%m-%d %H:%M:%S')
  1427. );
  1428. foreach my $row (@day_stats) {
  1429. my $user_id = $auth_info{$row->{auth_id}}{user_id};
  1430. $auth_info{$row->{auth_id}}{day} = $row->{traf_all} // 0;
  1431. $user_stats{$user_id}{day} += $row->{traf_all} // 0;
  1432. }
  1433. # --- Считаем месячный трафик ---
  1434. my @month_stats = get_records_sql($db,
  1435. "SELECT auth_id, SUM(byte_in + byte_out) AS traf_all
  1436. FROM user_stats
  1437. WHERE ts >= ? AND ts < ?
  1438. GROUP BY auth_id",
  1439. $month_start->strftime('%Y-%m-%d %H:%M:%S'),
  1440. $month_stop->strftime('%Y-%m-%d %H:%M:%S')
  1441. );
  1442. foreach my $row (@month_stats) {
  1443. my $user_id = $auth_info{$row->{auth_id}}{user_id};
  1444. $auth_info{$row->{auth_id}}{month} = $row->{traf_all} // 0;
  1445. $user_stats{$user_id}{month} += $row->{traf_all} // 0;
  1446. }
  1447. # --- Блокировка по квотам для auth_id ---
  1448. foreach my $auth_id (keys %auth_info) {
  1449. next unless $auth_info{$auth_id}{day_limit} || $auth_info{$auth_id}{month_limit};
  1450. my $day_limit = ($auth_info{$auth_id}{day_limit} // 0) * $KB * $KB;
  1451. my $month_limit = ($auth_info{$auth_id}{month_limit} // 0) * $KB * $KB;
  1452. my $blocked_d = $auth_info{$auth_id}{day} > $day_limit;
  1453. my $blocked_m = $auth_info{$auth_id}{month} > $month_limit;
  1454. if ($blocked_d || $blocked_m) {
  1455. my $history_msg;
  1456. if ($blocked_d) {
  1457. $history_msg = sprintf "Day quota limit found for auth_id: %d - Current: %d Max: %d",
  1458. $auth_id, $auth_info{$auth_id}{day}, $day_limit;
  1459. }
  1460. if ($blocked_m) {
  1461. $history_msg = sprintf "Month quota limit found for auth_id: %d - Current: %d Max: %d",
  1462. $auth_id, $auth_info{$auth_id}{month}, $month_limit;
  1463. }
  1464. do_sql($db, "UPDATE user_auth SET blocked = 1, changed = 1 WHERE id = ?", $auth_id);
  1465. db_log_verbose($db, $history_msg);
  1466. }
  1467. }
  1468. # --- Блокировка по квотам для user_id ---
  1469. foreach my $user_id (keys %user_stats) {
  1470. next unless $user_stats{$user_id}{day_limit} || $user_stats{$user_id}{month_limit};
  1471. my $day_limit = ($user_stats{$user_id}{day_limit} // 0) * $KB * $KB;
  1472. my $month_limit = ($user_stats{$user_id}{month_limit} // 0) * $KB * $KB;
  1473. my $blocked_d = $user_stats{$user_id}{day} > $day_limit;
  1474. my $blocked_m = $user_stats{$user_id}{month} > $month_limit;
  1475. if ($blocked_d || $blocked_m) {
  1476. my $history_msg;
  1477. if ($blocked_d) {
  1478. $history_msg = sprintf "Day quota limit found for user_id: %d - Current: %d Max: %d",
  1479. $user_id, $user_stats{$user_id}{day}, $day_limit;
  1480. }
  1481. if ($blocked_m) {
  1482. $history_msg = sprintf "Month quota limit found for user_id: %d - Current: %d Max: %d",
  1483. $user_id, $user_stats{$user_id}{month}, $month_limit;
  1484. }
  1485. # Исправлено: user_list вместо User_user
  1486. do_sql($db, "UPDATE user_list SET blocked = 1 WHERE id = ?", $user_id);
  1487. do_sql($db, "UPDATE user_auth SET blocked = 1, changed = 1 WHERE user_id = ?", $user_id);
  1488. db_log_verbose($db, $history_msg);
  1489. }
  1490. }
  1491. Del_Variable($db, 'RECALC');
  1492. }
  1493. #--------------------------------------------------------------------------------
  1494. sub process_dhcp_request {
  1495. my ($db, $type, $mac, $ip, $hostname, $client_id, $circuit_id, $remote_id) = @_;
  1496. return unless $type && $type =~ /^(old|add|del)$/i;
  1497. my $client_hostname = '';
  1498. if ($hostname && $hostname ne 'undef' && $hostname !~ /UNDEFINED/i) {
  1499. $client_hostname = $hostname;
  1500. }
  1501. my $auth_network = $office_networks->match_string($ip);
  1502. if (!$auth_network) {
  1503. log_error("Unknown network in dhcp request! IP: $ip");
  1504. return;
  1505. }
  1506. $circuit_id //= '';
  1507. $client_id //= '';
  1508. $remote_id //= '';
  1509. my $timestamp = time();
  1510. my $ip_aton = StrToIp($ip);
  1511. return unless defined $ip_aton;
  1512. $mac = mac_splitted($mac);
  1513. my $dhcp_event_time = GetNowTime($timestamp);
  1514. my $dhcp_record = {
  1515. mac => $mac,
  1516. ip => $ip,
  1517. ip_aton => $ip_aton,
  1518. hostname => $client_hostname,
  1519. network => $auth_network,
  1520. type => $type,
  1521. hostname_utf8 => $client_hostname,
  1522. ts => $timestamp,
  1523. last_time => time(),
  1524. circuit_id => $circuit_id,
  1525. client_id => $client_id,
  1526. remote_id => $remote_id,
  1527. hotspot => is_hotspot($db, $ip),
  1528. };
  1529. # --- Ищем существующую запись ---
  1530. 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 );
  1531. # Если запись не найдена и тип 'del' — выходим
  1532. if (!$auth_record && $type eq 'del') {
  1533. db_log_info($db, "Auth recrod for ip: $ip mac: $mac not found. Dhcp request type: $type. Skip processing.");
  1534. return;
  1535. }
  1536. # Если запись не найдена и тип 'add'/'old' — создаём
  1537. if (!$auth_record && ($type eq 'add' || $type eq 'old')) {
  1538. my $res_id = resurrection_auth($db, $dhcp_record);
  1539. if (!$res_id) {
  1540. db_log_error($db, "Error creating an ip address record for ip=$ip and mac=$mac!");
  1541. return;
  1542. }
  1543. $auth_record = get_record_sql($db, "SELECT * FROM user_auth WHERE id = ?", $res_id);
  1544. db_log_info($db, "Created new auth. auth id: $res_id", $res_id);
  1545. }
  1546. if (!$auth_record || !$auth_record->{id}) {
  1547. db_log_error($db, "Record not found/created for ip: $ip mac: $mac not found. Dhcp request type: $type!");
  1548. return;
  1549. }
  1550. my $auth_id = $auth_record->{id};
  1551. my $auth_ou_id = $auth_record->{ou_id};
  1552. $dhcp_record->{auth_id} = $auth_id;
  1553. $dhcp_record->{auth_ou_id} = $auth_ou_id;
  1554. update_dns_record_by_dhcp($db, $dhcp_record, $auth_record);
  1555. # --- Обработка ADD ---
  1556. if ($type eq 'add' && $dhcp_record->{hostname_utf8}) {
  1557. my $auth_rec = {
  1558. dhcp_hostname => $dhcp_record->{hostname_utf8},
  1559. dhcp_time => $dhcp_event_time,
  1560. arp_found => $dhcp_event_time,
  1561. created_by => 'dhcp',
  1562. };
  1563. log_info("Add lease by dhcp event for client id: $auth_id ip: $ip mac: $mac");
  1564. update_record($db, 'user_auth', $auth_rec, 'id = ?', $auth_id);
  1565. }
  1566. # --- Обработка OLD ---
  1567. if ($type eq 'old') {
  1568. my $auth_rec = {
  1569. dhcp_action => $type,
  1570. dhcp_time => $dhcp_event_time,
  1571. created_by => 'dhcp',
  1572. arp_found => $dhcp_event_time,
  1573. };
  1574. log_info("Update lease by dhcp event for client id: $auth_id ip: $ip mac: $mac");
  1575. update_record($db, 'user_auth', $auth_rec, 'id = ?', $auth_id);
  1576. }
  1577. # --- Обработка DEL ---
  1578. if ($type eq 'del' && $auth_id) {
  1579. if ($auth_record->{dhcp_time} =~ /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/) {
  1580. log_info("Release dhcp event for client id: $auth_id ip: $ip mac: $mac");
  1581. my $auth_rec = {
  1582. dhcp_action => $type,
  1583. dhcp_time => $dhcp_event_time,
  1584. };
  1585. update_record($db, 'user_auth', $auth_rec, 'id = ?', $auth_id);
  1586. my $d_time = mktime($6, $5, $4, $3, $2 - 1, $1 - 1900);
  1587. if (time() - $d_time > 60 && (is_dynamic_ou($db, $auth_ou_id) || is_default_ou($db, $auth_ou_id))) {
  1588. # Удаляем запись, если она из динамического или дефолтного пула
  1589. if (is_default_ou($db, $auth_ou_id) || (is_dynamic_ou($db, $auth_ou_id) && $auth_record->{dynamic})) {
  1590. db_log_info($db, "Remove user ip record by dhcp release event for dynamic clients id: $auth_id ip: $ip mac: $mac", $auth_id);
  1591. delete_user_auth($db, $auth_id);
  1592. # Проверяем, остались ли другие записи у пользователя
  1593. my $u_count = get_record_sql($db,
  1594. "SELECT COUNT(*) AS cnt FROM user_auth WHERE deleted = 0 AND user_id = ?",
  1595. $auth_record->{user_id}
  1596. );
  1597. if ($u_count && $u_count->{cnt} == 0) {
  1598. delete_user($db, $auth_record->{user_id});
  1599. }
  1600. }
  1601. }
  1602. }
  1603. }
  1604. # --- Пропуск логирования для hotspot или ignore_update_dhcp_event ---
  1605. if ($dhcp_record->{hotspot} && $ignore_hotspot_dhcp_log) {
  1606. return $dhcp_record;
  1607. }
  1608. if ($ignore_update_dhcp_event && $type eq 'old') {
  1609. return $dhcp_record;
  1610. }
  1611. # --- Логируем событие ---
  1612. my $dhcp_log = {
  1613. auth_id => $auth_id // 0,
  1614. ip => $ip,
  1615. ip_int => $ip_aton,
  1616. mac => $mac,
  1617. action => $type,
  1618. dhcp_hostname => $client_hostname,
  1619. ts => $dhcp_event_time,
  1620. circuit_id => $circuit_id,
  1621. client_id => $client_id,
  1622. remote_id => $remote_id,
  1623. };
  1624. insert_record($db, 'dhcp_log', $dhcp_log);
  1625. return $dhcp_record;
  1626. }
  1627. 1;
  1628. }