common.pm 67 KB

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