common.pm 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884
  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 && defined $ip_subnet->{ip_int_start} && defined $ip_subnet->{ip_int_stop};
  1030. # Безопасный параметризованный запрос
  1031. my @t_auth = get_records_sql($db,
  1032. "SELECT * FROM user_auth
  1033. WHERE ip_int BETWEEN ? AND ?
  1034. AND mac = ?
  1035. AND deleted = 0
  1036. ORDER BY id",
  1037. $ip_subnet->{ip_int_start},
  1038. $ip_subnet->{ip_int_stop},
  1039. $mac
  1040. );
  1041. return unless @t_auth;
  1042. my $result = { count => 0, items => {} };
  1043. for my $i (0 .. $#t_auth) {
  1044. $result->{count}++;
  1045. $result->{items}{$result->{count}} = $t_auth[$i];
  1046. }
  1047. return $result;
  1048. }
  1049. #---------------------------------------------------------------------------------------------------------------
  1050. sub get_creation_method {
  1051. my $script_name = $config_ref{my_name} // (split('/', $0))[-1];
  1052. return 'dhcp' if $script_name eq 'dhcp-log.pl';
  1053. return 'netflow' if $script_name eq 'eye-statd.pl';
  1054. return 'arp' if $script_name eq 'fetch_new_arp.pl';
  1055. # По умолчанию — имя скрипта без расширения
  1056. $script_name =~ s/\.pl$//;
  1057. return $script_name || 'unknown';
  1058. }
  1059. #---------------------------------------------------------------------------------------------------------------
  1060. sub resurrection_auth {
  1061. my ($db, $ip_record) = @_;
  1062. return 0 unless $db && ref $ip_record eq 'HASH';
  1063. my $ip = $ip_record->{ip} // '';
  1064. my $mac = $ip_record->{mac} // '';
  1065. my $action = $ip_record->{type} // '';
  1066. my $hostname= $ip_record->{hostname_utf8} // '';
  1067. my $client_id = $ip_record->{client_id} // '';
  1068. return 0 if !$ip || !$mac;
  1069. # Подготавливаем ip_aton и hotspot
  1070. $ip_record->{ip_aton} //= StrToIp($ip);
  1071. $ip_record->{hotspot} //= is_hotspot($db, $ip);
  1072. my $auth_ident = "Found new ip-address: $ip";
  1073. $auth_ident .= " [$mac]" if $mac;
  1074. $auth_ident .= " :: $hostname" if $hostname;
  1075. my $ip_aton = $ip_record->{ip_aton};
  1076. return 0 unless defined $ip_aton;
  1077. my $timestamp = GetNowTime();
  1078. # --- Ищем существующую запись по IP+MAC ---
  1079. my $record = get_record_sql($db,
  1080. "SELECT * FROM user_auth WHERE deleted = 0 AND ip_int = ? AND mac = ?",
  1081. $ip_aton, $mac
  1082. );
  1083. my $new_record = {
  1084. last_found => $timestamp,
  1085. arp_found => $timestamp,
  1086. client_id => $client_id // undef,
  1087. };
  1088. # Если нашли — обновляем
  1089. if ($record && $record->{user_id}) {
  1090. if ($action =~ /^(add|old|del)$/i) {
  1091. $new_record->{dhcp_action} = $action;
  1092. $new_record->{created_by} = 'dhcp';
  1093. $new_record->{dhcp_time} = $timestamp;
  1094. $new_record->{dhcp_hostname} = $hostname if $hostname;
  1095. } else {
  1096. $new_record->{created_by} = $action // get_creation_method();
  1097. }
  1098. update_record($db, 'user_auth', $new_record, 'id = ?', $record->{id});
  1099. return $record->{id};
  1100. }
  1101. my $send_alert_create = isNotifyCreate(get_notify_subnet($db, $ip));
  1102. # --- Проверка статической подсети ---
  1103. my $user_subnet = $office_networks->match_string($ip);
  1104. if ($user_subnet && $user_subnet->{static}) {
  1105. my $msg = "Found new unknown ip+mac in static subnet! Abort create record for this: $ip [$mac]";
  1106. db_log_warning($db, $msg);
  1107. sendEmail("WARN! " . get_first_line($msg), $msg, 1) if $send_alert_create;
  1108. return 0;
  1109. }
  1110. my $send_alert_update = isNotifyUpdate(get_notify_subnet($db, $ip));
  1111. # --- Ищем другие записи с этим MAC в той же подсети ---
  1112. my $mac_exists = find_mac_in_subnet($db, $ip, $mac);
  1113. # --- Ищем запись с тем же IP (но другим MAC) ---
  1114. my $ip_record_same = get_record_sql($db,
  1115. "SELECT * FROM user_auth WHERE ip_int = ? AND deleted = 0",
  1116. $ip_aton
  1117. );
  1118. if ($ip_record_same && $ip_record_same->{id}) {
  1119. if (!$ip_record_same->{mac}) {
  1120. # Обновляем запись без MAC
  1121. $new_record->{mac} = $mac;
  1122. $new_record->{dhcp} = 0 if $mac_exists && $mac_exists->{count};
  1123. if ($action =~ /^(add|old|del)$/i) {
  1124. $new_record->{dhcp_action} = $action;
  1125. $new_record->{dhcp_time} = $timestamp;
  1126. $new_record->{created_by} = 'dhcp';
  1127. $new_record->{dhcp_hostname} = $hostname if $hostname;
  1128. } else {
  1129. $new_record->{created_by} = $action // get_creation_method();
  1130. }
  1131. update_record($db, 'user_auth', $new_record, 'id = ?', $ip_record_same->{id});
  1132. return $ip_record_same->{id};
  1133. } elsif ($ip_record_same->{mac}) {
  1134. # MAC изменился — удаляем старую запись
  1135. if (!$ip_record->{hotspot}) {
  1136. 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}";
  1137. db_log_warning($db, $msg, $ip_record_same->{id});
  1138. sendEmail("WARN! " . get_first_line($msg), $msg, 1) if $send_alert_update;
  1139. }
  1140. delete_user_auth($db, $ip_record_same->{id});
  1141. }
  1142. }
  1143. # --- Создаём нового пользователя, если нужно ---
  1144. my $new_user_info = get_new_user_id($db, $ip, $mac, $hostname);
  1145. my $new_user_id = $new_user_info->{user_id} // new_user($db, $new_user_info);
  1146. # --- Удаляем дубли с dynamic=1 ---
  1147. if ($mac_exists && $mac_exists->{items}) {
  1148. for my $dup_id (keys %{$mac_exists->{items}}) {
  1149. my $dup = $mac_exists->{items}{$dup_id};
  1150. next unless $dup && $dup->{dynamic};
  1151. delete_user_auth($db, $dup->{id});
  1152. }
  1153. }
  1154. # --- Повторная проверка ---
  1155. $mac_exists = find_mac_in_subnet($db, $ip, $mac);
  1156. $new_record->{dhcp} = 0 if $mac_exists && $mac_exists->{count};
  1157. # --- Готовим полную запись ---
  1158. $new_record->{ip_int} = $ip_aton;
  1159. $new_record->{ip} = $ip;
  1160. $new_record->{mac} = $mac;
  1161. $new_record->{user_id} = $new_user_id;
  1162. $new_record->{save_traf} = $save_detail;
  1163. $new_record->{deleted} = 0;
  1164. if ($action =~ /^(add|old|del)$/i) {
  1165. $new_record->{dhcp_action} = $action;
  1166. $new_record->{dhcp_time} = $timestamp;
  1167. $new_record->{created_by} = 'dhcp';
  1168. } else {
  1169. $new_record->{created_by} = $action // get_creation_method();
  1170. }
  1171. # --- Проверяем, существует ли уже такая запись ---
  1172. my $auth_exists = get_record_sql($db,
  1173. "SELECT id FROM user_auth WHERE ip_int = ? AND mac = ? LIMIT 1",
  1174. $ip_aton, $mac
  1175. );
  1176. my $cur_auth_id;
  1177. my $msg = '';
  1178. if ($auth_exists && $auth_exists->{id}) {
  1179. # Воскрешаем старую запись
  1180. $cur_auth_id = $auth_exists->{id};
  1181. $msg = "$auth_ident Resurrection auth_id: $cur_auth_id with ip: $ip and mac: $mac";
  1182. if (!$ip_record->{hotspot}) { db_log_warning($db, $msg); } else { db_log_info($db, $msg); }
  1183. update_record($db, 'user_auth', $new_record, 'id = ?', $cur_auth_id);
  1184. } else {
  1185. # Создаём новую
  1186. $cur_auth_id = insert_record($db, 'user_auth', $new_record);
  1187. if ($cur_auth_id) {
  1188. $msg = $auth_ident;
  1189. if (!$ip_record->{hotspot}) { db_log_warning($db, $msg); } else { db_log_info($db, $msg); }
  1190. }
  1191. }
  1192. return 0 unless $cur_auth_id;
  1193. # --- Дополняем данными из user_list и OU ---
  1194. my $user_record = get_record_sql($db, "SELECT * FROM user_list WHERE id = ?", $new_user_id);
  1195. if ($user_record) {
  1196. my $ou_info = get_record_sql($db, "SELECT * FROM ou WHERE id = ?", $user_record->{ou_id});
  1197. if ($ou_info && $ou_info->{dynamic}) {
  1198. my $life_duration = $ou_info->{life_duration} // 24;
  1199. my $hours = int($life_duration);
  1200. my $minutes = ($life_duration - $hours) * 60;
  1201. my $now = DateTime->now(time_zone => 'local');
  1202. my $end_life = $now->clone->add(hours => $hours, minutes => $minutes);
  1203. $new_record->{dynamic} = 1;
  1204. $new_record->{end_life} = $end_life->strftime('%Y-%m-%d %H:%M:%S');
  1205. }
  1206. $new_record->{ou_id} = $user_record->{ou_id};
  1207. $new_record->{description} = $user_record->{description};
  1208. $new_record->{filter_group_id} = $user_record->{filter_group_id};
  1209. $new_record->{queue_id} = $user_record->{queue_id};
  1210. $new_record->{enabled} = $user_record->{enabled} // 0;
  1211. update_record($db, 'user_auth', $new_record, 'id = ?', $cur_auth_id);
  1212. }
  1213. my $final_record = get_record_sql($db, "SELECT * FROM user_auth WHERE id = ?", $cur_auth_id);
  1214. my $changed_msg = prepare_audit_message($db, 'user_auth', undef, $final_record , $cur_auth_id, 'insert');
  1215. $msg .= "\n". $changed_msg;
  1216. db_log_warning($db, $msg, $cur_auth_id);
  1217. sendEmail("WARN! " . get_first_line($msg), $msg . "\n" . record_to_txt($db, 'user_auth', $cur_auth_id), 1) if $send_alert_create;
  1218. return $cur_auth_id;
  1219. }
  1220. #---------------------------------------------------------------------------------------------------------------
  1221. sub new_auth {
  1222. my ($db, $ip) = @_;
  1223. return 0 unless $db && defined $ip && $ip ne '';
  1224. my $ip_aton = StrToIp($ip);
  1225. return 0 unless defined $ip_aton;
  1226. # Проверяем, существует ли уже запись с таким IP
  1227. my $record = get_record_sql($db,
  1228. "SELECT id FROM user_auth WHERE deleted = 0 AND ip_int = ?",
  1229. $ip_aton
  1230. );
  1231. return $record->{id} if $record && $record->{id};
  1232. # Получаем информацию о пользователе/OU
  1233. my $new_user_info = get_new_user_id($db, $ip, undef, undef);
  1234. return 0 unless $new_user_info;
  1235. my $new_user_id;
  1236. if ($new_user_info->{user_id}) {
  1237. $new_user_id = $new_user_info->{user_id};
  1238. } elsif ($new_user_info->{ou_id}) {
  1239. $new_user_id = new_user($db, $new_user_info);
  1240. }
  1241. return 0 unless $new_user_id;
  1242. my $send_alert = isNotifyCreate(get_notify_subnet($db, $ip));
  1243. # Получаем данные пользователя БЕЗОПАСНО
  1244. my $user_record = get_record_sql($db,
  1245. "SELECT * FROM user_list WHERE id = ?",
  1246. $new_user_id
  1247. );
  1248. return 0 unless $user_record;
  1249. my $timestamp = GetNowTime();
  1250. my $new_record = {
  1251. ip_int => $ip_aton,
  1252. ip => $ip,
  1253. user_id => $new_user_id,
  1254. save_traf => $save_detail,
  1255. deleted => 0,
  1256. created_by => get_creation_method(),
  1257. ou_id => $user_record->{ou_id},
  1258. filter_group_id => $user_record->{filter_group_id},
  1259. queue_id => $user_record->{queue_id},
  1260. enabled => $user_record->{enabled} // 0,
  1261. };
  1262. $new_record->{description} = $user_record->{description} if $user_record->{description};
  1263. my $cur_auth_id = insert_record($db, 'user_auth', $new_record);
  1264. return $cur_auth_id;
  1265. }
  1266. #--------------------------------------------------------------------------------------------------------------
  1267. sub get_dynamic_ou {
  1268. my $db = shift;
  1269. my @dynamic=();
  1270. my @ou_list = get_records_sql($db,"SELECT id FROM ou WHERE dynamic = 1");
  1271. foreach my $group (@ou_list) {
  1272. next if (!$group);
  1273. push(@dynamic,$group->{id});
  1274. }
  1275. return wantarray ? @dynamic : \@dynamic;
  1276. }
  1277. #--------------------------------------------------------------------------------------------------------------
  1278. sub get_default_ou {
  1279. my $db = shift;
  1280. my @dynamic=();
  1281. my $ou = get_record_sql($db,"SELECT id FROM ou WHERE default_users = 1");
  1282. if (!$ou) { push(@dynamic,0); } else { push(@dynamic,$ou->{'id'}); }
  1283. $ou = get_record_sql($db,"SELECT id FROM ou WHERE default_hotspot = 1");
  1284. if ($ou) { push(@dynamic,$ou->{id}); }
  1285. return wantarray ? @dynamic : \@dynamic;
  1286. }
  1287. #--------------------------------------------------------------------------------------------------------------
  1288. sub is_dynamic_ou {
  1289. my $db = shift;
  1290. my $ou_id = shift;
  1291. my @dynamic=get_dynamic_ou($db);
  1292. if (in_array(\@dynamic,$ou_id)) { return 1; }
  1293. return 0;
  1294. }
  1295. #--------------------------------------------------------------------------------------------------------------
  1296. sub is_default_ou {
  1297. my $db = shift;
  1298. my $ou_id = shift;
  1299. my @dynamic=get_default_ou($db);
  1300. if (in_array(\@dynamic,$ou_id)) { return 1; }
  1301. return 0;
  1302. }
  1303. #---------------------------------------------------------------------------------------------------------------
  1304. sub get_subnets_ref {
  1305. my $db = shift;
  1306. my @list=get_records_sql($db,'SELECT * FROM subnets ORDER BY ip_int_start');
  1307. my $list_ref;
  1308. foreach my $net (@list) {
  1309. next if (!$net->{subnet});
  1310. $list_ref->{$net->{subnet}}=$net;
  1311. }
  1312. return $list_ref;
  1313. }
  1314. #---------------------------------------------------------------------------------------------------------------
  1315. sub get_device_by_ip {
  1316. my ($db, $ip) = @_;
  1317. return unless $db && defined $ip && $ip ne '';
  1318. # Ищем устройство напрямую по IP
  1319. my $netdev = get_record_sql($db, "SELECT * FROM devices WHERE ip = ?", $ip);
  1320. return $netdev if $netdev && $netdev->{id} > 0;
  1321. # Ищем user_id по IP в user_auth
  1322. my $auth_rec = get_record_sql($db,
  1323. "SELECT user_id FROM user_auth WHERE ip = ? AND deleted = 0",
  1324. $ip
  1325. );
  1326. if ($auth_rec && defined $auth_rec->{user_id} && $auth_rec->{user_id} > 0) {
  1327. $netdev = get_record_sql($db,
  1328. "SELECT * FROM devices WHERE user_id = ?",
  1329. $auth_rec->{user_id}
  1330. );
  1331. return $netdev;
  1332. }
  1333. return;
  1334. }
  1335. #---------------------------------------------------------------------------------------------------------------
  1336. sub recalc_quotes {
  1337. my ($db, $calc_id) = @_;
  1338. $calc_id //= $$;
  1339. return unless get_option($db, 54);
  1340. clean_variables($db);
  1341. return if Get_Variable($db, 'RECALC');
  1342. my $timeshift = get_option($db, 55);
  1343. Set_Variable($db, 'RECALC', $calc_id, time() + $timeshift * 60);
  1344. # --- Готовим временные метки ---
  1345. my $now = DateTime->now(time_zone => 'local');
  1346. my $day_start = $now->clone->truncate(to => 'day');
  1347. my $day_stop = $day_start->clone->add(days => 1);
  1348. my $month_start = $now->clone->truncate(to => 'month');
  1349. my $month_stop = $month_start->clone->add(months => 1);
  1350. # --- Получаем список авторизаций ---
  1351. my $user_auth_list_sql = q{
  1352. SELECT A.id as auth_id, U.id, U.day_quota, U.month_quota,
  1353. A.day_quota as auth_day, A.month_quota as auth_month
  1354. FROM user_auth AS A
  1355. JOIN user_list AS U ON A.user_id = U.id
  1356. WHERE A.deleted = 0
  1357. ORDER BY user_id
  1358. };
  1359. my @authlist_ref = get_records_sql($db, $user_auth_list_sql);
  1360. my %user_stats;
  1361. my %auth_info;
  1362. foreach my $row (@authlist_ref) {
  1363. $auth_info{$row->{auth_id}}{user_id} = $row->{id};
  1364. $auth_info{$row->{auth_id}}{day_limit} = $row->{auth_day} // 0;
  1365. $auth_info{$row->{auth_id}}{month_limit} = $row->{auth_month} // 0;
  1366. $auth_info{$row->{auth_id}}{day} = 0;
  1367. $auth_info{$row->{auth_id}}{month} = 0;
  1368. $user_stats{$row->{id}}{day_limit} = $row->{day_quota} // 0;
  1369. $user_stats{$row->{id}}{month_limit} = $row->{month_quota} // 0;
  1370. $user_stats{$row->{id}}{day} = 0;
  1371. $user_stats{$row->{id}}{month} = 0;
  1372. }
  1373. # --- Считаем дневной трафик ---
  1374. my @day_stats = get_records_sql($db,
  1375. "SELECT auth_id, SUM(byte_in + byte_out) AS traf_all
  1376. FROM user_stats
  1377. WHERE ts >= ? AND ts < ?
  1378. GROUP BY auth_id",
  1379. $day_start->strftime('%Y-%m-%d %H:%M:%S'),
  1380. $day_stop->strftime('%Y-%m-%d %H:%M:%S')
  1381. );
  1382. foreach my $row (@day_stats) {
  1383. my $user_id = $auth_info{$row->{auth_id}}{user_id};
  1384. $auth_info{$row->{auth_id}}{day} = $row->{traf_all} // 0;
  1385. $user_stats{$user_id}{day} += $row->{traf_all} // 0;
  1386. }
  1387. # --- Считаем месячный трафик ---
  1388. my @month_stats = get_records_sql($db,
  1389. "SELECT auth_id, SUM(byte_in + byte_out) AS traf_all
  1390. FROM user_stats
  1391. WHERE ts >= ? AND ts < ?
  1392. GROUP BY auth_id",
  1393. $month_start->strftime('%Y-%m-%d %H:%M:%S'),
  1394. $month_stop->strftime('%Y-%m-%d %H:%M:%S')
  1395. );
  1396. foreach my $row (@month_stats) {
  1397. my $user_id = $auth_info{$row->{auth_id}}{user_id};
  1398. $auth_info{$row->{auth_id}}{month} = $row->{traf_all} // 0;
  1399. $user_stats{$user_id}{month} += $row->{traf_all} // 0;
  1400. }
  1401. # --- Блокировка по квотам для auth_id ---
  1402. foreach my $auth_id (keys %auth_info) {
  1403. next unless $auth_info{$auth_id}{day_limit} || $auth_info{$auth_id}{month_limit};
  1404. my $day_limit = ($auth_info{$auth_id}{day_limit} // 0) * $KB * $KB;
  1405. my $month_limit = ($auth_info{$auth_id}{month_limit} // 0) * $KB * $KB;
  1406. my $blocked_d = $auth_info{$auth_id}{day} > $day_limit;
  1407. my $blocked_m = $auth_info{$auth_id}{month} > $month_limit;
  1408. if ($blocked_d || $blocked_m) {
  1409. my $history_msg;
  1410. if ($blocked_d) {
  1411. $history_msg = sprintf "Day quota limit found for auth_id: %d - Current: %d Max: %d",
  1412. $auth_id, $auth_info{$auth_id}{day}, $day_limit;
  1413. }
  1414. if ($blocked_m) {
  1415. $history_msg = sprintf "Month quota limit found for auth_id: %d - Current: %d Max: %d",
  1416. $auth_id, $auth_info{$auth_id}{month}, $month_limit;
  1417. }
  1418. do_sql($db, "UPDATE user_auth SET blocked = 1, changed = 1 WHERE id = ?", $auth_id);
  1419. db_log_verbose($db, $history_msg);
  1420. }
  1421. }
  1422. # --- Блокировка по квотам для user_id ---
  1423. foreach my $user_id (keys %user_stats) {
  1424. next unless $user_stats{$user_id}{day_limit} || $user_stats{$user_id}{month_limit};
  1425. my $day_limit = ($user_stats{$user_id}{day_limit} // 0) * $KB * $KB;
  1426. my $month_limit = ($user_stats{$user_id}{month_limit} // 0) * $KB * $KB;
  1427. my $blocked_d = $user_stats{$user_id}{day} > $day_limit;
  1428. my $blocked_m = $user_stats{$user_id}{month} > $month_limit;
  1429. if ($blocked_d || $blocked_m) {
  1430. my $history_msg;
  1431. if ($blocked_d) {
  1432. $history_msg = sprintf "Day quota limit found for user_id: %d - Current: %d Max: %d",
  1433. $user_id, $user_stats{$user_id}{day}, $day_limit;
  1434. }
  1435. if ($blocked_m) {
  1436. $history_msg = sprintf "Month quota limit found for user_id: %d - Current: %d Max: %d",
  1437. $user_id, $user_stats{$user_id}{month}, $month_limit;
  1438. }
  1439. # Исправлено: user_list вместо User_user
  1440. do_sql($db, "UPDATE user_list SET blocked = 1 WHERE id = ?", $user_id);
  1441. do_sql($db, "UPDATE user_auth SET blocked = 1, changed = 1 WHERE user_id = ?", $user_id);
  1442. db_log_verbose($db, $history_msg);
  1443. }
  1444. }
  1445. Del_Variable($db, 'RECALC');
  1446. }
  1447. #--------------------------------------------------------------------------------
  1448. sub process_dhcp_request {
  1449. my ($db, $type, $mac, $ip, $hostname, $client_id, $circuit_id, $remote_id) = @_;
  1450. return unless $type && $type =~ /^(old|add|del)$/i;
  1451. my $client_hostname = '';
  1452. if ($hostname && $hostname ne 'undef' && $hostname !~ /UNDEFINED/i) {
  1453. $client_hostname = $hostname;
  1454. }
  1455. my $auth_network = $office_networks->match_string($ip);
  1456. if (!$auth_network) {
  1457. log_error("Unknown network in dhcp request! IP: $ip");
  1458. return;
  1459. }
  1460. $circuit_id //= '';
  1461. $client_id //= '';
  1462. $remote_id //= '';
  1463. my $timestamp = time();
  1464. my $ip_aton = StrToIp($ip);
  1465. return unless defined $ip_aton;
  1466. $mac = mac_splitted($mac);
  1467. my $dhcp_event_time = GetNowTime($timestamp);
  1468. my $dhcp_record = {
  1469. mac => $mac,
  1470. ip => $ip,
  1471. ip_aton => $ip_aton,
  1472. hostname => $client_hostname,
  1473. network => $auth_network,
  1474. type => $type,
  1475. hostname_utf8 => $client_hostname,
  1476. ts => $timestamp,
  1477. last_time => time(),
  1478. circuit_id => $circuit_id,
  1479. client_id => $client_id,
  1480. remote_id => $remote_id,
  1481. hotspot => is_hotspot($db, $ip),
  1482. };
  1483. # --- Ищем существующую запись ---
  1484. 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 );
  1485. # Если запись не найдена и тип 'del' — выходим
  1486. if (!$auth_record && $type eq 'del') {
  1487. db_log_info($db, "Auth recrod for ip: $ip mac: $mac not found. Dhcp request type: $type");
  1488. return;
  1489. }
  1490. # Если запись не найдена и тип 'add'/'old' — создаём
  1491. if (!$auth_record && ($type eq 'add' || $type eq 'old')) {
  1492. my $res_id = resurrection_auth($db, $dhcp_record);
  1493. if (!$res_id) {
  1494. db_log_error($db, "Error creating an ip address record for ip=$ip and mac=$mac!");
  1495. return;
  1496. }
  1497. $auth_record = get_record_sql($db, "SELECT * FROM user_auth WHERE id = ?", $res_id);
  1498. db_log_info($db, "Check for new auth. Found id: $res_id", $res_id);
  1499. }
  1500. if (!$auth_record || !$auth_record->{id}) {
  1501. db_log_error($db, "Record not found/created for ip: $ip mac: $mac not found. Dhcp request type: $type!");
  1502. return;
  1503. }
  1504. my $auth_id = $auth_record->{id};
  1505. my $auth_ou_id = $auth_record->{ou_id};
  1506. $dhcp_record->{auth_id} = $auth_id;
  1507. $dhcp_record->{auth_ou_id} = $auth_ou_id;
  1508. update_dns_record_by_dhcp($db, $dhcp_record, $auth_record);
  1509. # --- Обработка ADD ---
  1510. if ($type eq 'add' && $dhcp_record->{hostname_utf8}) {
  1511. my $auth_rec = {
  1512. dhcp_hostname => $dhcp_record->{hostname_utf8},
  1513. dhcp_time => $dhcp_event_time,
  1514. arp_found => $dhcp_event_time,
  1515. created_by => 'dhcp',
  1516. };
  1517. db_log_verbose($db, "Add lease by dhcp event for dynamic clients id: $auth_id ip: $ip", $auth_id);
  1518. update_record($db, 'user_auth', $auth_rec, 'id = ?', $auth_id);
  1519. }
  1520. # --- Обработка OLD ---
  1521. if ($type eq 'old') {
  1522. my $auth_rec = {
  1523. dhcp_action => $type,
  1524. dhcp_time => $dhcp_event_time,
  1525. created_by => 'dhcp',
  1526. arp_found => $dhcp_event_time,
  1527. };
  1528. db_log_verbose($db, "Update lease by dhcp event for dynamic clients id: $auth_id ip: $ip", $auth_id);
  1529. update_record($db, 'user_auth', $auth_rec, 'id = ?', $auth_id);
  1530. }
  1531. # --- Обработка DEL ---
  1532. if ($type eq 'del' && $auth_id) {
  1533. if ($auth_record->{dhcp_time} =~ /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/) {
  1534. my $d_time = mktime($6, $5, $4, $3, $2 - 1, $1 - 1900);
  1535. if (time() - $d_time > 60 && (is_dynamic_ou($db, $auth_ou_id) || is_default_ou($db, $auth_ou_id))) {
  1536. db_log_info($db, "Remove user ip record by dhcp release event for dynamic clients id: $auth_id ip: $ip", $auth_id);
  1537. my $auth_rec = {
  1538. dhcp_action => $type,
  1539. dhcp_time => $dhcp_event_time,
  1540. };
  1541. update_record($db, 'user_auth', $auth_rec, 'id = ?', $auth_id);
  1542. # Удаляем запись, если она из динамического или дефолтного пула
  1543. if (is_default_ou($db, $auth_ou_id) || (is_dynamic_ou($db, $auth_ou_id) && $auth_record->{dynamic})) {
  1544. delete_user_auth($db, $auth_id);
  1545. # Проверяем, остались ли другие записи у пользователя
  1546. my $u_count = get_record_sql($db,
  1547. "SELECT COUNT(*) AS cnt FROM user_auth WHERE deleted = 0 AND user_id = ?",
  1548. $auth_record->{user_id}
  1549. );
  1550. if ($u_count && $u_count->{cnt} == 0) {
  1551. delete_user($db, $auth_record->{user_id});
  1552. }
  1553. }
  1554. }
  1555. }
  1556. }
  1557. # --- Пропуск логирования для hotspot или ignore_update_dhcp_event ---
  1558. if ($dhcp_record->{hotspot} && $ignore_hotspot_dhcp_log) {
  1559. return $dhcp_record;
  1560. }
  1561. if ($ignore_update_dhcp_event && $type eq 'old') {
  1562. return $dhcp_record;
  1563. }
  1564. # --- Логируем событие ---
  1565. my $dhcp_log = {
  1566. auth_id => $auth_id // 0,
  1567. ip => $ip,
  1568. ip_int => $ip_aton,
  1569. mac => $mac,
  1570. action => $type,
  1571. dhcp_hostname => $client_hostname,
  1572. ts => $dhcp_event_time,
  1573. circuit_id => $circuit_id,
  1574. client_id => $client_id,
  1575. remote_id => $remote_id,
  1576. };
  1577. insert_record($db, 'dhcp_log', $dhcp_log);
  1578. return $dhcp_record;
  1579. }
  1580. 1;
  1581. }