common.pm 70 KB

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