1
0

database.pm 88 KB

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