database.pm 92 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659
  1. package eyelib::database;
  2. #
  3. # Copyright (C) Roman Dmitiriev, 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 DateTime;
  19. use POSIX qw(mktime ctime strftime);
  20. use File::Temp qw(tempfile);
  21. use DBI;
  22. our @ISA = qw(Exporter);
  23. our @EXPORT = qw(
  24. batch_db_sql
  25. reconnect_db
  26. batch_db_sql_cached
  27. batch_db_sql_csv
  28. db_log_warning
  29. db_log_debug
  30. db_log_error
  31. db_log_info
  32. db_log_verbose
  33. delete_record
  34. record_to_txt
  35. unblock_user
  36. do_sql
  37. Get_Variable
  38. Set_Variable
  39. Del_Variable
  40. get_count_records
  41. get_record_sql
  42. get_records_sql
  43. get_device_by_ip
  44. get_diff_rec
  45. get_id_record
  46. get_new_user_id
  47. is_hotspot
  48. GetNowTime
  49. GetUnixTimeByStr
  50. GetTimeStrByUnixTime
  51. get_option
  52. process_dhcp_request
  53. get_subnets_ref
  54. init_db
  55. init_option
  56. insert_record
  57. apply_device_lock
  58. set_lock_discovery
  59. unset_lock_discovery
  60. find_mac_in_subnet
  61. IpToStr
  62. unbind_ports
  63. resurrection_auth
  64. new_auth
  65. StrToIp
  66. get_first_line
  67. is_ad_computer
  68. get_dynamic_ou
  69. is_dynamic_ou
  70. get_default_ou
  71. is_default_ou
  72. update_dns_record
  73. update_dns_record_by_dhcp
  74. create_dns_cname
  75. delete_dns_cname
  76. create_dns_hostname
  77. delete_dns_hostname
  78. create_dns_ptr
  79. delete_dns_ptr
  80. update_record
  81. delete_user_auth
  82. delete_user
  83. delete_device
  84. write_db_log
  85. set_changed
  86. recalc_quotes
  87. clean_variables
  88. get_office_subnet
  89. get_notify_subnet
  90. $add_rules
  91. $L_WARNING
  92. $L_INFO
  93. $L_DEBUG
  94. $L_ERROR
  95. $L_VERBOSE
  96. );
  97. BEGIN
  98. {
  99. #---------------------------------------------------------------------------------------------------------------
  100. our $add_rules;
  101. our $L_ERROR = 0;
  102. our $L_WARNING = 1;
  103. our $L_INFO = 2;
  104. our $L_VERBOSE = 3;
  105. our $L_DEBUG = 255;
  106. our %acl_fields = (
  107. 'ip' => '1',
  108. 'ip_int' => '1',
  109. 'enabled'=>'1',
  110. 'dhcp'=>'1',
  111. 'filter_group_id'=>'1',
  112. 'deleted'=>'1',
  113. 'dhcp_acl'=>'1',
  114. 'queue_id'=>'1',
  115. 'mac'=>'1',
  116. 'blocked'=>'1'
  117. );
  118. our %dhcp_fields = (
  119. 'ip' => '1',
  120. 'dhcp_acl'=>'1',
  121. 'dhcp_option_set'=>'1',
  122. 'dhcp'=>'1',
  123. 'deleted'=>'1',
  124. 'mac'=>'1',
  125. );
  126. our %dns_fields = (
  127. 'ip' => '1',
  128. 'dns_name'=>'1',
  129. 'dns_ptr_only'=>'1',
  130. 'alias'=>'1',
  131. );
  132. #---------------------------------------------------------------------------------------------------------------
  133. sub StrToIp{
  134. return unpack('N',pack('C4',split(/\./,$_[0])));
  135. }
  136. #---------------------------------------------------------------------------------------------------------------
  137. sub IpToStr{
  138. my $nIP = shift;
  139. my $res = (($nIP>>24) & 255) .".". (($nIP>>16) & 255) .".". (($nIP>>8) & 255) .".". ($nIP & 255);
  140. return $res;
  141. }
  142. #---------------------------------------------------------------------------------------------------------------
  143. sub batch_db_sql {
  144. my $db=shift;
  145. my $batch_sql=shift;
  146. return if (!$db);
  147. $db->{AutoCommit} = 0;
  148. my $apply = 0;
  149. my $sth;
  150. my @msg = ();
  151. if (ref($batch_sql) eq 'ARRAY') { @msg = @$batch_sql; } else { @msg = split("\n",$batch_sql); }
  152. foreach my $sSQL (@msg) {
  153. next if (!$sSQL);
  154. $sth = $db->prepare($sSQL) or die "Unable to prepare $sSQL" . $db->errstr;
  155. $sth->execute() or die "Unable to prepare $sSQL" . $db->errstr;
  156. $apply = 1;
  157. }
  158. if ($apply) { $sth->finish(); }
  159. $db->{AutoCommit} = 1;
  160. }
  161. #---------------------------------------------------------------------------------------------------------------
  162. sub batch_db_sql_cached {
  163. my $db = DBI->connect("dbi:$config_ref{DBTYPE}:database=$DBNAME;host=$DBHOST","$DBUSER","$DBPASS", { RaiseError => 0, AutoCommit => 0 });
  164. if ( !defined $db ) { die "Cannot connect to $config_ref{DBTYPE} server: $DBI::errstr\n"; }
  165. if ($config_ref{DBTYPE} eq 'mysql') {
  166. $db->do('SET NAMES utf8mb4');
  167. $db->{'mysql_enable_utf8'} = 1;
  168. }
  169. my $table= shift;
  170. my $batch_sql=shift;
  171. return if (!$db);
  172. my @msg = ();
  173. if (ref($batch_sql) eq 'ARRAY') { @msg = @$batch_sql; } else { @msg = split("\n",$batch_sql); }
  174. my $sth = $db->prepare_cached($table) or die "Unable to prepare:" . $db->errstr;
  175. foreach my $sSQL (@msg) {
  176. next if (!$sSQL);
  177. $sth->execute(@$sSQL) or die "Unable to execute:" . $db->errstr;
  178. }
  179. $db->commit();
  180. $db->disconnect();
  181. }
  182. #---------------------------------------------------------------------------------------------------------------
  183. sub batch_db_sql_csv {
  184. my $db;
  185. if ($config_ref{DBTYPE} eq 'mysql') {
  186. $db = DBI->connect("dbi:$config_ref{DBTYPE}:database=$DBNAME;host=$DBHOST","$DBUSER","$DBPASS", { RaiseError => 1, mysql_local_infile=> 1 });
  187. } else {
  188. $db = DBI->connect("dbi:$config_ref{DBTYPE}:database=$DBNAME;host=$DBHOST","$DBUSER","$DBPASS", { RaiseError => 1 });
  189. }
  190. if ( !defined $db ) { die "Cannot connect to $config_ref{DBTYPE} server: $DBI::errstr\n"; }
  191. return if (!$db);
  192. if ($config_ref{DBTYPE} eq 'mysql') {
  193. $db->do('SET NAMES utf8mb4');
  194. $db->{'mysql_enable_utf8'} = 1;
  195. }
  196. my $table= shift;
  197. my $data = shift;
  198. my $fh = File::Temp->new(UNLINK=>1);
  199. my $fname = $fh->filename;
  200. binmode($fh,':utf8');
  201. foreach my $row (@$data) {
  202. next if (!$row);
  203. my @tmp = @$row;
  204. my $values = 'NULL';
  205. for (my $i = 0; $i <@tmp ; $i++) {
  206. $values.=',"'.$tmp[$i].'"';
  207. }
  208. $values =~s/,$//;
  209. print $fh $values."\r\n";
  210. }
  211. close $fh;
  212. my $query = qq{ LOAD DATA LOCAL INFILE '$fname' INTO TABLE $table FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\r\n'; };
  213. $db->do($query);
  214. $db->disconnect;
  215. File::Temp::cleanup();
  216. }
  217. #---------------------------------------------------------------------------------------------------------------
  218. sub reconnect_db {
  219. my $db_ref = shift;
  220. # Если соединение активно, ничего не делаем
  221. if ($$db_ref && $$db_ref->ping) {
  222. return 1;
  223. }
  224. # Переподключаемся
  225. eval {
  226. # Закрываем старое соединение если есть
  227. if ($$db_ref) {
  228. $$db_ref->disconnect;
  229. $$db_ref = undef;
  230. }
  231. # Создаем новое соединение
  232. $$db_ref = init_db();
  233. # Проверяем что соединение установлено
  234. unless ($$db_ref && $$db_ref->ping) {
  235. die "Failed to establish database connection";
  236. }
  237. 1; # возвращаем истину при успехе
  238. } or do {
  239. my $error = $@ || 'Unknown error';
  240. warn "Database reconnection failed: $error";
  241. $$db_ref = undef;
  242. return 0;
  243. };
  244. return 1;
  245. }
  246. #---------------------------------------------------------------------------------------------------------------
  247. sub do_sql {
  248. my ($db, $sql, @bind_values) = @_;
  249. return 0 unless $db;
  250. return 0 unless $sql;
  251. unless (reconnect_db(\$db)) {
  252. log_error("No database connection available for SQL: $sql");
  253. return 0;
  254. }
  255. # Логируем не-SELECT-запросы
  256. log_debug( $sql . (@bind_values ? ' | bind: [' . join(', ', map { defined $_ ? $_ : 'undef' } @bind_values) . ']' : '')) unless $sql =~ /^select /i;
  257. # Подготовка запроса
  258. my $sth = $db->prepare($sql) or do {
  259. log_error("Unable to prepare SQL [$sql]: " . $db->errstr);
  260. return 0;
  261. };
  262. # Выполнение запроса
  263. my $rv;
  264. if (@bind_values) {
  265. $rv = $sth->execute(@bind_values) or do {
  266. log_error("Unable to execute SQL [$sql] with bind: [" . join(', ', map { defined $_ ? $_ : 'undef' } @bind_values) . "]: " . $sth->errstr);
  267. return 0;
  268. };
  269. } else {
  270. $rv = $sth->execute() or do {
  271. log_error("Unable to execute SQL [$sql]: " . $sth->errstr);
  272. return 0;
  273. };
  274. }
  275. # Обработка результатов по типу запроса
  276. if ($sql =~ /^insert/i) {
  277. my $id;
  278. if ($config_ref{DBTYPE} and $config_ref{DBTYPE} eq 'mysql') {
  279. $id = $sth->{mysql_insertid};
  280. } else {
  281. ($id) = $db->selectrow_array("SELECT lastval()");
  282. }
  283. $sth->finish();
  284. return $id || 0; # Возвращаем ID или 0 если ID нет
  285. }
  286. elsif ($sql =~ /^select /i) {
  287. my $data = $sth->fetchall_arrayref({});
  288. $sth->finish();
  289. return $data; # возвращаем ссылку на массив
  290. }
  291. else {
  292. # UPDATE, DELETE, CREATE, ALTER и т.д.
  293. $sth->finish();
  294. return 1;
  295. }
  296. }
  297. #---------------------------------------------------------------------------------------------------------------
  298. sub get_first_line {
  299. my $msg = shift;
  300. if (!$msg) { return; }
  301. if ($msg=~ /(.*)(\n|\<br\>)/) {
  302. $msg = $1 if ($1);
  303. chomp($msg);
  304. }
  305. return $msg;
  306. }
  307. #---------------------------------------------------------------------------------------------------------------
  308. sub write_db_log {
  309. my $db=shift;
  310. my $msg=shift;
  311. my $level = shift || $L_VERBOSE;
  312. my $auth_id = shift || 0;
  313. return if (!$db);
  314. return if (!$msg);
  315. $msg=~s/[\'\"]//g;
  316. my $db_log = 0;
  317. # Переподключение
  318. unless (reconnect_db(\$db)) {
  319. log_error("No database connection available");
  320. $db_log = 0;
  321. }
  322. if ($level eq $L_ERROR and $log_level >= $L_ERROR) { log_error($msg); $db_log = 1; }
  323. if ($level eq $L_WARNING and $log_level >= $L_WARNING) { log_warning($msg); $db_log = 1; }
  324. if ($level eq $L_INFO and $log_level >= $L_INFO) { log_info($msg); $db_log = 1; }
  325. if ($level eq $L_VERBOSE and $log_level >= $L_VERBOSE) { log_verbose($msg); $db_log = 1; }
  326. if ($level eq $L_DEBUG and $log_level >= $L_DEBUG) { log_debug($msg); return; }
  327. if ($db_log) {
  328. #my $new_id = do_sql($dbh, 'INSERT INTO User_list (login) VALUES (?)', 'Ivan');
  329. do_sql($db,'INSERT INTO worklog(customer,message,level,auth_id,ip) VALUES( ?, ?, ?, ?, ?)',$MY_NAME,$msg,$level,$auth_id,$config_ref{self_ip});
  330. }
  331. }
  332. #---------------------------------------------------------------------------------------------------------------
  333. sub db_log_debug {
  334. my $db = shift;
  335. my $msg = shift;
  336. my $id = shift;
  337. if ($debug) { log_debug($msg); }
  338. }
  339. #---------------------------------------------------------------------------------------------------------------
  340. sub db_log_error {
  341. my $db = shift;
  342. my $msg = shift;
  343. if ($log_level >= $L_ERROR) {
  344. sendEmail("ERROR! ".get_first_line($msg),$msg,1);
  345. write_db_log($db,$msg,$L_ERROR);
  346. }
  347. }
  348. #---------------------------------------------------------------------------------------------------------------
  349. sub db_log_info {
  350. my $db = shift;
  351. my $msg = shift;
  352. my $id = shift;
  353. if ($log_level >= $L_INFO) { write_db_log($db,$msg,$L_INFO,$id); }
  354. }
  355. #---------------------------------------------------------------------------------------------------------------
  356. sub db_log_verbose {
  357. my $db = shift;
  358. my $msg = shift;
  359. my $id = shift;
  360. if ($log_level >= $L_VERBOSE) { write_db_log($db,$msg,$L_VERBOSE,$id); }
  361. }
  362. #---------------------------------------------------------------------------------------------------------------
  363. sub db_log_warning {
  364. my $db = shift;
  365. my $msg = shift;
  366. my $id = shift;
  367. if ($log_level >= $L_WARNING) { write_db_log($db,$msg,$L_WARNING,$id); }
  368. }
  369. #---------------------------------------------------------------------------------------------------------------
  370. sub init_db {
  371. # Create new database handle. If we can't connect, die()
  372. my $db = DBI->connect("dbi:$config_ref{DBTYPE}:database=$DBNAME;host=$DBHOST","$DBUSER","$DBPASS", { RaiseError => 0, AutoCommit => 1 });
  373. if ( !defined $db ) { die "Cannot connect to mySQL server: $DBI::errstr\n"; }
  374. if ($config_ref{DBTYPE} eq 'mysql') {
  375. $db->do('SET NAMES utf8mb4');
  376. $db->{'mysql_enable_utf8'} = 1;
  377. }
  378. return $db;
  379. }
  380. #---------------------------------------------------------------------------------------------------------------
  381. sub get_count_records {
  382. my $db = shift;
  383. my $table = shift;
  384. my $filter = shift;
  385. my $result = 0;
  386. return $result if (!$db);
  387. return $result if (!$table);
  388. my $sSQL='SELECT COUNT(*) as rec_cnt FROM '.$table;
  389. if ($filter) { $sSQL=$sSQL." WHERE ".$filter; }
  390. my $record = get_record_sql($db,$sSQL);
  391. if ($record->{rec_cnt}) { $result = $record->{rec_cnt}; }
  392. return $result;
  393. }
  394. #---------------------------------------------------------------------------------------------------------------
  395. sub get_id_record {
  396. my $db = shift;
  397. my $table = shift;
  398. my $filter = shift;
  399. my $result = 0;
  400. return $result if (!$db);
  401. return $result if (!$table);
  402. my $record = get_record_sql($db,"SELECT id FROM $table WHERE $filter");
  403. if ($record->{id}) { $result = $record->{id}; }
  404. return $result;
  405. }
  406. #---------------------------------------------------------------------------------------------------------------
  407. sub get_records_sql {
  408. my $db = shift;
  409. my $table = shift;
  410. my @result;
  411. return @result if (!$db);
  412. return @result if (!$table);
  413. unless (reconnect_db(\$db)) {
  414. log_error("No database connection available");
  415. return 0;
  416. }
  417. my $list = $db->prepare( $table ) or die "Unable to prepare $table:" . $db->errstr;
  418. $list->execute() or die "Unable to execute $table: " . $db->errstr;
  419. while(my $row_ref = $list->fetchrow_hashref()) { push(@result,$row_ref); }
  420. $list->finish();
  421. return @result;
  422. }
  423. #---------------------------------------------------------------------------------------------------------------
  424. sub get_record_sql {
  425. my $db = shift;
  426. my $tsql = shift;
  427. my @result;
  428. return @result if (!$db);
  429. return @result if (!$tsql);
  430. $tsql.=' LIMIT 1';
  431. my $row_ref;
  432. # Переподключение
  433. unless (reconnect_db(\$db)) {
  434. log_error("No database connection available");
  435. return;
  436. }
  437. eval {
  438. my $list = $db->prepare($tsql) or die "Unable to prepare $tsql: " . $db->errstr;
  439. $list->execute() or die "Unable to execute $tsql: " . $db->errstr;
  440. $row_ref = $list->fetchrow_hashref();
  441. $list->finish();
  442. };
  443. if ($@) {
  444. log_error("Error apply sql: $tsql err:".$@);
  445. die "Error apply sql: $tsql";
  446. }
  447. return $row_ref;
  448. }
  449. #---------------------------------------------------------------------------------------------------------------
  450. sub unbind_ports {
  451. my $db = shift;
  452. my $device_id = shift;
  453. return if (!$db);
  454. return if (!$device_id);
  455. my @target = get_records_sql($db, "SELECT U.target_port_id,U.id FROM device_ports U WHERE U.device_id=".$device_id);
  456. foreach my $row (@target) {
  457. do_sql($db, "UPDATE device_ports SET target_port_id=0 WHERE target_port_id=".$row->{id});
  458. do_sql($db, "UPDATE device_ports SET target_port_id=0 WHERE id=".$row->{id});
  459. }
  460. }
  461. #---------------------------------------------------------------------------------------------------------------
  462. sub get_diff_rec {
  463. my $db = shift;
  464. my $table = shift;
  465. my $value = shift;
  466. my $filter = shift;
  467. return if (!$db);
  468. return if (!$table);
  469. return if (!$filter);
  470. my $old_value = get_record_sql($db,"SELECT * FROM $table WHERE $filter");
  471. my $result;
  472. foreach my $field (keys %$value) {
  473. if (!$value->{$field}) { $value->{$field}=''; }
  474. if (!$old_value->{$field}) { $old_value->{$field}=''; }
  475. if ($value->{$field}!~/^$old_value->{$field}$/) { $result->{$field} = "$value->{$field} [ old: " . $old_value->{$field} . "]"; }
  476. }
  477. return hast_to_txt($result);
  478. }
  479. #---------------------------------------------------------------------------------------------------------------
  480. sub get_dns_name {
  481. my $db = shift;
  482. my $id = shift;
  483. my $auth_record = get_record_sql($db,"SELECT dns_name FROM User_auth WHERE deleted=0 AND id=".$id);
  484. if ($auth_record and $auth_record->{'dns_name'}) { return $auth_record->{'dns_name'}; }
  485. return;
  486. }
  487. #---------------------------------------------------------------------------------------------------------------
  488. sub update_record {
  489. my $db = shift;
  490. my $table = shift;
  491. my $record = shift;
  492. my $filter = shift;
  493. return if (!$db);
  494. return if (!$table);
  495. return if (!$filter);
  496. # Переподключение
  497. unless (reconnect_db(\$db)) {
  498. log_error("No database connection available");
  499. return;
  500. }
  501. my $old_record = get_record_sql($db,"SELECT * FROM $table WHERE $filter");
  502. my $diff='';
  503. my $change_str='';
  504. my $found_changed=0;
  505. my $rec_id = 0;
  506. my $dns_changed = 0;
  507. if ($table eq "User_auth") {
  508. $rec_id = $old_record->{'id'} if ($old_record->{'id'});
  509. #disable update field 'created_by'
  510. if ($old_record->{'created_by'} and exists ($record->{'created_by'})) { delete $record->{'created_by'}; }
  511. foreach my $field (keys %$record) {
  512. if (exists $acl_fields{$field}) { $record->{changed}="1"; }
  513. if (exists $dhcp_fields{$field}) { $record->{dhcp_changed}="1"; }
  514. if (exists $dns_fields{$field}) { $dns_changed=1; }
  515. }
  516. }
  517. foreach my $field (keys %$record) {
  518. if (!defined $record->{$field}) { $record->{$field}=''; }
  519. if (!defined $old_record->{$field}) { $old_record->{$field}=''; }
  520. my $old_value = quotemeta($old_record->{$field});
  521. my $new_value = $record->{$field};
  522. $new_value=~s/\'//g;
  523. $new_value=~s/\"//g;
  524. if ($new_value!~/^$old_value$/) {
  525. $diff = $diff." $field => $record->{$field} (old: $old_record->{$field}),";
  526. $change_str = $change_str." `$field`=".$db->quote($record->{$field}).",";
  527. $found_changed++;
  528. }
  529. }
  530. if ($found_changed) {
  531. $change_str=~s/\,$//;
  532. $diff=~s/\,$//;
  533. if ($table eq 'User_auth') {
  534. $change_str .= ", `changed_time`='".GetNowTime()."'";
  535. if ($dns_changed) {
  536. my $del_dns;
  537. if ($old_record->{'dns_name'} and $old_record->{'ip'} and !$old_record->{'dns_ptr_only'} and $old_record->{'dns_name'}!~/\.$/) {
  538. $del_dns->{'name_type'}='A';
  539. $del_dns->{'name'}=$old_record->{'dns_name'};
  540. $del_dns->{'value'}=$old_record->{'ip'};
  541. $del_dns->{'type'}='del';
  542. if ($rec_id) { $del_dns->{'auth_id'}=$rec_id; }
  543. insert_record($db,'dns_queue',$del_dns);
  544. }
  545. if ($old_record->{'dns_name'} and $old_record->{'ip'} and $old_record->{'dns_ptr_only'} and $old_record->{'dns_name'}!~/\.$/) {
  546. $del_dns->{'name_type'}='PTR';
  547. $del_dns->{'name'}=$old_record->{'dns_name'};
  548. $del_dns->{'value'}=$old_record->{'ip'};
  549. $del_dns->{'type'}='del';
  550. if ($rec_id) { $del_dns->{'auth_id'}=$rec_id; }
  551. insert_record($db,'dns_queue',$del_dns);
  552. }
  553. my $new_dns;
  554. my $dns_rec_ip = $old_record->{ip};
  555. my $dns_rec_name = $old_record->{dns_name};
  556. if ($record->{'dns_name'}) { $dns_rec_name = $record->{'dns_name'}; }
  557. if ($record->{'ip'}) { $dns_rec_ip = $record->{'ip'}; }
  558. if ($dns_rec_name and $dns_rec_ip and !$record->{'dns_ptr_only'} and $record->{'dns_name'}!~/\.$/) {
  559. $new_dns->{'name_type'}='A';
  560. $new_dns->{'name'}=$dns_rec_name;
  561. $new_dns->{'value'}=$dns_rec_ip;
  562. $new_dns->{'type'}='add';
  563. if ($rec_id) { $new_dns->{'auth_id'}=$rec_id; }
  564. insert_record($db,'dns_queue',$new_dns);
  565. }
  566. if ($dns_rec_name and $dns_rec_ip and $record->{'dns_ptr_only'} and $record->{'dns_name'}!~/\.$/) {
  567. $new_dns->{'name_type'}='PTR';
  568. $new_dns->{'name'}=$dns_rec_name;
  569. $new_dns->{'value'}=$dns_rec_ip;
  570. $new_dns->{'type'}='add';
  571. if ($rec_id) { $new_dns->{'auth_id'}=$rec_id; }
  572. insert_record($db,'dns_queue',$new_dns);
  573. }
  574. }
  575. }
  576. if ($table eq 'User_auth_alias') {
  577. if ($dns_changed) {
  578. my $del_dns;
  579. if ($old_record->{'alias'} and $old_record->{'alias'}!~/\.$/) {
  580. $del_dns->{'name_type'}='CNAME';
  581. $del_dns->{'name'}=$old_record->{'alias'};
  582. $del_dns->{'type'}='del';
  583. $del_dns->{'value'}=get_dns_name($db,$old_record->{auth_id});
  584. $del_dns->{'auth_id'}=$old_record->{auth_id};
  585. insert_record($db,'dns_queue',$del_dns);
  586. }
  587. my $new_dns;
  588. my $dns_rec_name = $old_record->{alias};
  589. if ($record->{'alias'}) { $dns_rec_name = $record->{'alias'}; }
  590. if ($dns_rec_name and $record->{'alias'}!~/\.$/) {
  591. $new_dns->{'name_type'}='CNAME';
  592. $new_dns->{'name'}=$dns_rec_name;
  593. $new_dns->{'type'}='add';
  594. $new_dns->{'value'}=get_dns_name($db,$old_record->{auth_id});
  595. $new_dns->{'auth_id'}=$rec_id;
  596. insert_record($db,'dns_queue',$new_dns);
  597. }
  598. }
  599. }
  600. my $sSQL = "UPDATE $table SET $change_str WHERE $filter";
  601. db_log_debug($db,'Change table '.$table.' for '.$filter.' set: '.$diff, $rec_id);
  602. do_sql($db,$sSQL);
  603. }
  604. return 1;
  605. }
  606. #---------------------------------------------------------------------------------------------------------------
  607. sub insert_record {
  608. my $db = shift;
  609. my $table = shift;
  610. my $record = shift;
  611. return if (!$db);
  612. return if (!$table);
  613. my $change_str='';
  614. my $fields='';
  615. my $values='';
  616. my $new_str='';
  617. my $rec_id = 0;
  618. my $dns_changed = 0;
  619. # Переподключение
  620. unless (reconnect_db(\$db)) {
  621. log_error("No database connection available");
  622. return;
  623. }
  624. if ($table eq "User_auth") {
  625. foreach my $field (keys %$record) {
  626. if (exists $acl_fields{$field}) { $record->{changed}="1"; }
  627. if (exists $dhcp_fields{$field}) { $record->{dhcp_changed}="1"; }
  628. if (exists $dns_fields{$field}) { $dns_changed=1; }
  629. }
  630. }
  631. foreach my $field (keys %$record) {
  632. if (!defined $record->{$field}) { $record->{$field}=''; }
  633. my $new_value = $record->{$field};
  634. $new_value=~s/\'//g;
  635. $new_value=~s/\"//g;
  636. $record->{$field} = $new_value;
  637. $fields = $fields."`$field`,";
  638. $values = $values." ".$db->quote($record->{$field}).",";
  639. $new_str = $new_str." $field => $record->{$field},";
  640. }
  641. $fields=~s/,$//;
  642. $values=~s/,$//;
  643. $new_str=~s/,$//;
  644. my $sSQL = "INSERT INTO $table($fields) VALUES($values)";
  645. my $result = do_sql($db,$sSQL);
  646. if ($result) {
  647. $rec_id = $result if ($table eq "User_auth");
  648. $new_str='id: '.$result.' '.$new_str;
  649. if ($table eq 'User_auth_alias' and $dns_changed) {
  650. if ($record->{'alias'} and $record->{'alias'}!~/\.$/) {
  651. my $add_dns;
  652. $add_dns->{'name_type'}='CNAME';
  653. $add_dns->{'name'}=$record->{'alias'};
  654. $add_dns->{'value'}=get_dns_name($db,$record->{'auth_id'});
  655. $add_dns->{'type'}='add';
  656. $add_dns->{'auth_id'}=$record->{'auth_id'};
  657. insert_record($db,'dns_queue',$add_dns);
  658. }
  659. }
  660. if ($table eq 'User_auth' and $dns_changed) {
  661. if ($record->{'dns_name'} and $record->{'ip'} and $dns_changed and !$record->{'dns_ptr_only'} and $record->{'dns_name'}!~/\.$/) {
  662. my $add_dns;
  663. $add_dns->{'name_type'}='A';
  664. $add_dns->{'name'}=$record->{'dns_name'};
  665. $add_dns->{'value'}=$record->{'ip'};
  666. $add_dns->{'type'}='add';
  667. $add_dns->{'auth_id'}=$result;
  668. insert_record($db,'dns_queue',$add_dns);
  669. }
  670. if ($record->{'dns_name'} and $record->{'ip'} and $dns_changed and $record->{'dns_ptr_only'} and $record->{'dns_name'}!~/\.$/) {
  671. my $add_dns;
  672. $add_dns->{'name_type'}='PTR';
  673. $add_dns->{'name'}=$record->{'dns_name'};
  674. $add_dns->{'value'}=$record->{'ip'};
  675. $add_dns->{'type'}='add';
  676. $add_dns->{'auth_id'}=$result;
  677. insert_record($db,'dns_queue',$add_dns);
  678. }
  679. }
  680. }
  681. db_log_debug($db,'Add record to table '.$table.' '.$new_str,$rec_id);
  682. return $result;
  683. }
  684. #---------------------------------------------------------------------------------------------------------------
  685. sub delete_record {
  686. my $db = shift;
  687. my $table = shift;
  688. my $filter = shift;
  689. return if (!$db);
  690. return if (!$table);
  691. return if (!$filter);
  692. my $rec_id = 0;
  693. # Переподключение
  694. unless (reconnect_db(\$db)) {
  695. log_error("No database connection available");
  696. return;
  697. }
  698. my $old_record = get_record_sql($db,"SELECT * FROM $table WHERE $filter");
  699. my $diff='';
  700. foreach my $field (keys %$old_record) {
  701. if (!$old_record->{$field}) { $old_record->{$field}=''; }
  702. $diff = $diff." $field => $old_record->{$field},";
  703. }
  704. $diff=~s/,$//;
  705. if ($table eq 'User_auth') {
  706. $rec_id = $old_record->{'id'} if ($old_record->{'id'});
  707. }
  708. db_log_debug($db,'Delete record from table '.$table.' value: '.$diff, $rec_id);
  709. #never delete user ip record!
  710. if ($table eq 'User_auth') {
  711. my $sSQL = "UPDATE User_auth SET changed=1, deleted=1, changed_time='".GetNowTime()."' WHERE ".$filter;
  712. my $ret = do_sql($db,$sSQL);
  713. if ($old_record->{'dns_name'} and $old_record->{'ip'} and !$old_record->{'dns_ptr_only'} and $old_record->{'dns_name'}!~/\.$/) {
  714. my $del_dns;
  715. $del_dns->{'name_type'}='A';
  716. $del_dns->{'name'}=$old_record->{'dns_name'};
  717. $del_dns->{'value'}=$old_record->{'ip'};
  718. $del_dns->{'type'}='del';
  719. $del_dns->{'auth_id'}=$old_record->{'id'};
  720. insert_record($db,'dns_queue',$del_dns);
  721. }
  722. if ($old_record->{'dns_name'} and $old_record->{'ip'} and $old_record->{'dns_ptr_only'} and $old_record->{'dns_name'}!~/\.$/) {
  723. my $del_dns;
  724. $del_dns->{'name_type'}='PTR';
  725. $del_dns->{'name'}=$old_record->{'dns_name'};
  726. $del_dns->{'value'}=$old_record->{'ip'};
  727. $del_dns->{'type'}='del';
  728. $del_dns->{'auth_id'}=$old_record->{'id'};
  729. insert_record($db,'dns_queue',$del_dns);
  730. }
  731. return $ret;
  732. }
  733. if ($table eq 'User_list' and $old_record->{'permanent'}) { return; }
  734. if ($table eq 'User_auth_alias') {
  735. if ($old_record->{'alias'} and $old_record->{'auth_id'} and $old_record->{'alias'}!~/\.$/) {
  736. my $del_dns;
  737. $del_dns->{'name_type'}='CNAME';
  738. $del_dns->{'name'}=$old_record->{'alias'};
  739. $del_dns->{'value'}=get_dns_name($db,$old_record->{'auth_id'});
  740. $del_dns->{'type'}='del';
  741. $del_dns->{'auth_id'}=$old_record->{'auth_id'};
  742. insert_record($db,'dns_queue',$del_dns);
  743. }
  744. }
  745. my $sSQL = "DELETE FROM ".$table." WHERE ".$filter;
  746. return do_sql($db,$sSQL);
  747. }
  748. #---------------------------------------------------------------------------------------------------------------
  749. sub record_to_txt {
  750. my $db = shift;
  751. my $table = shift;
  752. my $id = shift;
  753. my $record = get_record_sql($db,'SELECT * FROM '.$table.' WHERE id='.$id);
  754. return hash_to_text($record);
  755. }
  756. #---------------------------------------------------------------------------------------------------------------
  757. sub delete_user_auth {
  758. my $db = shift;
  759. my $id = shift;
  760. my $record = get_record_sql($db,'SELECT * FROM User_auth WHERE id='.$id);
  761. my $auth_ident = $record->{ip};
  762. $auth_ident = $auth_ident . '['.$record->{dns_name} .']' if ($record->{dns_name});
  763. $auth_ident = $auth_ident . ' :: '.$record->{comments} if ($record->{dns_name});
  764. my $msg = "";
  765. my $txt_record = hash_to_text($record);
  766. #remove aliases
  767. my @t_User_auth_alias = get_records_sql($db,'SELECT * FROM User_auth_alias WHERE auth_id='.$id);
  768. if (@t_User_auth_alias and scalar @t_User_auth_alias) {
  769. foreach my $row ( @t_User_auth_alias) {
  770. my $alias_txt = record_to_txt($db,'User_auth_alias','id='.$row->{'id'});
  771. if (delete_record($db,'User_auth_alias','id='.$row->{'id'})) {
  772. $msg = "Deleting an alias: ". $alias_txt . "\n::Success!\n" . $msg;
  773. } else {
  774. $msg = "Deleting an alias: ". $alias_txt . "\n::Fail!\n" . $msg;
  775. }
  776. }
  777. }
  778. #remove connections
  779. do_sql($db,'DELETE FROM connections WHERE auth_id='.$id);
  780. #remove user auth record
  781. my $changes = delete_record($db, "User_auth", "id=" . $id);
  782. if ($changes) {
  783. $msg = "Deleting ip-record: ". $txt_record . "\n::Success!\n" . $msg;
  784. } else {
  785. $msg = "Deleting ip-record: ". $txt_record . "\n::Fail!\n" . $msg;
  786. }
  787. $msg = "Deleting user ip record $auth_ident\n\n".$msg;
  788. db_log_warning($db, $msg, $id);
  789. my $send_alert = isNotifyDelete(get_notify_subnet($db,$record->{ip}));
  790. sendEmail("WARN! ".get_first_line($msg),$msg,1) if ($send_alert);
  791. return $changes;
  792. }
  793. #---------------------------------------------------------------------------------------------------------------
  794. sub unblock_user {
  795. my $db = shift;
  796. my $user_id = shift;
  797. my $user_record = get_record_sql($db,'SELECT * FROM User_list WHERE id='.$user_id);
  798. my $user_ident = 'id:'. $user_record->{'id'} . ' '. $user_record->{'login'};
  799. $user_ident = $user_ident . '[' . $user_record->{'fio'} . ']' if ($user_record->{'fio'});
  800. my $msg = "Amnistuyemo blocked by traffic user $user_ident \nInternet access for the user's IP address has been restored:\n";
  801. my @user_auth = get_records_sql($db,'SELECT * FROM User_auth WHERE deleted=0 AND user_id='.$user_id);
  802. my $send_alert = 0;
  803. if (@user_auth and scalar @user_auth) {
  804. foreach my $record (@user_auth) {
  805. $send_alert = ($send_alert or isNotifyUpdate(get_notify_subnet($db,$record->{ip})));
  806. my $auth_ident = $record->{ip};
  807. $auth_ident = $auth_ident . '['.$record->{dns_name} .']' if ($record->{dns_name});
  808. $auth_ident = $auth_ident . ' :: '.$record->{comments} if ($record->{dns_name});
  809. my $new;
  810. $new->{'blocked'}=0;
  811. $new->{'changed'}=1;
  812. my $ret_id = update_record($db,'User_auth',$new,'id='.$record->{'id'});
  813. if ($ret_id) {
  814. $msg = $msg ."\n".$auth_ident;
  815. }
  816. }
  817. }
  818. my $new;
  819. $new->{'blocked'}=0;
  820. my $ret_id = update_record($db,'User_list','id='.$user_id);
  821. if ($ret_id) {
  822. db_log_info($db,$msg);
  823. sendEmail("WARN! ".get_first_line($msg),$msg,1) if ($send_alert);
  824. }
  825. return $ret_id;
  826. }
  827. #---------------------------------------------------------------------------------------------------------------
  828. sub delete_user {
  829. my $db = shift;
  830. my $id = shift;
  831. #remove user record
  832. my $changes = delete_record($db, "User_list", "id=" . $id);
  833. #if fail - exit
  834. if (!$changes) { return; }
  835. #remove auth records
  836. my @t_User_auth = get_records_sql($db,'SELECT * FROM User_auth WHERE user_id='.$id);
  837. if (@t_User_auth and scalar @t_User_auth) {
  838. foreach my $row ( @t_User_auth ) { delete_user_auth($db,$row->{'id'}); }
  839. }
  840. #remove device
  841. my $device = get_record_sql($db, "SELECT * FROM devices WHERE user_id=".$id);
  842. if ($device) { delete_device($db,$device->{'id'}); }
  843. #remove auth assign rules
  844. do_sql($db, "DELETE FROM auth_rules WHERE user_id=$id");
  845. return $changes;
  846. }
  847. #---------------------------------------------------------------------------------------------------------------
  848. sub delete_device {
  849. my $db = shift;
  850. my $id = shift;
  851. #remove user record
  852. my $changes = delete_record($db, "devices", "id=" . $id);
  853. #if fail - exit
  854. if (!$changes) { return; }
  855. unbind_ports($db, $id);
  856. do_sql($db, "DELETE FROM connections WHERE device_id=" . $id);
  857. do_sql($db, "DELETE FROM device_l3_interfaces WHERE device_id=" . $id);
  858. do_sql($db, "DELETE FROM device_ports WHERE device_id=" . $id);
  859. do_sql($db, "DELETE FROM device_filter_instances WHERE device_id=" . $id);
  860. do_sql($db, "DELETE FROM gateway_subnets WHERE device_id=".$id);
  861. return $changes;
  862. }
  863. #---------------------------------------------------------------------------------------------------------------
  864. sub GetNowTime {
  865. my ($sec,$min,$hour,$day,$month,$year,$zone) = localtime(time());
  866. $month += 1;
  867. $year += 1900;
  868. my $now_str=sprintf "%04d-%02d-%02d %02d:%02d:%02d",$year,$month,$day,$hour,$min,$sec;
  869. return $now_str;
  870. }
  871. #---------------------------------------------------------------------------------------------------------------
  872. sub is_hotspot {
  873. my $db = shift;
  874. my $ip = shift;
  875. my $users = new Net::Patricia;
  876. #check hotspot
  877. my @ip_rules = get_records_sql($db,'SELECT * FROM subnets WHERE hotspot=1 AND LENGTH(subnet)>0');
  878. foreach my $row (@ip_rules) { $users->add_string($row->{subnet}); }
  879. if ($users->match_string($ip)) { return 1; }
  880. return 0;
  881. }
  882. #---------------------------------------------------------------------------------------------------------------
  883. sub get_office_subnet {
  884. my $db = shift;
  885. my $ip = shift;
  886. my $subnets = new Net::Patricia;
  887. my @ip_rules = get_records_sql($db,'SELECT * FROM subnets WHERE office=1 AND LENGTH(subnet)>0');
  888. foreach my $row (@ip_rules) { $subnets->add_string($row->{subnet},$row); }
  889. return $subnets->match_string($ip);
  890. }
  891. #---------------------------------------------------------------------------------------------------------------
  892. sub get_notify_subnet {
  893. my $db = shift;
  894. my $ip = shift;
  895. my $notify_flag = get_office_subnet($db,$ip);
  896. if ($notify_flag) { return $notify_flag->{notify}; }
  897. return 0;
  898. }
  899. #---------------------------------------------------------------------------------------------------------------
  900. sub get_new_user_id {
  901. my $db = shift;
  902. my $ip = shift;
  903. my $mac = shift;
  904. my $hostname = shift;
  905. my $result;
  906. #check user rules
  907. $mac = mac_simplify($mac);
  908. $result->{ip} = $ip;
  909. $result->{mac} = mac_splitted($mac);
  910. $result->{dhcp_hostname} = $hostname;
  911. $result->{ou_id}=undef;
  912. $result->{user_id}=undef;
  913. my $hotspot_users = new Net::Patricia;
  914. #check hotspot
  915. my @hotspot_rules = get_records_sql($db,'SELECT * FROM subnets WHERE hotspot=1 AND LENGTH(subnet)>0');
  916. foreach my $row (@hotspot_rules) { $hotspot_users->add_string($row->{subnet},$default_hotspot_ou_id); }
  917. if ($hotspot_users->match_string($ip)) { $result->{ou_id}=$hotspot_users->match_string($ip); return $result; }
  918. #check ip
  919. if (defined $ip and $ip) {
  920. my $users = new Net::Patricia;
  921. #check ip rules
  922. my @ip_rules = get_records_sql($db,'SELECT * FROM auth_rules WHERE type=1 and LENGTH(rule)>0 AND user_id IS NOT NULL');
  923. foreach my $row (@ip_rules) { eval { $users->add_string($row->{rule},$row->{user_id}); }; }
  924. if ($users->match_string($ip)) { $result->{user_id}=$users->match_string($ip); return $result; }
  925. }
  926. #check mac
  927. if (defined $mac and $mac) {
  928. my @user_rules=get_records_sql($db,'SELECT * FROM auth_rules WHERE type=2 AND LENGTH(rule)>0 AND user_id IS NOT NULL');
  929. foreach my $user (@user_rules) {
  930. my $rule = mac_simplify($user->{rule});
  931. if ($mac=~/$rule/i) { $result->{user_id}=$user->{user_id}; return $result; }
  932. }
  933. }
  934. #check hostname
  935. if (defined $hostname and $hostname) {
  936. my @user_rules=get_records_sql($db,'SELECT * FROM auth_rules WHERE type=3 AND LENGTH(rule)>0 AND user_id IS NOT NULL');
  937. foreach my $user (@user_rules) {
  938. if ($hostname=~/$user->{rule}/i) { $result->{user_id}=$user->{user_id}; return $result; }
  939. }
  940. }
  941. #check ou rules
  942. #check ip
  943. if (defined $ip and $ip) {
  944. my $users = new Net::Patricia;
  945. #check ip rules
  946. my @ip_rules = get_records_sql($db,'SELECT * FROM auth_rules WHERE type=1 and LENGTH(rule)>0 AND ou_id IS NOT NULL');
  947. foreach my $row (@ip_rules) { eval { $users->add_string($row->{rule},$row->{ou_id}); }; }
  948. if ($users->match_string($ip)) { $result->{ou_id}=$users->match_string($ip); return $result; }
  949. }
  950. #check mac
  951. if (defined $mac and $mac) {
  952. my @user_rules=get_records_sql($db,'SELECT * FROM auth_rules WHERE type=2 AND LENGTH(rule)>0 AND ou_id IS NOT NULL');
  953. foreach my $user (@user_rules) {
  954. my $rule = mac_simplify($user->{rule});
  955. if ($mac=~/$rule/i) { $result->{ou_id}=$user->{ou_id}; return $result; }
  956. }
  957. }
  958. #check hostname
  959. if (defined $hostname and $hostname) {
  960. my @user_rules=get_records_sql($db,'SELECT * FROM auth_rules WHERE type=3 AND LENGTH(rule)>0 AND ou_id IS NOT NULL');
  961. foreach my $user (@user_rules) {
  962. if ($hostname=~/$user->{rule}/i) { $result->{ou_id}=$user->{ou_id}; return $result; }
  963. }
  964. }
  965. if (!$result->{ou_id}) { $result->{ou_id}=$default_user_ou_id; }
  966. return $result;
  967. }
  968. #---------------------------------------------------------------------------------------------------------------
  969. sub set_changed {
  970. my $db = shift;
  971. my $id = shift;
  972. return if (!$db or !$id);
  973. my $update_record;
  974. $update_record->{changed}=1;
  975. update_record($db,'User_auth',$update_record,"id=$id");
  976. }
  977. #---------------------------------------------------------------------------------------------------------------
  978. sub update_dns_record {
  979. my $hdb = shift;
  980. my $auth_id = shift;
  981. return if (!$config_ref{enable_dns_updates});
  982. # Переподключение
  983. if (!$hdb or !$hdb->ping) { $hdb = init_db(); }
  984. #get domain
  985. my $ad_zone = get_option($hdb,33);
  986. #get dns server
  987. my $ad_dns = get_option($hdb,3);
  988. my $enable_ad_dns_update = ($ad_zone and $ad_dns and $config_ref{enable_dns_updates});
  989. log_debug("Auth id: ".$auth_id);
  990. log_debug("enable_ad_dns_update: ".$enable_ad_dns_update);
  991. log_debug("DNS update flags - zone: ".$ad_zone.", dns: ".$ad_dns.", enable_ad_dns_update: ".$enable_ad_dns_update);
  992. my @dns_queue = get_records_sql($hdb,"SELECT * FROM dns_queue WHERE auth_id=".$auth_id." AND `value`>'' AND `value` NOT LIKE '%.'ORDER BY id ASC");
  993. if (!@dns_queue or !scalar @dns_queue) { return; }
  994. foreach my $dns_cmd (@dns_queue) {
  995. my $fqdn = '';
  996. my $fqdn_ip = '';
  997. my $fqdn_parent = '';
  998. my $static_exists = 0;
  999. my $static_ref = '';
  1000. my $static_ok = 0;
  1001. eval {
  1002. if ($dns_cmd->{name_type}=~/^cname$/i) {
  1003. #skip update unknown domain
  1004. if ($dns_cmd->{name} =~/\.$/ or $dns_cmd->{value} =~/\.$/) { next; }
  1005. $fqdn=lc($dns_cmd->{name});
  1006. $fqdn=~s/\.$ad_zone$//i;
  1007. # $fqdn=~s/\.$//;
  1008. if ($dns_cmd->{value}) {
  1009. $fqdn_parent=lc($dns_cmd->{value});
  1010. $fqdn_parent=~s/\.$ad_zone$//i;
  1011. # $fqdn_parent=~s/\.$//;
  1012. }
  1013. $fqdn = $fqdn.".".$ad_zone;
  1014. $fqdn_parent = $fqdn_parent.".".$ad_zone;
  1015. #remove cname
  1016. if ($dns_cmd->{type} eq 'del') {
  1017. delete_dns_cname($fqdn_parent,$fqdn,$ad_zone,$ad_dns,$hdb);
  1018. }
  1019. #create cname
  1020. if ($dns_cmd->{type} eq 'add') {
  1021. create_dns_cname($fqdn_parent,$fqdn,$ad_zone,$ad_dns,$hdb);
  1022. }
  1023. }
  1024. if ($dns_cmd->{name_type}=~/^a$/i) {
  1025. #skip update unknown domain
  1026. if ($dns_cmd->{name} =~/\.$/ or $dns_cmd->{value} =~/\.$/) { next; }
  1027. $fqdn=lc($dns_cmd->{name});
  1028. $fqdn=~s/\.$ad_zone$//i;
  1029. # $fqdn=~s/\.$//;
  1030. if (!$dns_cmd->{value}) { next; }
  1031. $fqdn_ip=lc($dns_cmd->{value});
  1032. $fqdn = $fqdn.".".$ad_zone;
  1033. #dns update disabled?
  1034. my $maybe_update_dns=( $enable_ad_dns_update and $office_networks->match_string($fqdn_ip) );
  1035. if (!$maybe_update_dns) {
  1036. db_log_info($hdb,"FOUND Auth_id: $auth_id. DNS update disabled.");
  1037. next;
  1038. }
  1039. #get aliases
  1040. my @aliases = get_records_sql($hdb,"SELECT * FROM User_auth_alias WHERE auth_id=".$auth_id);
  1041. #remove A & PTR
  1042. if ($dns_cmd->{type} eq 'del') {
  1043. #remove aliases
  1044. if (@aliases and scalar @aliases) {
  1045. foreach my $alias (@aliases) {
  1046. delete_dns_cname($fqdn,$alias->{alias},$ad_zone,$ad_dns,$hdb) if ($alias->{alias});
  1047. delete_dns_hostname($fqdn,$alias->{alias},$ad_zone,$ad_dns,$hdb) if ($alias->{alias});
  1048. }
  1049. }
  1050. #remove main record
  1051. delete_dns_hostname($fqdn,$fqdn_ip,$ad_zone,$ad_dns,$hdb);
  1052. delete_dns_ptr($fqdn,$fqdn_ip,$ad_zone,$ad_dns,$hdb);
  1053. }
  1054. #create A & PTR
  1055. if ($dns_cmd->{type} eq 'add') {
  1056. my @dns_record=ResolveNames($fqdn,$dns_server);
  1057. $static_exists = (scalar @dns_record>0);
  1058. if ($static_exists) {
  1059. $static_ref = join(' ',@dns_record);
  1060. foreach my $dns_a (@dns_record) {
  1061. if ($dns_a=~/^$fqdn_ip$/) { $static_ok = 1; }
  1062. }
  1063. db_log_debug($hdb,"Dns record for static record $fqdn: $static_ref");
  1064. }
  1065. #skip update if already exists
  1066. if ($static_ok) {
  1067. db_log_debug($hdb,"Static record for $fqdn [$static_ok] correct.");
  1068. next;
  1069. }
  1070. #create record
  1071. create_dns_hostname($fqdn,$fqdn_ip,$ad_zone,$ad_dns,$hdb);
  1072. create_dns_ptr($fqdn,$fqdn_ip,$ad_zone,$ad_dns,$hdb);
  1073. #create aliases
  1074. if (@aliases and scalar @aliases) {
  1075. foreach my $alias (@aliases) {
  1076. create_dns_cname($fqdn,$alias->{alias},$ad_zone,$ad_dns,$hdb) if ($alias->{alias});
  1077. }
  1078. }
  1079. }
  1080. }
  1081. #PTR
  1082. if ($dns_cmd->{name_type}=~/^ptr$/i) {
  1083. $fqdn=lc($dns_cmd->{name});
  1084. $fqdn=~s/\.$ad_zone$//i;
  1085. # $fqdn=~s/\.$//;
  1086. if (!$dns_cmd->{value}) { next; }
  1087. $fqdn_ip=lc($dns_cmd->{value});
  1088. #skip update unknown domain
  1089. if ($fqdn =~/\.$/) { next; }
  1090. $fqdn = $fqdn.".".$ad_zone;
  1091. #dns update disabled?
  1092. my $maybe_update_dns=( $enable_ad_dns_update and $office_networks->match_string($fqdn_ip) );
  1093. if (!$maybe_update_dns) {
  1094. db_log_info($hdb,"FOUND Auth_id: $auth_id. DNS update disabled.");
  1095. next;
  1096. }
  1097. #remove A & PTR
  1098. if ($dns_cmd->{type} eq 'del') {
  1099. #remove main record
  1100. delete_dns_ptr($fqdn,$fqdn_ip,$ad_zone,$ad_dns,$hdb);
  1101. }
  1102. #create A & PTR
  1103. if ($dns_cmd->{type} eq 'add') {
  1104. #create record
  1105. create_dns_ptr($fqdn,$fqdn_ip,$ad_zone,$ad_dns,$hdb);
  1106. }
  1107. }
  1108. };
  1109. if ($@) { log_error("Error dns commands: $@"); }
  1110. }
  1111. }
  1112. #---------------------------------------------------------------------------------------------------------------
  1113. sub is_ad_computer {
  1114. my $hdb = shift;
  1115. my $computer_name = shift;
  1116. if (!$computer_name or $computer_name =~/UNDEFINED/i) { return 0; }
  1117. my $ad_check = get_option($hdb,73);
  1118. if (!$ad_check) { return 1; }
  1119. my $ad_zone = get_option($hdb,33);
  1120. if ($computer_name =~/\./) {
  1121. if ($computer_name!~/\.$ad_zone$/i) {
  1122. db_log_verbose($hdb,"The domain of the computer $computer_name does not match the domain of the organization $ad_zone. Skip update.");
  1123. return 0;
  1124. }
  1125. }
  1126. if ($computer_name =~/^(.+)\./) {
  1127. $computer_name = $1;
  1128. }
  1129. my $ad_computer_name = trim($computer_name).'$';
  1130. my $name_in_cache = get_record_sql($hdb,"SELECT * FROM ad_comp_cache WHERE name='".$computer_name."'");
  1131. if ($name_in_cache) { return 1; }
  1132. my %name_found=do_exec_ref('/usr/bin/getent passwd '.$ad_computer_name);
  1133. if (!$name_found{output} or $name_found{status} ne 0) {
  1134. db_log_verbose($hdb,"The computer ".uc($ad_computer_name)." was not found in the domain $ad_zone. Skip update.");
  1135. return 0;
  1136. }
  1137. do_sql($hdb,"INSERT INTO ad_comp_cache(name) VALUES('".$computer_name."') ON DUPLICATE KEY UPDATE name='".$computer_name."';");
  1138. return 1;
  1139. }
  1140. #---------------------------------------------------------------------------------------------------------------
  1141. sub update_dns_record_by_dhcp {
  1142. my $hdb = shift;
  1143. my $dhcp_record = shift;
  1144. my $auth_record = shift;
  1145. return if (!$config_ref{enable_dns_updates});
  1146. my $ad_zone = get_option($hdb,33);
  1147. my $ad_dns = get_option($hdb,3);
  1148. $update_hostname_from_dhcp = get_option($hdb,46) || 0;
  1149. my $subnets_dhcp = get_subnets_ref($hdb);
  1150. my $enable_ad_dns_update = ($ad_zone and $ad_dns and $update_hostname_from_dhcp);
  1151. log_debug("Dhcp record: ".Dumper($dhcp_record));
  1152. log_debug("Subnets: ".Dumper($subnets_dhcp->{$dhcp_record->{network}->{subnet}}));
  1153. log_debug("enable_ad_dns_update: ".$enable_ad_dns_update);
  1154. log_debug("DNS update flags - zone: ".$ad_zone.",dns: ".$ad_dns.", update_hostname_from_dhcp: ".$update_hostname_from_dhcp.", enable_ad_dns_update: ".$enable_ad_dns_update. ", network dns-update enabled: ".$subnets_dhcp->{$dhcp_record->{network}->{subnet}}->{dhcp_update_hostname});
  1155. my $maybe_update_dns=($enable_ad_dns_update and $subnets_dhcp->{$dhcp_record->{network}->{subnet}}->{dhcp_update_hostname} and (is_ad_computer($hdb,$dhcp_record->{hostname_utf8}) and ($dhcp_record->{type}=~/add/i or $dhcp_record->{type}=~/old/i)));
  1156. if (!$maybe_update_dns) {
  1157. db_log_debug($hdb,"FOUND Auth_id: $auth_record->{id}. DNS update don't needed.");
  1158. return 0;
  1159. }
  1160. log_debug("DNS update enabled.");
  1161. #update dns block
  1162. my $fqdn_static;
  1163. if ($auth_record->{dns_name}) {
  1164. $fqdn_static=lc($auth_record->{dns_name});
  1165. if ($fqdn_static!~/\.$ad_zone$/i) {
  1166. $fqdn_static=~s/\.$//;
  1167. $fqdn_static=lc($fqdn_static.'.'.$ad_zone);
  1168. }
  1169. }
  1170. my $fqdn=lc(trim($dhcp_record->{hostname_utf8}));
  1171. if ($fqdn!~/\.$ad_zone$/i) {
  1172. $fqdn=~s/\.$//;
  1173. $fqdn=lc($fqdn.'.'.$ad_zone);
  1174. }
  1175. db_log_debug($hdb,"FOUND Auth_id: $auth_record->{id} dns_name: $fqdn_static dhcp_hostname: $fqdn");
  1176. #check exists static dns name
  1177. my $static_exists = 0;
  1178. my $dynamic_exists = 0;
  1179. my $static_ok = 0;
  1180. my $dynamic_ok = 0;
  1181. my $static_ref;
  1182. my $dynamic_ref;
  1183. if ($fqdn_static ne '') {
  1184. my @dns_record=ResolveNames($fqdn_static,$dns_server);
  1185. $static_exists = (scalar @dns_record>0);
  1186. if ($static_exists) {
  1187. $static_ref = join(' ',@dns_record);
  1188. foreach my $dns_a (@dns_record) {
  1189. if ($dns_a=~/^$dhcp_record->{ip}$/) { $static_ok = $dns_a; }
  1190. }
  1191. }
  1192. } else { $static_ok = 1; }
  1193. if ($fqdn ne '') {
  1194. my @dns_record=ResolveNames($fqdn,$dns_server);
  1195. $dynamic_exists = (scalar @dns_record>0);
  1196. if ($dynamic_exists) {
  1197. $dynamic_ref = join(' ',@dns_record);
  1198. foreach my $dns_a (@dns_record) {
  1199. if ($dns_a=~/^$dhcp_record->{ip}$/) { $dynamic_ok = $dns_a; }
  1200. }
  1201. }
  1202. }
  1203. db_log_debug($hdb,"Dns record for static record $fqdn_static: $static_ok");
  1204. db_log_debug($hdb,"Dns record for dhcp-hostname $fqdn: $dynamic_ok");
  1205. if ($fqdn_static ne '') {
  1206. if (!$static_ok) {
  1207. db_log_info($hdb,"Static record mismatch! Expected $fqdn_static => $dhcp_record->{ip}, recivied: $static_ref");
  1208. if (!$static_exists) {
  1209. db_log_info($hdb,"Static dns hostname defined but not found. Create it ($fqdn_static => $dhcp_record->{ip})!");
  1210. create_dns_hostname($fqdn_static,$dhcp_record->{ip},$ad_zone,$ad_dns,$hdb);
  1211. }
  1212. } else {
  1213. db_log_debug($hdb,"Static record for $fqdn_static [$static_ok] correct.");
  1214. }
  1215. }
  1216. if ($fqdn ne '' and $dynamic_ok ne '') { db_log_debug($hdb,"Dynamic record for $fqdn [$dynamic_ok] correct. No changes required."); }
  1217. if ($fqdn ne '' and !$dynamic_ok) {
  1218. log_error("Dynamic record mismatch! Expected: $fqdn => $dhcp_record->{ip}, recivied: $dynamic_ref. Checking the status.");
  1219. #check exists hostname
  1220. my $another_hostname_exists = 0;
  1221. my $hostname_filter = ' LOWER(dns_name) REGEXP("^'.lc($dhcp_record->{hostname_utf8}).'\.*$")';
  1222. if ($fqdn_static ne '' and $fqdn !~/$fqdn_static/) {
  1223. $hostname_filter = $hostname_filter . ' or LOWER(dns_name) REGEXP("^'.lc($auth_record->{dns_name}).'\.*$")';
  1224. }
  1225. #check exists another records with some static hostname
  1226. my $filter_sql = 'SELECT * FROM User_auth WHERE id<>'.$auth_record->{id}.' and deleted=0 and ('.$hostname_filter.') ORDER BY last_found DESC';
  1227. db_log_debug($hdb,"Search dhcp hostname by: ".$filter_sql);
  1228. my $name_record = get_record_sql($hdb,$filter_sql);
  1229. if ($name_record->{dns_name} =~/^$fqdn$/i or $name_record->{dns_name} =~/^$dhcp_record->{hostname_utf8}$/i) {
  1230. $another_hostname_exists = 1;
  1231. }
  1232. if (!$another_hostname_exists) {
  1233. if ($fqdn_static and $fqdn_static ne '') {
  1234. if ($fqdn_static!~/$fqdn/) {
  1235. db_log_info($hdb,"Hostname from dhcp request $fqdn differs from static dns hostname $fqdn_static. Ignore dynamic binding!");
  1236. # delete_dns_hostname($fqdn,$dhcp_record->{ip},$ad_zone,$ad_dns,$hdb);
  1237. # create_dns_hostname($fqdn,$dhcp_record->{ip},$ad_zone,$ad_dns,$hdb);
  1238. }
  1239. } else {
  1240. db_log_info($hdb,"Rewrite aliases if exists for $fqdn => $dhcp_record->{ip}");
  1241. #get and remove aliases
  1242. my @aliases = get_records_sql($hdb,"SELECT * FROM User_auth_alias WHERE auth_id=".$auth_record->{id});
  1243. if (@aliases and scalar @aliases) {
  1244. foreach my $alias (@aliases) {
  1245. delete_dns_cname($fqdn_static,$alias->{alias},$ad_zone,$ad_dns,$hdb) if ($alias->{alias});
  1246. }
  1247. }
  1248. db_log_info($hdb,"Static dns hostname not defined. Create dns record by dhcp request. $fqdn => $dhcp_record->{ip}");
  1249. create_dns_hostname($fqdn,$dhcp_record->{ip},$ad_zone,$ad_dns,$hdb);
  1250. if (@aliases and scalar @aliases) {
  1251. foreach my $alias (@aliases) {
  1252. create_dns_cname($fqdn_static,$alias->{alias},$ad_zone,$ad_dns,$hdb) if ($alias->{alias});
  1253. }
  1254. }
  1255. }
  1256. } else {
  1257. 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.");
  1258. }
  1259. }
  1260. #end update dns block
  1261. }
  1262. #------------------------------------------------------------------------------------------------------------
  1263. sub apply_device_lock {
  1264. my $db = shift;
  1265. my $device_id = shift;
  1266. my $iteration = shift || 0;
  1267. $iteration++;
  1268. if ($iteration>2) { return 0; }
  1269. my $dev = get_record_sql($db,"SELECT `discovery_locked`, `locked_timestamp`, UNIX_TIMESTAMP(`locked_timestamp`) as u_locked_timestamp FROM devices WHERE id=".$device_id);
  1270. if (!$dev) { return 0; }
  1271. if (!$dev->{'discovery_locked'}) { return set_lock_discovery($db,$device_id); }
  1272. #if timestamp undefined, set and return
  1273. if (!$dev->{'locked_timestamp'}) { return set_lock_discovery($db,$device_id); }
  1274. #wait for discovery
  1275. my $wait_time = $dev->{'locked_timestamp'} + 30 - time();
  1276. if ($wait_time<0) { return set_lock_discovery($db,$device_id); }
  1277. sleep($wait_time);
  1278. return apply_device_lock($db,$device_id,$iteration);
  1279. }
  1280. #------------------------------------------------------------------------------------------------------------
  1281. sub set_lock_discovery {
  1282. my $db = shift;
  1283. my $device_id = shift;
  1284. my $new;
  1285. $new->{'discovery_locked'} = 1;
  1286. $new->{'locked_timestamp'} = GetNowTime();
  1287. if (update_record($db,'devices',$new,'id='.$device_id)) { return 1; }
  1288. return 0;
  1289. }
  1290. #------------------------------------------------------------------------------------------------------------
  1291. sub unset_lock_discovery {
  1292. my $db = shift;
  1293. my $device_id = shift;
  1294. my $new;
  1295. $new->{'discovery_locked'} = 0;
  1296. $new->{'locked_timestamp'} = GetNowTime();
  1297. if (update_record($db,'devices',$new,'id='.$device_id)) { return 1; }
  1298. return 0;
  1299. }
  1300. #------------------------------------------------------------------------------------------------------------
  1301. sub create_dns_cname {
  1302. my $fqdn = shift;
  1303. my $alias = shift;
  1304. my $zone = shift;
  1305. my $server = shift;
  1306. my $db = shift;
  1307. #skip update domain controllers
  1308. if (!$db) {
  1309. log_info("DNS-UPDATE: Add => Zone $zone Server: $server CNAME: $alias for $fqdn");
  1310. } else {
  1311. db_log_info($db,"DNS-UPDATE: Add => Zone $zone Server: $server CNAME: $alias for $fqdn ");
  1312. }
  1313. my $ad_zone = get_option($db,33);
  1314. my $nsupdate_file = "/tmp/".$fqdn."-nsupdate";
  1315. my @add_dns;
  1316. if ($config_ref{dns_server_type}=~/windows/i) {
  1317. push(@add_dns,"gsstsig");
  1318. push(@add_dns,"server $server");
  1319. push(@add_dns,"zone $zone");
  1320. push(@add_dns,"update add $alias 3600 cname $fqdn.");
  1321. push(@add_dns,"send");
  1322. write_to_file($nsupdate_file,\@add_dns);
  1323. do_exec('/usr/bin/kinit -k -t /opt/Eye/scripts/cfg/dns_updater.keytab dns_updater@'.uc($ad_zone).' && /usr/bin/nsupdate "'.$nsupdate_file.'"');
  1324. }
  1325. if ($config_ref{dns_server_type}=~/bind/i) {
  1326. push(@add_dns,"server $server");
  1327. push(@add_dns,"zone $zone");
  1328. push(@add_dns,"update add $alias 3600 cname $fqdn.");
  1329. push(@add_dns,"send");
  1330. write_to_file($nsupdate_file,\@add_dns);
  1331. do_exec('/usr/bin/nsupdate -k /etc/bind/rndc.key "'.$nsupdate_file.'"');
  1332. }
  1333. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  1334. }
  1335. #---------------------------------------------------------------------------------------------------------------
  1336. sub delete_dns_cname {
  1337. my $fqdn = shift;
  1338. my $alias = shift;
  1339. my $zone = shift;
  1340. my $server = shift;
  1341. my $db = shift;
  1342. if (!$db) {
  1343. log_info("DNS-UPDATE: Delete => Zone $zone Server: $server CNAME: $alias for $fqdn ");
  1344. } else {
  1345. db_log_info($db,"DNS-UPDATE: Delete => Zone $zone Server: $server CNAME: $alias for $fqdn");
  1346. }
  1347. my $ad_zone = get_option($db,33);
  1348. my $nsupdate_file = "/tmp/".$fqdn."-nsupdate";
  1349. my @add_dns;
  1350. if ($config_ref{dns_server_type}=~/windows/i) {
  1351. push(@add_dns,"gsstsig");
  1352. push(@add_dns,"server $server");
  1353. push(@add_dns,"zone $zone");
  1354. push(@add_dns,"update delete $alias cname ");
  1355. push(@add_dns,"send");
  1356. write_to_file($nsupdate_file,\@add_dns);
  1357. do_exec('/usr/bin/kinit -k -t /opt/Eye/scripts/cfg/dns_updater.keytab dns_updater@'.uc($ad_zone).' && /usr/bin/nsupdate "'.$nsupdate_file.'"');
  1358. }
  1359. if ($config_ref{dns_server_type}=~/bind/i) {
  1360. push(@add_dns,"server $server");
  1361. push(@add_dns,"zone $zone");
  1362. push(@add_dns,"update delete $alias cname");
  1363. push(@add_dns,"send");
  1364. write_to_file($nsupdate_file,\@add_dns);
  1365. do_exec('/usr/bin/nsupdate -k /etc/bind/rndc.key "'.$nsupdate_file.'"');
  1366. }
  1367. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  1368. }
  1369. #------------------------------------------------------------------------------------------------------------
  1370. sub create_dns_hostname {
  1371. my $fqdn = shift;
  1372. my $ip = shift;
  1373. my $zone = shift;
  1374. my $server = shift;
  1375. my $db = shift;
  1376. #skip update domain controllers
  1377. if ($fqdn=~/^dc[0-9]{1,2}\./i) { return; }
  1378. if (!$db) {
  1379. log_info("DNS-UPDATE: Add => Zone $zone Server: $server A: $fqdn IP: $ip");
  1380. } else {
  1381. db_log_info($db,"DNS-UPDATE: Add => Zone $zone Server: $server A: $fqdn IP: $ip");
  1382. }
  1383. my $ad_zone = get_option($db,33);
  1384. my $nsupdate_file = "/tmp/".$fqdn."-nsupdate";
  1385. my @add_dns;
  1386. if ($config_ref{dns_server_type}=~/windows/i) {
  1387. push(@add_dns,"gsstsig");
  1388. push(@add_dns,"server $server");
  1389. push(@add_dns,"zone $zone");
  1390. push(@add_dns,"update add $fqdn 3600 A $ip");
  1391. push(@add_dns,"send");
  1392. write_to_file($nsupdate_file,\@add_dns);
  1393. do_exec('/usr/bin/kinit -k -t /opt/Eye/scripts/cfg/dns_updater.keytab dns_updater@'.uc($ad_zone).' && /usr/bin/nsupdate "'.$nsupdate_file.'"');
  1394. }
  1395. if ($config_ref{dns_server_type}=~/bind/i) {
  1396. push(@add_dns,"server $server");
  1397. push(@add_dns,"zone $zone");
  1398. push(@add_dns,"update add $fqdn 3600 A $ip");
  1399. push(@add_dns,"send");
  1400. write_to_file($nsupdate_file,\@add_dns);
  1401. do_exec('/usr/bin/nsupdate -k /etc/bind/rndc.key "'.$nsupdate_file.'"');
  1402. }
  1403. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  1404. }
  1405. #---------------------------------------------------------------------------------------------------------------
  1406. sub delete_dns_hostname {
  1407. my $fqdn = shift;
  1408. my $ip = shift;
  1409. my $zone = shift;
  1410. my $server = shift;
  1411. my $db = shift;
  1412. #skip update domain controllers
  1413. if ($fqdn=~/^dc[0-9]{1,2}\./i) { return; }
  1414. if (!$db) {
  1415. log_info("DNS-UPDATE: Delete => Zone $zone Server: $server A: $fqdn IP: $ip");
  1416. } else {
  1417. db_log_info($db,"DNS-UPDATE: Delete => Zone $zone Server: $server A: $fqdn IP: $ip");
  1418. }
  1419. my $ad_zone = get_option($db,33);
  1420. my $nsupdate_file = "/tmp/".$fqdn."-nsupdate";
  1421. my @add_dns;
  1422. if ($config_ref{dns_server_type}=~/windows/i) {
  1423. push(@add_dns,"gsstsig");
  1424. push(@add_dns,"server $server");
  1425. push(@add_dns,"zone $zone");
  1426. push(@add_dns,"update delete $fqdn A");
  1427. push(@add_dns,"send");
  1428. write_to_file($nsupdate_file,\@add_dns);
  1429. do_exec('/usr/bin/kinit -k -t /opt/Eye/scripts/cfg/dns_updater.keytab dns_updater@'.uc($ad_zone).' && /usr/bin/nsupdate "'.$nsupdate_file.'"');
  1430. }
  1431. if ($config_ref{dns_server_type}=~/bind/i) {
  1432. push(@add_dns,"server $server");
  1433. push(@add_dns,"zone $zone");
  1434. push(@add_dns,"update delete $fqdn A");
  1435. push(@add_dns,"send");
  1436. write_to_file($nsupdate_file,\@add_dns);
  1437. do_exec('/usr/bin/nsupdate -k /etc/bind/rndc.key "'.$nsupdate_file.'"');
  1438. }
  1439. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  1440. }
  1441. #---------------------------------------------------------------------------------------------------------------
  1442. sub create_dns_ptr {
  1443. my $fqdn = shift;
  1444. my $ip = shift;
  1445. my $ad_zone = shift;
  1446. my $server = shift;
  1447. my $db = shift;
  1448. my $radr;
  1449. my $zone;
  1450. #skip update domain controllers
  1451. if ($fqdn=~/^dc[0-9]{1,2}\./i) { return; }
  1452. if ($ip =~ /([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})(\/[0-9]{1,2}){0,1}/) {
  1453. return 0 if($1 > 255 || $2 > 255 || $3 > 255 || $4 > 255);
  1454. $radr = "$4.$3.$2.$1.in-addr.arpa";
  1455. $zone = "$3.$2.$1.in-addr.arpa";
  1456. }
  1457. if (!$radr or !$zone) { return 0; }
  1458. if (!$db) { return 0; }
  1459. db_log_info($db,"DNS-UPDATE: Zone $zone Server: $server A: $fqdn PTR: $ip");
  1460. my $nsupdate_file = "/tmp/".$radr."-nsupdate";
  1461. my @add_dns;
  1462. if ($config_ref{dns_server_type}=~/windows/i) {
  1463. push(@add_dns,"gsstsig");
  1464. push(@add_dns,"server $server");
  1465. push(@add_dns,"zone $zone");
  1466. push(@add_dns,"update add $radr 3600 PTR $fqdn.");
  1467. push(@add_dns,"send");
  1468. write_to_file($nsupdate_file,\@add_dns);
  1469. 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.'"';
  1470. do_exec($run_cmd);
  1471. }
  1472. if ($config_ref{dns_server_type}=~/bind/i) {
  1473. push(@add_dns,"server $server");
  1474. push(@add_dns,"zone $zone");
  1475. push(@add_dns,"update add $radr 3600 PTR $fqdn.");
  1476. push(@add_dns,"send");
  1477. write_to_file($nsupdate_file,\@add_dns);
  1478. my $run_cmd = '/usr/bin/nsupdate -k /etc/bind/rndc.key "'.$nsupdate_file.'"';
  1479. do_exec($run_cmd);
  1480. }
  1481. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  1482. }
  1483. #---------------------------------------------------------------------------------------------------------------
  1484. sub delete_dns_ptr {
  1485. my $fqdn = shift;
  1486. my $ip = shift;
  1487. my $ad_zone = shift;
  1488. my $server = shift;
  1489. my $db = shift;
  1490. my $radr;
  1491. my $zone;
  1492. #skip update domain controllers
  1493. if ($fqdn=~/^dc[0-9]{1,2}\./i) { return; }
  1494. if ($ip =~ /([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})(\/[0-9]{1,2}){0,1}/) {
  1495. return 0 if($1 > 255 || $2 > 255 || $3 > 255 || $4 > 255);
  1496. $radr = "$4.$3.$2.$1.in-addr.arpa";
  1497. $zone = "$3.$2.$1.in-addr.arpa";
  1498. }
  1499. if (!$radr or !$zone) { return 0; }
  1500. if (!$db) { return 0 ; }
  1501. db_log_info($db,"DNS-UPDATE: Delete => Zone $zone Server: $server A: $fqdn PTR: $ip");
  1502. my $nsupdate_file = "/tmp/".$radr."-nsupdate";
  1503. my @add_dns;
  1504. if ($config_ref{dns_server_type}=~/windows/i) {
  1505. push(@add_dns,"gsstsig");
  1506. push(@add_dns,"server $server");
  1507. push(@add_dns,"zone $zone");
  1508. push(@add_dns,"update delete $radr PTR");
  1509. push(@add_dns,"send");
  1510. write_to_file($nsupdate_file,\@add_dns);
  1511. 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.'"';
  1512. do_exec($run_cmd);
  1513. }
  1514. if ($config_ref{dns_server_type}=~/bind/i) {
  1515. push(@add_dns,"server $server");
  1516. push(@add_dns,"zone $zone");
  1517. push(@add_dns,"update delete $radr PTR");
  1518. push(@add_dns,"send");
  1519. write_to_file($nsupdate_file,\@add_dns);
  1520. my $run_cmd = '/usr/bin/nsupdate -k /etc/bind/rndc.key "'.$nsupdate_file.'"';
  1521. do_exec($run_cmd);
  1522. }
  1523. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  1524. }
  1525. #---------------------------------------------------------------------------------------------------------------
  1526. sub new_user {
  1527. my $db = shift;
  1528. my $user_info = shift;
  1529. my $user;
  1530. if ($user_info->{mac}) {
  1531. $user->{login}=mac_splitted($user_info->{mac});
  1532. } else {
  1533. $user->{login}=$user_info->{ip};
  1534. }
  1535. if ($user_info->{dhcp_hostname}) { $user->{fio}=$user_info->{dhcp_hostname}; }
  1536. if (!$user->{fio}) { $user->{fio}=$user_info->{ip}; }
  1537. my $login_count = get_count_records($db,"User_list","(login LIKE '".$user->{login}."(%)') OR (login='".$user->{login}."')");
  1538. if ($login_count) { $login_count++; $user->{login} .="(".$login_count.")"; }
  1539. $user->{ou_id} = $user_info->{ou_id};
  1540. my $ou_info = get_record_sql($db,"SELECT * FROM OU WHERE id=".$user_info->{'ou_id'});
  1541. if ($ou_info) {
  1542. $user->{'enabled'} = $ou_info->{'enabled'};
  1543. $user->{'queue_id'} = $ou_info->{'queue_id'};
  1544. $user->{'filter_group_id'} = $ou_info->{'filter_group_id'};
  1545. }
  1546. my $result = insert_record($db,"User_list",$user);
  1547. if ($result and $config_ref{auto_mac_rule} and $user_info->{mac}) {
  1548. my $auth_rule;
  1549. $auth_rule->{user_id} = $result;
  1550. $auth_rule->{type} = 2;
  1551. $auth_rule->{rule} = mac_splitted($user_info->{mac});
  1552. insert_record($db,"auth_rules",$auth_rule);
  1553. }
  1554. return $result;
  1555. }
  1556. #---------------------------------------------------------------------------------------------------------------
  1557. sub get_ip_subnet {
  1558. my $db = shift;
  1559. my $ip = shift;
  1560. if (!$ip) { return; }
  1561. my $ip_aton = StrToIp($ip);
  1562. my $user_subnet = get_record_sql($db, "SELECT * FROM `subnets` WHERE hotspot=1 or office=1 and ( ".$ip_aton." >= ip_int_start and ".$ip_aton." <= ip_int_stop)");
  1563. return $user_subnet;
  1564. }
  1565. #---------------------------------------------------------------------------------------------------------------
  1566. sub find_mac_in_subnet {
  1567. my $db = shift;
  1568. my $ip = shift;
  1569. my $mac = shift;
  1570. if (!$ip or !$mac) { return; }
  1571. my $ip_subnet = get_ip_subnet($db, $ip);
  1572. if (!$ip_subnet) { return; }
  1573. my @t_auth = get_records_sql($db, "SELECT * FROM User_auth WHERE ip_int>=" . $ip_subnet->{'ip_int_start'} . " and ip_int<=" . $ip_subnet->{'ip_int_stop'} . " and mac='" . $mac . "' and deleted=0 ORDER BY id");
  1574. my $auth_count = 0;
  1575. my $result;
  1576. $result->{'count'} = 0;
  1577. foreach my $row (@t_auth) {
  1578. next if (!$row);
  1579. $auth_count++;
  1580. $result->{'count'} = $auth_count;
  1581. $result->{items}{$auth_count} = $row;
  1582. }
  1583. return $result;
  1584. }
  1585. #---------------------------------------------------------------------------------------------------------------
  1586. sub resurrection_auth {
  1587. my $db = shift;
  1588. my $ip_record = shift;
  1589. my $ip = $ip_record->{'ip'};
  1590. my $mac = $ip_record->{'mac'};
  1591. my $action = $ip_record->{'type'};
  1592. my $hostname = $ip_record->{'hostname_utf8'};
  1593. my $client_id = $ip_record->{'client-id'};
  1594. if (!exists $ip_record->{ip_aton}) { $ip_record->{ip_aton}=StrToIp($ip); }
  1595. if (!exists $ip_record->{hotspot}) { $ip_record->{hotspot}=is_hotspot($db,$ip); }
  1596. my $auth_ident = "Found new ip-address: " . $ip;
  1597. $auth_ident = $auth_ident . '['.$mac .']' if ($mac);
  1598. $auth_ident = $auth_ident . ' :: '.$hostname if ($hostname);
  1599. my $ip_aton=$ip_record->{ip_aton};
  1600. my $timestamp=GetNowTime();
  1601. my $record=get_record_sql($db,'SELECT * FROM User_auth WHERE `deleted`=0 AND `ip_int`='.$ip_aton.' AND `mac`="'.$mac.'"');
  1602. my $new_record;
  1603. $new_record->{last_found}=$timestamp;
  1604. $new_record->{arp_found}=$timestamp;
  1605. if ($client_id) { $new_record->{'client-id'} = $client_id; }
  1606. #auth found?
  1607. if ($record->{user_id}) {
  1608. #update timestamp and return
  1609. if ($action=~/^(add|old|del)$/i) {
  1610. $new_record->{dhcp_action}=$action;
  1611. $new_record->{created_by}='dhcp';
  1612. $new_record->{dhcp_time}=$timestamp;
  1613. if ($hostname) { $new_record->{dhcp_hostname} = $hostname; }
  1614. }
  1615. update_record($db,'User_auth',$new_record,"id=$record->{id}");
  1616. return $record->{id};
  1617. }
  1618. my $user_subnet=$office_networks->match_string($ip);
  1619. if ($user_subnet->{static}) {
  1620. db_log_warning($db,"Unknown ip+mac found in static subnet! Abort create record for ip: $ip mac: [".$mac."]");
  1621. return 0;
  1622. }
  1623. my $send_alert_update = isNotifyUpdate(get_notify_subnet($db,$ip));
  1624. my $send_alert_create = isNotifyCreate(get_notify_subnet($db,$ip));
  1625. #my $send_alert_delete = isNotifyDelete(get_notify_subnet($db,$ip));
  1626. my $mac_exists=find_mac_in_subnet($db,$ip,$mac);
  1627. my $msg = '';
  1628. #search changed mac
  1629. $record=get_record_sql($db,'SELECT * FROM User_auth WHERE `ip_int`='.$ip_aton." and deleted=0");
  1630. if ($record->{id}) {
  1631. #if found record with same ip but without mac - update it
  1632. if (!$record->{mac}) {
  1633. $msg = $auth_ident. "\nUse auth record with no mac: " . hash_to_text($record);
  1634. db_log_verbose($db,$msg);
  1635. $new_record->{mac}=$mac;
  1636. #disable dhcp for same mac in one ip subnet
  1637. if ($mac_exists and $mac_exists->{'count'}) { $new_record->{dhcp}=0; }
  1638. if ($action=~/^(add|old|del)$/i) {
  1639. $new_record->{dhcp_action}=$action;
  1640. $new_record->{dhcp_time}=$timestamp;
  1641. $new_record->{created_by}='dhcp';
  1642. if ($hostname) { $new_record->{dhcp_hostname} = $hostname; }
  1643. }
  1644. update_record($db,'User_auth',$new_record,"id=$record->{id}");
  1645. sendEmail("WARN! ".get_first_line($msg),$msg,1) if ($send_alert_update);
  1646. return $record->{id};
  1647. }
  1648. #if found record with same ip but another mac - delete old record
  1649. if ($record->{mac}) {
  1650. if (!$ip_record->{hotspot}) {
  1651. my $msg = "For ip: $ip mac change detected! Old mac: [".$record->{mac}."] New mac: [".$mac."]. Disable old auth_id: $record->{id}";
  1652. db_log_warning($db,$msg,$record->{id});
  1653. sendEmail("WARN! ".get_first_line($msg),$msg,1) if ($send_alert_update);
  1654. }
  1655. delete_user_auth($db,$record->{id});
  1656. }
  1657. }
  1658. #default user
  1659. my $new_user_info=get_new_user_id($db,$ip,$mac,$hostname);
  1660. my $new_user_id;
  1661. if ($new_user_info->{user_id}) { $new_user_id = $new_user_info->{user_id}; }
  1662. if (!$new_user_id) { $new_user_id = new_user($db,$new_user_info); }
  1663. if ($mac_exists) {
  1664. #deleting the user's entry if the address belongs to a dynamic group
  1665. foreach my $dup_record_id (keys %{$mac_exists->{items}}) {
  1666. my $dup_record = $mac_exists->{items}{$dup_record_id};
  1667. next if (!$dup_record);
  1668. #remove old dynamic record with some mac
  1669. if ($dup_record->{dynamic}) {
  1670. delete_user_auth($db,$dup_record->{id});
  1671. }
  1672. }
  1673. }
  1674. #recheck
  1675. $mac_exists=find_mac_in_subnet($db,$ip,$mac);
  1676. #disable dhcp for same mac in one ip subnet
  1677. if ($mac_exists and $mac_exists->{'count'}) { $new_record->{dhcp}=0; }
  1678. #seek old auth with same ip and mac
  1679. my $auth_exists=get_count_records($db,'User_auth',"ip_int=".$ip_aton." and mac='".$mac."'");
  1680. $new_record->{ip_int}=$ip_aton;
  1681. $new_record->{ip}=$ip;
  1682. $new_record->{mac}=$mac;
  1683. $new_record->{user_id}=$new_user_id;
  1684. $new_record->{save_traf}="$save_detail";
  1685. $new_record->{deleted}="0";
  1686. if ($action=~/^(add|old|del)$/i) {
  1687. $new_record->{dhcp_action}=$action;
  1688. $new_record->{dhcp_time}=$timestamp;
  1689. $new_record->{created_by}='dhcp';
  1690. } else {
  1691. $new_record->{created_by}=$action;
  1692. }
  1693. my $cur_auth_id= 0;
  1694. if ($auth_exists) {
  1695. #found ->Resurrection old record
  1696. my $resurrection_id = get_id_record($db,'User_auth',"ip_int=".$ip_aton." and mac='".$mac."'");
  1697. $msg = $auth_ident . " Resurrection auth_id: $resurrection_id with ip: $ip and mac: $mac";
  1698. if (!$ip_record->{hotspot}) { db_log_warning($db,$msg); } else { db_log_info($db,$msg); }
  1699. if (update_record($db,'User_auth',$new_record,"id=$resurrection_id")) { $cur_auth_id = $resurrection_id; }
  1700. } else {
  1701. #not found ->create new record
  1702. $msg = $auth_ident ."\n";
  1703. $cur_auth_id = insert_record($db,'User_auth',$new_record);
  1704. if ($cur_auth_id) {
  1705. if (!$ip_record->{hotspot}) { db_log_warning($db,$msg); } else { db_log_info($db,$msg); }
  1706. }
  1707. }
  1708. #filter and status
  1709. $cur_auth_id=get_id_record($db,'User_auth',"ip='$ip' and mac='$mac' and deleted=0 ORDER BY last_found DESC") if (!$cur_auth_id);
  1710. if ($cur_auth_id) {
  1711. my $user_record=get_record_sql($db,"SELECT * FROM User_list WHERE id=".$new_user_id);
  1712. if ($user_record) {
  1713. my $ou_info = get_record_sql($db,'SELECT * FROM OU WHERE id='.$user_record->{ou_id});
  1714. if ($ou_info and $ou_info->{'dynamic'}) {
  1715. # Устанавливаем значение по умолчанию, если не задано
  1716. if (!$ou_info->{'life_duration'}) {
  1717. $ou_info->{'life_duration'} = 24.0; # Явно указываем дробное число
  1718. }
  1719. my $now = DateTime->now(time_zone => 'local');
  1720. # Разбиваем life_duration на часы и минуты (для дробного значения)
  1721. my $hours = int($ou_info->{'life_duration'}); # Целая часть (часы)
  1722. my $minutes = ($ou_info->{'life_duration'} - $hours) * 60; # Дробная часть → минуты
  1723. # Создаём продолжительность с учётом дробных часов (в виде часов + минут)
  1724. my $duration = DateTime::Duration->new( hours => $hours, minutes => $minutes);
  1725. my $eof = $now + $duration;
  1726. $new_record->{'dynamic'} = 1;
  1727. $new_record->{'eof'} = $eof->strftime('%Y-%m-%d %H:%M:%S');
  1728. }
  1729. $new_record->{ou_id}=$user_record->{ou_id};
  1730. $new_record->{comments}=$user_record->{fio};
  1731. $new_record->{filter_group_id}=$user_record->{filter_group_id};
  1732. $new_record->{queue_id}=$user_record->{queue_id};
  1733. $new_record->{enabled}="$user_record->{enabled}";
  1734. update_record($db,'User_auth',$new_record,"id=$cur_auth_id");
  1735. }
  1736. db_log_warning($db, $msg, $cur_auth_id);
  1737. sendEmail("WARN! ".get_first_line($msg),$msg."\n".record_to_txt($db,'User_auth',$cur_auth_id),1) if ($send_alert_create);
  1738. } else { return; }
  1739. return $cur_auth_id;
  1740. }
  1741. #---------------------------------------------------------------------------------------------------------------
  1742. sub new_auth {
  1743. my $db = shift;
  1744. my $ip = shift;
  1745. my $ip_aton=StrToIp($ip);
  1746. my $record=get_record_sql($db,'SELECT id FROM User_auth WHERE `deleted`=0 AND `ip_int`='.$ip_aton);
  1747. if ($record->{id}) { return $record->{id}; }
  1748. #default user
  1749. my $new_user_info=get_new_user_id($db,$ip,undef,undef);
  1750. my $new_user_id;
  1751. if ($new_user_info->{user_id}) { $new_user_id = $new_user_info->{user_id}; }
  1752. if ($new_user_info->{ou_id}) { $new_user_id = new_user($db,$new_user_info); }
  1753. if (is_dynamic_ou($db,$new_user_info->{ou_id})) {
  1754. db_log_debug($db,"The ip-address $ip belongs to a dynamic group - ignore it.");
  1755. return;
  1756. }
  1757. my $send_alert = isNotifyCreate(get_notify_subnet($db,$ip));
  1758. my $user_record=get_record_sql($db,"SELECT * FROM User_list WHERE id=".$new_user_id);
  1759. my $timestamp=GetNowTime();
  1760. my $new_record;
  1761. $new_record->{ip_int}=$ip_aton;
  1762. $new_record->{ip}=$ip;
  1763. $new_record->{user_id}=$new_user_id;
  1764. $new_record->{save_traf}="$save_detail";
  1765. $new_record->{deleted}="0";
  1766. $new_record->{created_by}='netflow';
  1767. $new_record->{ou_id}=$user_record->{ou_id};
  1768. $new_record->{filter_group_id}=$user_record->{filter_group_id};
  1769. $new_record->{queue_id}=$user_record->{queue_id};
  1770. $new_record->{enabled}="$user_record->{enabled}";
  1771. if ($user_record->{fio}) { $new_record->{comments}=$user_record->{fio}; }
  1772. my $cur_auth_id=insert_record($db,'User_auth',$new_record);
  1773. if ($cur_auth_id) {
  1774. my $msg = "New ip created by netflow! ip: $ip";
  1775. db_log_warning($db,$msg,$cur_auth_id);
  1776. sendEmail("WARN! ".get_first_line($msg),$msg,1) if ($send_alert);
  1777. }
  1778. return $cur_auth_id;
  1779. }
  1780. #---------------------------------------------------------------------------------------------------------------
  1781. sub get_option {
  1782. my $db=shift;
  1783. my $option_id=shift;
  1784. return if (!$option_id);
  1785. return if (!$db);
  1786. my $default_option = get_record_sql($db,'SELECT * FROM config_options WHERE id='.$option_id);
  1787. my $config_options = get_record_sql($db,'SELECT * FROM config WHERE option_id='.$option_id);
  1788. my $result;
  1789. if (!$config_options) {
  1790. if ($default_option->{'type'}=~/^(int|bool)/i) { $result = $default_option->{'default_value'}*1; };
  1791. if ($default_option->{'type'}=~/^(string|text)/i) { $result = $default_option->{'default_value'}; }
  1792. if ($default_option->{'type'}=~/^list/i) { $result = $default_option->{'default_value'}; }
  1793. return $result;
  1794. }
  1795. $result = $config_options->{'value'};
  1796. return $result;
  1797. }
  1798. #---------------------------------------------------------------------------------------------------------------
  1799. sub init_option {
  1800. my $db=shift;
  1801. $last_refresh_config = time();
  1802. $config_ref{version}='';
  1803. my $version_record = get_record_sql($db,"SELECT version FROM version WHERE version is NOT NULL");
  1804. if ($version_record) { $config_ref{version}=$version_record->{version}; }
  1805. $config_ref{self_ip} = '127.0.0.1';
  1806. if ($DBHOST ne '127.0.0.1') {
  1807. my $ip_route = qx(ip r get $DBHOST 2>&1 | head -1);
  1808. if ($? == 0) {
  1809. if ($ip_route =~ /src\s+(\d+\.\d+\.\d+\.\d+)/) { $config_ref{self_ip} = $1; }
  1810. }
  1811. }
  1812. $config_ref{dbh}=$db;
  1813. $config_ref{save_detail}=get_option($db,23);
  1814. $config_ref{add_unknown_user}=get_option($db,22);
  1815. $config_ref{dhcp_server}=get_option($db,5);
  1816. $config_ref{snmp_default_version}=get_option($db,9);
  1817. $config_ref{snmp_default_community}=get_option($db,11);
  1818. $config_ref{KB}=get_option($db,1);
  1819. if ($config_ref{KB} ==0) { $config_ref{KB}=1000; }
  1820. if ($config_ref{KB} ==1) { $config_ref{KB}=1024; }
  1821. $config_ref{admin_email}=get_option($db,21);
  1822. $config_ref{sender_email}=get_option($db,52);
  1823. $config_ref{send_email}=get_option($db,51);
  1824. $config_ref{history}=get_option($db,26);
  1825. $config_ref{history_dhcp}=get_option($db,27);
  1826. $config_ref{router_login}=get_option($db,28);
  1827. $config_ref{router_password}=get_option($db,29);
  1828. $config_ref{router_port}=get_option($db,30);
  1829. $config_ref{org_name}=get_option($db,32);
  1830. $config_ref{domain_name}=get_option($db,33);
  1831. $config_ref{connections_history}=get_option($db,35);
  1832. $config_ref{debug}=get_option($db,34);
  1833. $config_ref{log_level} = get_option($db,53);
  1834. if ($config_ref{debug}) { $config_ref{log_level} = 255; }
  1835. $config_ref{urgent_sync}=get_option($db,50);
  1836. $config_ref{ignore_hotspot_dhcp_log} = get_option($db,44);
  1837. $config_ref{ignore_update_dhcp_event} = get_option($db,45);
  1838. $config_ref{update_hostname_from_dhcp} = get_option($db,46);
  1839. $config_ref{history_log_day}=get_option($db,47);
  1840. $config_ref{history_syslog_day} = get_option($db,48);
  1841. $config_ref{history_trafstat_day} = get_option($db,49);
  1842. $config_ref{enable_quotes} = get_option($db,54);
  1843. $config_ref{netflow_step} = get_option($db,55);
  1844. $config_ref{traffic_ipstat_history} = get_option($db,56);
  1845. $config_ref{nagios_url} = get_option($db,57);
  1846. $config_ref{cacti_url} = get_option($db,58);
  1847. $config_ref{torrus_url} = get_option($db,59);
  1848. $config_ref{wiki_url} = get_option($db,60);
  1849. $config_ref{stat_url} = get_option($db,62);
  1850. $config_ref{wiki_path} = get_option($db,61);
  1851. $config_ref{auto_mac_rule} = get_option($db,64);
  1852. #network configuration mode
  1853. $config_ref{config_mode}=get_option($db,68);
  1854. #auto clean old user record
  1855. $config_ref{clean_empty_user}=get_option($db,69);
  1856. #dns_server_type
  1857. $config_ref{dns_server}=get_option($db,3);
  1858. $config_ref{dns_server_type}=get_option($db,70);
  1859. $config_ref{enable_dns_updates}=get_option($db,71);
  1860. #$save_detail = 1; id=23
  1861. $save_detail=get_option($db,23);
  1862. #$add_unknown_user = 1; id=22
  1863. $add_unknown_user=get_option($db,22);
  1864. #$dns_server='192.168.2.12'; id=3
  1865. $dns_server=get_option($db,3);
  1866. #$dhcp_server='192.168.2.12'; id=5
  1867. $dhcp_server=get_option($db,5);
  1868. #$snmp_default_version='2'; id=9
  1869. $snmp_default_version=get_option($db,9);
  1870. #$snmp_default_community='public'; id=11
  1871. $snmp_default_community=get_option($db,11);
  1872. #$KB=1024; id=1
  1873. $KB=$config_ref{KB};
  1874. #$admin_email; id=21
  1875. $admin_email=get_option($db,21);
  1876. #sender email
  1877. $sender_email=get_option($db,52);
  1878. #send email
  1879. $send_email=get_option($db,51);
  1880. #$history=15; id=26
  1881. $history=get_option($db,26);
  1882. #$history_dhcp=7; id=27
  1883. $history_dhcp=get_option($db,27);
  1884. #$router_login="admin"; id=28
  1885. $router_login=get_option($db,28);
  1886. #$router_password="admin"; id=29
  1887. $router_password=get_option($db,29);
  1888. #$router_port=23; id=30
  1889. $router_port=get_option($db,30);
  1890. #32
  1891. $org_name=get_option($db,32);
  1892. #33
  1893. $domain_name=get_option($db,33);
  1894. #35
  1895. $connections_history=get_option($db,35);
  1896. #debug
  1897. $debug=get_option($db,34);
  1898. #log level
  1899. $log_level = get_option($db,53);
  1900. if ($debug) { $log_level = 255; }
  1901. #urgent sync access
  1902. $urgent_sync=get_option($db,50);
  1903. $ignore_hotspot_dhcp_log = get_option($db,44);
  1904. $ignore_update_dhcp_event = get_option($db,45);
  1905. $update_hostname_from_dhcp = get_option($db,46);
  1906. $history_log_day=get_option($db,47);
  1907. $history_syslog_day = get_option($db,48);
  1908. $history_trafstat_day = get_option($db,49);
  1909. my $ou = get_record_sql($db,"SELECT id FROM OU WHERE default_users = 1");
  1910. if (!$ou) { $default_user_ou_id = 0; } else { $default_user_ou_id = $ou->{'id'}; }
  1911. $ou = get_record_sql($db,"SELECT id FROM OU WHERE default_hotspot = 1");
  1912. if (!$ou) { $default_hotspot_ou_id = $default_user_ou_id; } else { $default_hotspot_ou_id = $ou->{'id'}; }
  1913. @subnets=get_records_sql($db,'SELECT * FROM subnets ORDER BY ip_int_start');
  1914. if (defined $office_networks) { undef $office_networks; }
  1915. if (defined $free_networks) { undef $free_networks; }
  1916. if (defined $vpn_networks) { undef $vpn_networks; }
  1917. if (defined $hotspot_networks) { undef $hotspot_networks; }
  1918. if (defined $all_networks) { undef $all_networks; }
  1919. $office_networks = new Net::Patricia;
  1920. $free_networks = new Net::Patricia;
  1921. $vpn_networks = new Net::Patricia;
  1922. $hotspot_networks = new Net::Patricia;
  1923. $all_networks = new Net::Patricia;
  1924. @office_network_list=();
  1925. @free_network_list=();
  1926. @free_network_list=();
  1927. @vpn_network_list=();
  1928. @hotspot_network_list=();
  1929. @all_network_list=();
  1930. foreach my $net (@subnets) {
  1931. next if (!$net->{subnet});
  1932. $subnets_ref{$net->{subnet}}=$net;
  1933. if ($net->{office}) {
  1934. push(@office_network_list,$net->{subnet});
  1935. $office_networks->add_string($net->{subnet},$net);
  1936. }
  1937. if ($net->{free}) {
  1938. push(@free_network_list,$net->{subnet});
  1939. $free_networks->add_string($net->{subnet},$net);
  1940. }
  1941. if ($net->{vpn}) {
  1942. push(@vpn_network_list,$net->{subnet});
  1943. $vpn_networks->add_string($net->{subnet},$net);
  1944. }
  1945. if ($net->{hotspot}) {
  1946. push(@hotspot_network_list,$net->{subnet});
  1947. push(@all_network_list,$net->{subnet});
  1948. $hotspot_networks->add_string($net->{subnet},$net);
  1949. }
  1950. push(@all_network_list,$net->{subnet});
  1951. $all_networks->add_string($net->{subnet},$net);
  1952. }
  1953. }
  1954. #--------------------------------------------------------------------------------------------------------------
  1955. sub get_dynamic_ou {
  1956. my $db = shift;
  1957. my @dynamic=();
  1958. my @ou_list = get_records_sql($db,"SELECT id FROM OU WHERE dynamic = 1");
  1959. foreach my $group (@ou_list) {
  1960. next if (!$group);
  1961. push(@dynamic,$group->{id});
  1962. }
  1963. return wantarray ? @dynamic : \@dynamic;
  1964. }
  1965. #--------------------------------------------------------------------------------------------------------------
  1966. sub get_default_ou {
  1967. my $db = shift;
  1968. my @dynamic=();
  1969. my $ou = get_record_sql($db,"SELECT id FROM OU WHERE default_users = 1");
  1970. if (!$ou) { push(@dynamic,0); } else { push(@dynamic,$ou->{'id'}); }
  1971. $ou = get_record_sql($db,"SELECT id FROM OU WHERE default_hotspot = 1");
  1972. if ($ou) { push(@dynamic,$ou->{id}); }
  1973. return wantarray ? @dynamic : \@dynamic;
  1974. }
  1975. #--------------------------------------------------------------------------------------------------------------
  1976. sub is_dynamic_ou {
  1977. my $db = shift;
  1978. my $ou_id = shift;
  1979. my @dynamic=get_dynamic_ou($db);
  1980. if (in_array(\@dynamic,$ou_id)) { return 1; }
  1981. return 0;
  1982. }
  1983. #--------------------------------------------------------------------------------------------------------------
  1984. sub is_default_ou {
  1985. my $db = shift;
  1986. my $ou_id = shift;
  1987. my @dynamic=get_default_ou($db);
  1988. if (in_array(\@dynamic,$ou_id)) { return 1; }
  1989. return 0;
  1990. }
  1991. #---------------------------------------------------------------------------------------------------------------
  1992. sub get_subnets_ref {
  1993. my $db = shift;
  1994. my @list=get_records_sql($db,'SELECT * FROM subnets ORDER BY ip_int_start');
  1995. my $list_ref;
  1996. foreach my $net (@list) {
  1997. next if (!$net->{subnet});
  1998. $list_ref->{$net->{subnet}}=$net;
  1999. }
  2000. return $list_ref;
  2001. }
  2002. #---------------------------------------------------------------------------------------------------------------
  2003. sub get_device_by_ip {
  2004. my $db = shift;
  2005. my $ip = shift;
  2006. my $netdev=get_record_sql($db,'SELECT * FROM devices WHERE ip="'.$ip.'"');
  2007. if ($netdev and $netdev->{id}>0) { return $netdev; }
  2008. my $auth_rec=get_record_sql($db,'SELECT user_id FROM User_auth WHERE ip="'.$ip.'" and deleted=0');
  2009. if ($auth_rec and $auth_rec->{user_id}>0) {
  2010. $netdev=get_record_sql($db,'SELECT * FROM devices WHERE user_id='.$auth_rec->{user_id});
  2011. return $netdev;
  2012. }
  2013. return;
  2014. }
  2015. #---------------------------------------------------------------------------------------------------------------
  2016. sub GetUnixTimeByStr {
  2017. my $time_str = shift;
  2018. $time_str =~s/\//-/g;
  2019. $time_str = trim($time_str);
  2020. my ($sec,$min,$hour,$day,$mon,$year) = (localtime())[0,1,2,3,4,5];
  2021. $year+=1900;
  2022. $mon++;
  2023. if ($time_str =~/^([0-9]{2,4})\-([0-9]{1,2})-([0-9]{1,2})\s+/) {
  2024. $year = $1; $mon = $2; $day = $3;
  2025. }
  2026. if ($time_str =~/([0-9]{1,2})\:([0-9]{1,2})\:([0-9]{1,2})$/) {
  2027. $hour = $1; $min = $2; $sec = $3;
  2028. }
  2029. my $result = mktime($sec,$min,$hour,$day,$mon-1,$year-1900);
  2030. return $result;
  2031. }
  2032. #---------------------------------------------------------------------------------------------------------------
  2033. sub GetTimeStrByUnixTime {
  2034. my $time = shift || time();
  2035. my ($sec, $min, $hour, $mday, $mon, $year) = (localtime($time))[0,1,2,3,4,5];
  2036. my $result = strftime("%Y-%m-%d %H:%M:%S",$sec, $min, $hour, $mday, $mon, $year);
  2037. return $result;
  2038. }
  2039. #---------------------------------------------------------------------------------------------------------------
  2040. sub Set_Variable {
  2041. my $db = shift;
  2042. my $name = shift || $MY_NAME;
  2043. my $value = shift || $$;
  2044. my $timeshift = shift || 60;
  2045. Del_Variable($db,$name);
  2046. my $clean_variables = time() + $timeshift;
  2047. my ($sec,$min,$hour,$day,$month,$year,$zone) = localtime($clean_variables);
  2048. $month++;
  2049. $year += 1900;
  2050. my $clean_str=sprintf "%04d-%02d-%02d %02d:%02d:%02d",$year,$month,$day,$hour,$min,$sec;
  2051. my $clean_variables_date=$db->quote($clean_str);
  2052. do_sql($db,"INSERT INTO variables(name,value,clear_time) VALUES('".$name."','".$value."',".$clean_variables_date.");");
  2053. }
  2054. #---------------------------------------------------------------------------------------------------------------
  2055. sub Get_Variable {
  2056. my $db = shift;
  2057. my $name = shift || $MY_NAME;
  2058. my $variable=get_record_sql($db,'SELECT `value` FROM `variables` WHERE name="'.$name.'"');
  2059. if (!$variable and $variable->{'value'}) { return $variable->{'value'}; }
  2060. return;
  2061. }
  2062. #---------------------------------------------------------------------------------------------------------------
  2063. sub Del_Variable {
  2064. my $db = shift;
  2065. my $name = shift || $MY_NAME;
  2066. do_sql($db,"DELETE FROM `variables` WHERE name='".$name."';");
  2067. }
  2068. #---------------------------------------------------------------------------------------------------------------
  2069. sub recalc_quotes {
  2070. my $db = shift;
  2071. my $calc_id = shift || $$;
  2072. return if (!get_option($db,54));
  2073. clean_variables($db);
  2074. return if (Get_Variable($db,'RECALC'));
  2075. my $timeshift = get_option($db,55);
  2076. Set_Variable($db,'RECALC',$calc_id,time()+$timeshift*60);
  2077. my $now = DateTime->now(time_zone=>'local');
  2078. my $day_start = $db->quote($now->ymd("-")." 00:00:00");
  2079. my $day_dur = DateTime::Duration->new( days => 1 );
  2080. my $tomorrow = $now+$day_dur;
  2081. my $day_stop = $db->quote($tomorrow->ymd("-")." 00:00:00");
  2082. $now->set(day=>1);
  2083. my $month_start=$db->quote($now->ymd("-")." 00:00:00");
  2084. my $month_dur = DateTime::Duration->new( months => 1 );
  2085. my $next_month = $now + $month_dur;
  2086. $next_month->set(day=>1);
  2087. my $month_stop = $db->quote($next_month->ymd("-")." 00:00:00");
  2088. #get user limits
  2089. my $user_auth_list_sql="SELECT A.id as auth_id, U.id, U.day_quota, U.month_quota, A.day_quota as auth_day, A.month_quota as auth_month FROM User_auth as A,User_list as U WHERE A.deleted=0 ORDER by user_id";
  2090. my @authlist_ref = get_records_sql($db,$user_auth_list_sql);
  2091. my %user_stats;
  2092. my %auth_info;
  2093. foreach my $row (@authlist_ref) {
  2094. $auth_info{$row->{auth_id}}{user_id}=$row->{id};
  2095. $auth_info{$row->{auth_id}}{day_limit}=$row->{auth_day};
  2096. $auth_info{$row->{auth_id}}{month_limit}=$row->{auth_month};
  2097. $auth_info{$row->{auth_id}}{day}=0;
  2098. $auth_info{$row->{auth_id}}{month}=0;
  2099. $user_stats{$row->{id}}{day_limit}=$row->{day_quota};
  2100. $user_stats{$row->{id}}{month_limit}=$row->{month_quota};
  2101. $user_stats{$row->{id}}{day}=0;
  2102. $user_stats{$row->{id}}{month}=0;
  2103. }
  2104. #recalc quotes - global
  2105. #day
  2106. my $day_sql="SELECT User_stats.auth_id, SUM( byte_in + byte_out ) AS traf_all FROM User_stats
  2107. WHERE User_stats.`timestamp`>= $day_start AND User_stats.`timestamp`< $day_stop GROUP BY User_stats.auth_id";
  2108. my @day_stats = get_records_sql($db,$day_sql);
  2109. foreach my $row (@day_stats) {
  2110. my $user_id=$auth_info{$row->{auth_id}}{user_id};
  2111. $auth_info{$row->{auth_id}}{day}=$row->{traf_all};
  2112. $user_stats{$user_id}{day}+=$row->{traf_all};
  2113. }
  2114. #month
  2115. my $month_sql="SELECT User_stats.auth_id, SUM( byte_in + byte_out ) AS traf_all FROM User_stats
  2116. WHERE User_stats.`timestamp`>= $month_start AND User_stats.`timestamp`< $month_stop GROUP BY User_stats.auth_id";
  2117. my @month_stats = get_records_sql($db,$month_sql);
  2118. foreach my $row (@month_stats) {
  2119. my $user_id=$auth_info{$row->{auth_id}}{user_id};
  2120. $auth_info{$row->{auth_id}}{month}=$row->{traf_all};
  2121. $user_stats{$user_id}{month}+=$row->{traf_all};
  2122. }
  2123. foreach my $auth_id (keys %auth_info) {
  2124. next if (!$auth_info{$auth_id}{day_limit});
  2125. next if (!$auth_info{$auth_id}{month_limit});
  2126. my $day_limit=$auth_info{$auth_id}{day_limit}*$KB*$KB;
  2127. my $month_limit=$auth_info{$auth_id}{month_limit}*$KB*$KB;
  2128. my $blocked_d=($auth_info{$auth_id}{day}>$day_limit);
  2129. my $blocked_m=($auth_info{$auth_id}{month}>$month_limit);
  2130. if ($blocked_d or $blocked_m) {
  2131. my $history_msg;
  2132. if ($blocked_d) { $history_msg=printf "Day quota limit found for auth_id: $auth_id - Current: %d Max: %d",$auth_info{$auth_id}{day},$day_limit; }
  2133. if ($blocked_m) { $history_msg=printf "Month quota limit found for auth_id: $auth_id - Current: %d Max: %d",$auth_info{$auth_id}{month},$month_limit; }
  2134. do_sql($db,"UPDATE User_auth set blocked=1, changed=1 where id=$auth_id");
  2135. db_log_verbose($db,$history_msg);
  2136. }
  2137. }
  2138. foreach my $user_id (keys %user_stats) {
  2139. next if (!$user_stats{$user_id}{day_limit});
  2140. next if (!$user_stats{$user_id}{month_limit});
  2141. my $day_limit=$user_stats{$user_id}{day_limit}*$KB*$KB;
  2142. my $month_limit=$user_stats{$user_id}{month_limit}*$KB*$KB;
  2143. my $blocked_d=($user_stats{$user_id}{day}>$day_limit);
  2144. my $blocked_m=($user_stats{$user_id}{month}>$month_limit);
  2145. if ($blocked_d or $blocked_m) {
  2146. my $history_msg;
  2147. if ($blocked_d) { $history_msg=printf "Day quota limit found for user_id: $user_id - Current: %d Max: %d",$user_stats{$user_id}{day},$day_limit; }
  2148. if ($blocked_m) { $history_msg=printf "Month quota limit found for user_id: $user_id - Current: %d Max: %d",$user_stats{$user_id}{month},$month_limit; }
  2149. do_sql($db,"UPDATE User_user set blocked=1 where id=$user_id");
  2150. do_sql($db,"UPDATE User_auth set blocked=1, changed=1 where user_id=$user_id");
  2151. db_log_verbose($db,$history_msg);
  2152. }
  2153. }
  2154. Del_Variable($db,'RECALC');
  2155. }
  2156. #---------------------------------------------------------------------------------------------------------------
  2157. sub clean_variables {
  2158. my $db = shift;
  2159. #clean temporary variables
  2160. my $clean_variables = time();
  2161. my ($sec,$min,$hour,$day,$month,$year,$zone) = localtime($clean_variables);
  2162. $month++;
  2163. $year += 1900;
  2164. my $now_str=sprintf "%04d-%02d-%02d %02d:%02d:%02d",$year,$month,$day,$hour,$min,$sec;
  2165. my $clean_variables_date=$db->quote($now_str);
  2166. do_sql($db,"DELETE FROM `variables` WHERE clear_time<=$clean_variables_date");
  2167. #clean old AD computer cache
  2168. my $now = DateTime->now(time_zone=>'local');
  2169. my $day_dur = DateTime::Duration->new( days => 1 );
  2170. my $clean_date = $now - $day_dur;
  2171. my $clean_str = $db->quote($clean_date->ymd("-")." 00:00:00");
  2172. do_sql($db,"DELETE FROM `ad_comp_cache` WHERE last_found<=$clean_str");
  2173. }
  2174. #--------------------------------------------------------------------------------
  2175. sub process_dhcp_request {
  2176. my ($db, $type, $mac, $ip, $hostname, $client_id, $circuit_id, $remote_id) = @_;
  2177. return if (!$type);
  2178. return if ($type!~/(old|add|del)/i);
  2179. my $client_hostname='';
  2180. if ($hostname and ($hostname ne "undef" or $hostname !~ /UNDEFINED/i)) { $client_hostname=$hostname; }
  2181. my $auth_network = $office_networks->match_string($ip);
  2182. if (!$auth_network) {
  2183. log_error("Unknown network in dhcp request! IP: $ip");
  2184. return;
  2185. }
  2186. if (!$circuit_id) { $circuit_id=''; }
  2187. if (!$client_id) { $client_id = ''; }
  2188. if (!$remote_id) { $remote_id = ''; }
  2189. my $timestamp=time();
  2190. my $ip_aton=StrToIp($ip);
  2191. $mac=mac_splitted(isc_mac_simplify($mac));
  2192. my $dhcp_event_time = GetNowTime($timestamp);
  2193. my $dhcp_record;
  2194. $dhcp_record->{'mac'}=$mac;
  2195. $dhcp_record->{'ip'}=$ip;
  2196. $dhcp_record->{'ip_aton'}=$ip_aton;
  2197. $dhcp_record->{'hostname'}=$client_hostname;
  2198. $dhcp_record->{'network'}=$auth_network;
  2199. $dhcp_record->{'type'}=$type;
  2200. $dhcp_record->{'hostname_utf8'}=$client_hostname;
  2201. $dhcp_record->{'timestamp'} = $timestamp;
  2202. $dhcp_record->{'last_time'} = time();
  2203. $dhcp_record->{'circuit-id'} = $circuit_id;
  2204. $dhcp_record->{'client-id'} = $client_id;
  2205. $dhcp_record->{'remote-id'} = $remote_id;
  2206. $dhcp_record->{'hotspot'}=is_hotspot($dbh,$dhcp_record->{ip});
  2207. #search actual record
  2208. my $auth_record = get_record_sql($db,'SELECT * FROM User_auth WHERE ip="'.$dhcp_record->{ip}.'" and mac="'.$mac.'" and deleted=0 ORDER BY last_found DESC');
  2209. #if record not found and type del => next event
  2210. if (!$auth_record and $type eq 'del') { return; }
  2211. #if record not found - create it
  2212. if (!$auth_record and $type=~/(add|old)/i) {
  2213. # db_log_warning($db,"Record for dhcp request type: ".$type." ip=".$dhcp_record->{ip}." and mac=".$mac." does not exists!");
  2214. my $res_id = resurrection_auth($db,$dhcp_record);
  2215. if (!$res_id) { db_log_error($db,"Error creating an ip address record for ip=".$dhcp_record->{ip}." and mac=".$mac."!"); return; }
  2216. $auth_record = get_record_sql($db,'SELECT * FROM User_auth WHERE id='.$res_id);
  2217. db_log_info($db,"Check for new auth. Found id: $res_id",$res_id);
  2218. }
  2219. my $auth_id = $auth_record->{id};
  2220. my $auth_ou_id = $auth_record->{ou_id};
  2221. $dhcp_record->{'auth_id'} = $auth_id;
  2222. $dhcp_record->{'auth_ou_id'} = $auth_ou_id;
  2223. log_debug(uc($type).">>");
  2224. log_debug("MAC: ".$dhcp_record->{'mac'});
  2225. log_debug("IP: ".$dhcp_record->{'ip'});
  2226. log_debug("CIRCUIT-ID: ".$dhcp_record->{'circuit-id'});
  2227. log_debug("REMOTE-ID: ".$dhcp_record->{'remote-id'});
  2228. log_debug("HOSTNAME: ".$dhcp_record->{'hostname'});
  2229. log_debug("TYPE: ".$dhcp_record->{'type'});
  2230. log_debug("TIME: ".$dhcp_event_time);
  2231. log_debug("AUTH_ID: ".$auth_id);
  2232. log_debug("END GET");
  2233. update_dns_record_by_dhcp($db,$dhcp_record,$auth_record);
  2234. if ($type=~/add/i and $dhcp_record->{hostname_utf8}) {
  2235. my $auth_rec;
  2236. $auth_rec->{dhcp_hostname} = $dhcp_record->{hostname_utf8};
  2237. $auth_rec->{dhcp_time}=$dhcp_event_time;
  2238. $auth_rec->{arp_found}=$dhcp_event_time;
  2239. $auth_rec->{created_by}='dhcp';
  2240. db_log_verbose($db,"Add lease by dhcp event for dynamic clients id: $auth_id ip: $dhcp_record->{ip}",$auth_id);
  2241. update_record($db,'User_auth',$auth_rec,"id=$auth_id");
  2242. }
  2243. if ($type=~/old/i) {
  2244. my $auth_rec;
  2245. $auth_rec->{dhcp_action}=$type;
  2246. $auth_rec->{dhcp_time}=$dhcp_event_time;
  2247. $auth_rec->{created_by}='dhcp';
  2248. $auth_rec->{arp_found}=$dhcp_event_time;
  2249. db_log_verbose($db,"Update lease by dhcp event for dynamic clients id: $auth_id ip: $dhcp_record->{ip}",$auth_id);
  2250. update_record($db,'User_auth',$auth_rec,"id=$auth_id");
  2251. }
  2252. if ($type=~/del/i and $auth_id) {
  2253. if ($auth_record->{dhcp_time} =~ /([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})/) {
  2254. my $d_time = mktime($6,$5,$4,$3,$2-1,$1-1900);
  2255. if (time()-$d_time>60 and (is_dynamic_ou($db,$auth_ou_id) or is_default_ou($db,$auth_ou_id))) {
  2256. db_log_info($db,"Remove user ip record by dhcp release event for dynamic clients id: $auth_id ip: $dhcp_record->{ip}",$auth_id);
  2257. my $auth_rec;
  2258. $auth_rec->{dhcp_action}=$type;
  2259. $auth_rec->{dhcp_time}=$dhcp_event_time;
  2260. update_record($db,'User_auth',$auth_rec,"id=$auth_id");
  2261. #remove user auth record if it belongs to the default pool or it is dynamic
  2262. if (is_default_ou($db,$auth_ou_id) or (is_dynamic_ou($db,$auth_ou_id) and $auth_record->{dynamic})) {
  2263. delete_user_auth($db,$auth_id);
  2264. my $u_count=get_count_records($db,'User_auth','deleted=0 and user_id='.$auth_record->{'user_id'});
  2265. if (!$u_count) { delete_user($db,$auth_record->{'user_id'}); }
  2266. }
  2267. }
  2268. }
  2269. }
  2270. if ($dhcp_record->{hotspot} and $ignore_hotspot_dhcp_log) { return $dhcp_record; }
  2271. if ($ignore_update_dhcp_event and $type=~/old/i) { return $dhcp_record; }
  2272. my $dhcp_log;
  2273. if (!$auth_id) { $auth_id=0; }
  2274. $dhcp_log->{'auth_id'} = $auth_id;
  2275. $dhcp_log->{'ip'} = $dhcp_record->{'ip'};
  2276. $dhcp_log->{'ip_int'} = $dhcp_record->{'ip_aton'};
  2277. $dhcp_log->{'mac'} = $dhcp_record->{'mac'};
  2278. $dhcp_log->{'action'} = $type;
  2279. $dhcp_log->{'dhcp_hostname'} = $dhcp_record->{'hostname_utf8'};
  2280. $dhcp_log->{'timestamp'} = $dhcp_event_time;
  2281. $dhcp_log->{'circuit-id'} = $circuit_id;
  2282. $dhcp_log->{'client-id'} = $client_id;
  2283. $dhcp_log->{'remote-id'} = $remote_id;
  2284. insert_record($db,'dhcp_log',$dhcp_log);
  2285. return $dhcp_record;
  2286. }
  2287. #---------------------------------------------------------------------------------------------------------------
  2288. #skip init for upgrade
  2289. if ($MY_NAME!~/upgrade.pl/) {
  2290. $dbh=init_db();
  2291. init_option($dbh);
  2292. clean_variables($dbh);
  2293. Set_Variable($dbh);
  2294. }
  2295. 1;
  2296. }