1
0

common.pm 69 KB

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