common.pm 67 KB

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