1
0

common.pm 66 KB

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