common.pm 66 KB

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