common.pm 67 KB

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