database.pm 70 KB

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