database.pm 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097
  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. #disable update field 'created_by'
  424. if ($old_record->{'created_by'} and exists ($record->{'created_by'})) { delete $record->{'created_by'}; }
  425. foreach my $field (keys %$record) {
  426. if (exists $acl_fields{$field}) { $record->{changed}="1"; }
  427. if (exists $dhcp_fields{$field}) { $record->{dhcp_changed}="1"; }
  428. if (exists $dns_fields{$field}) { $dns_changed=1; }
  429. }
  430. }
  431. foreach my $field (keys %$record) {
  432. if (!defined $record->{$field}) { $record->{$field}=''; }
  433. if (!defined $old_record->{$field}) { $old_record->{$field}=''; }
  434. my $old_value = quotemeta($old_record->{$field});
  435. my $new_value = $record->{$field};
  436. $new_value=~s/\'//g;
  437. $new_value=~s/\"//g;
  438. if ($new_value!~/^$old_value$/) {
  439. $diff = $diff." $field => $record->{$field} (old: $old_record->{$field}),";
  440. $change_str = $change_str." `$field`=".$db->quote($record->{$field}).",";
  441. $found_changed++;
  442. }
  443. }
  444. if ($found_changed) {
  445. $change_str=~s/\,$//;
  446. $diff=~s/\,$//;
  447. if ($table eq 'User_auth') {
  448. $change_str .= ", `changed_time`='".GetNowTime()."'";
  449. if ($dns_changed) {
  450. my $del_dns;
  451. if ($old_record->{'dns_name'} and $old_record->{'ip'}) {
  452. $del_dns->{'name_type'}='A';
  453. $del_dns->{'name'}=$old_record->{'dns_name'};
  454. $del_dns->{'value'}=$old_record->{'ip'};
  455. $del_dns->{'type'}='del';
  456. if ($rec_id) { $del_dns->{'auth_id'}=$rec_id; }
  457. insert_record($db,'dns_queue',$del_dns);
  458. }
  459. my $new_dns;
  460. my $dns_rec_ip = $old_record->{ip};
  461. my $dns_rec_name = $old_record->{dns_name};
  462. if ($record->{'dns_name'}) { $dns_rec_name = $record->{'dns_name'}; }
  463. if ($record->{'ip'}) { $dns_rec_ip = $record->{'ip'}; }
  464. if ($dns_rec_name and $dns_rec_ip) {
  465. $new_dns->{'name_type'}='A';
  466. $new_dns->{'name'}=$dns_rec_name;
  467. $new_dns->{'value'}=$dns_rec_ip;
  468. $new_dns->{'type'}='add';
  469. if ($rec_id) { $new_dns->{'auth_id'}=$rec_id; }
  470. insert_record($db,'dns_queue',$new_dns);
  471. }
  472. }
  473. }
  474. if ($table eq 'User_auth_alias') {
  475. if ($dns_changed) {
  476. my $del_dns;
  477. if ($old_record->{'alias'}) {
  478. $del_dns->{'name_type'}='CNAME';
  479. $del_dns->{'name'}=$old_record->{'alias'};
  480. $del_dns->{'type'}='del';
  481. $del_dns->{'value'}=get_dns_name($db,$old_record->{auth_id});
  482. $del_dns->{'auth_id'}=$old_record->{auth_id};
  483. insert_record($db,'dns_queue',$del_dns);
  484. }
  485. my $new_dns;
  486. my $dns_rec_name = $old_record->{alias};
  487. if ($record->{'alias'}) { $dns_rec_name = $record->{'alias'}; }
  488. if ($dns_rec_name) {
  489. $new_dns->{'name_type'}='CNAME';
  490. $new_dns->{'name'}=$dns_rec_name;
  491. $new_dns->{'type'}='add';
  492. $new_dns->{'value'}=get_dns_name($db,$old_record->{auth_id});
  493. $new_dns->{'auth_id'}=$rec_id;
  494. insert_record($db,'dns_queue',$new_dns);
  495. }
  496. }
  497. }
  498. my $sSQL = "UPDATE $table SET $change_str WHERE $filter";
  499. db_log_debug($db,'Change table '.$table.' for '.$filter.' set: '.$diff, $rec_id);
  500. do_sql($db,$sSQL);
  501. } else {
  502. db_log_debug($db,'Nothing change. Skip update.');
  503. }
  504. return 1;
  505. }
  506. #---------------------------------------------------------------------------------------------------------------
  507. sub insert_record {
  508. my $db = shift;
  509. my $table = shift;
  510. my $record = shift;
  511. return if (!$db);
  512. return if (!$table);
  513. my $change_str='';
  514. my $fields='';
  515. my $values='';
  516. my $new_str='';
  517. my $dns_changed = 0;
  518. if ($table eq "User_auth") {
  519. foreach my $field (keys %$record) {
  520. if (exists $acl_fields{$field}) { $record->{changed}="1"; }
  521. if (exists $dhcp_fields{$field}) { $record->{dhcp_changed}="1"; }
  522. if (exists $dns_fields{$field}) { $dns_changed=1; }
  523. }
  524. }
  525. foreach my $field (keys %$record) {
  526. if (!defined $record->{$field}) { $record->{$field}=''; }
  527. my $new_value = $record->{$field};
  528. $new_value=~s/\'//g;
  529. $new_value=~s/\"//g;
  530. $record->{$field} = $new_value;
  531. $fields = $fields."`$field`,";
  532. $values = $values." ".$db->quote($record->{$field}).",";
  533. $new_str = $new_str." $field => $record->{$field},";
  534. }
  535. $fields=~s/,$//;
  536. $values=~s/,$//;
  537. $new_str=~s/,$//;
  538. my $sSQL = "INSERT INTO $table($fields) VALUES($values)";
  539. my $result = do_sql($db,$sSQL);
  540. if ($result) {
  541. $new_str='id: '.$result.' '.$new_str;
  542. if ($table eq 'User_auth_alias' and $dns_changed) {
  543. if ($record->{'alias'}) {
  544. my $add_dns;
  545. $add_dns->{'name_type'}='CNAME';
  546. $add_dns->{'name'}=$record->{'alias'};
  547. $add_dns->{'value'}=get_dns_name($db,$record->{'auth_id'});
  548. $add_dns->{'type'}='add';
  549. $add_dns->{'auth_id'}=$record->{'auth_id'};
  550. insert_record($db,'dns_queue',$add_dns);
  551. }
  552. }
  553. if ($table eq 'User_auth' and $dns_changed) {
  554. if ($record->{'dns_name'} and $record->{'ip'} and $dns_changed) {
  555. my $add_dns;
  556. $add_dns->{'name_type'}='A';
  557. $add_dns->{'name'}=$record->{'dns_name'};
  558. $add_dns->{'value'}=$record->{'ip'};
  559. $add_dns->{'type'}='add';
  560. $add_dns->{'auth_id'}=$result;
  561. insert_record($db,'dns_queue',$add_dns);
  562. }
  563. }
  564. }
  565. db_log_debug($db,'Add record to table '.$table.' '.$new_str);
  566. return $result;
  567. }
  568. #---------------------------------------------------------------------------------------------------------------
  569. sub delete_record {
  570. my $db = shift;
  571. my $table = shift;
  572. my $filter = shift;
  573. return if (!$db);
  574. return if (!$table);
  575. return if (!$filter);
  576. my $old_record = get_record_sql($db,"SELECT * FROM $table WHERE $filter");
  577. my $diff='';
  578. foreach my $field (keys %$old_record) {
  579. if (!$old_record->{$field}) { $old_record->{$field}=''; }
  580. $diff = $diff." $field => $old_record->{$field},";
  581. }
  582. $diff=~s/,$//;
  583. db_log_debug($db,'Delete record from table '.$table.' value: '.$diff);
  584. #never delete user ip record!
  585. if ($table eq 'User_auth') {
  586. my $sSQL = "UPDATE User_auth SET changed=1, deleted=1, changed_time='".GetNowTime()."' WHERE ".$filter;
  587. do_sql($db,$sSQL);
  588. if ($old_record->{'dns_name'} and $old_record->{'ip'}) {
  589. my $del_dns;
  590. $del_dns->{'name_type'}='A';
  591. $del_dns->{'name'}=$old_record->{'dns_name'};
  592. $del_dns->{'value'}=$old_record->{'ip'};
  593. $del_dns->{'type'}='del';
  594. $del_dns->{'auth_id'}=$old_record->{'id'};
  595. insert_record($db,'dns_queue',$del_dns);
  596. }
  597. }
  598. if ($table eq 'User_auth_alias') {
  599. if ($old_record->{'alias'} and $old_record->{'auth_id'}) {
  600. my $del_dns;
  601. $del_dns->{'name_type'}='CNAME';
  602. $del_dns->{'name'}=$old_record->{'alias'};
  603. $del_dns->{'value'}=get_dns_name($db,$old_record->{'auth_id'});
  604. $del_dns->{'type'}='del';
  605. $del_dns->{'auth_id'}=$old_record->{'auth_id'};
  606. insert_record($db,'dns_queue',$del_dns);
  607. }
  608. }
  609. my $sSQL = "DELETE FROM ".$table." WHERE ".$filter;
  610. return do_sql($db,$sSQL);
  611. }
  612. #---------------------------------------------------------------------------------------------------------------
  613. sub GetNowTime {
  614. my ($sec,$min,$hour,$day,$month,$year,$zone) = localtime(time());
  615. $month += 1;
  616. $year += 1900;
  617. my $now_str=sprintf "%04d-%02d-%02d %02d:%02d:%02d",$year,$month,$day,$hour,$min,$sec;
  618. return $now_str;
  619. }
  620. #---------------------------------------------------------------------------------------------------------------
  621. sub is_hotspot {
  622. my $db = shift;
  623. my $ip = shift;
  624. my $users = new Net::Patricia;
  625. #check hotspot
  626. my @ip_rules = get_records_sql($db,'SELECT * FROM subnets WHERE hotspot=1 AND LENGTH(subnet)>0');
  627. foreach my $row (@ip_rules) { $users->add_string($row->{subnet}); }
  628. if ($users->match_string($ip)) { return 1; }
  629. return 0;
  630. }
  631. #---------------------------------------------------------------------------------------------------------------
  632. sub get_new_user_id {
  633. my $db = shift;
  634. my $ip = shift;
  635. my $mac = shift;
  636. my $hostname = shift;
  637. my $result;
  638. #check user rules
  639. $mac = mac_simplify($mac);
  640. $result->{ip} = $ip;
  641. $result->{mac} = mac_splitted($mac);
  642. $result->{dhcp_hostname} = $hostname;
  643. $result->{ou_id}=undef;
  644. $result->{user_id}=undef;
  645. #check ip
  646. if (defined $ip and $ip) {
  647. my $users = new Net::Patricia;
  648. #check ip rules
  649. my @ip_rules = get_records_sql($db,'SELECT * FROM auth_rules WHERE type=1 and LENGTH(rule)>0 AND user_id IS NOT NULL');
  650. foreach my $row (@ip_rules) { eval { $users->add_string($row->{rule},$row->{user_id}); }; }
  651. if ($users->match_string($ip)) { $result->{user_id}=$users->match_string($ip); }
  652. }
  653. #check mac
  654. if (defined $mac and $mac) {
  655. my @user_rules=get_records_sql($db,'SELECT * FROM auth_rules WHERE type=2 AND LENGTH(rule)>0 AND user_id IS NOT NULL');
  656. foreach my $user (@user_rules) {
  657. my $rule = mac_simplify($user->{rule});
  658. if ($mac=~/$rule/i) { $result->{user_id}=$user->{user_id}; }
  659. }
  660. }
  661. #check hostname
  662. if (defined $hostname and $hostname) {
  663. my @user_rules=get_records_sql($db,'SELECT * FROM auth_rules WHERE type=3 AND LENGTH(rule)>0 AND user_id IS NOT NULL');
  664. foreach my $user (@user_rules) {
  665. if ($hostname=~/$user->{rule}/i) { $result->{user_id}=$user->{user_id}; }
  666. }
  667. }
  668. #
  669. if ($result->{user_id}) { return $result; }
  670. #check ou rules
  671. #check ip
  672. if (defined $ip and $ip) {
  673. my $users = new Net::Patricia;
  674. #check hotspot
  675. my @ip_rules = get_records_sql($db,'SELECT * FROM subnets WHERE hotspot=1 AND LENGTH(subnet)>0');
  676. foreach my $row (@ip_rules) { $users->add_string($row->{subnet},$default_hotspot_ou_id); }
  677. if ($users->match_string($ip)) { $result->{ou_id}=$users->match_string($ip); }
  678. #check ip rules
  679. @ip_rules = get_records_sql($db,'SELECT * FROM auth_rules WHERE type=1 and LENGTH(rule)>0 AND ou_id IS NOT NULL');
  680. foreach my $row (@ip_rules) { eval { $users->add_string($row->{rule},$row->{ou_id}); }; }
  681. if ($users->match_string($ip)) { $result->{ou_id}=$users->match_string($ip); }
  682. }
  683. #check mac
  684. if (defined $mac and $mac) {
  685. my @user_rules=get_records_sql($db,'SELECT * FROM auth_rules WHERE type=2 AND LENGTH(rule)>0 AND ou_id IS NOT NULL');
  686. foreach my $user (@user_rules) {
  687. my $rule = mac_simplify($user->{rule});
  688. if ($mac=~/$rule/i) { $result->{ou_id}=$user->{ou_id}; }
  689. }
  690. }
  691. #check hostname
  692. if (defined $hostname and $hostname) {
  693. my @user_rules=get_records_sql($db,'SELECT * FROM auth_rules WHERE type=3 AND LENGTH(rule)>0 AND ou_id IS NOT NULL');
  694. foreach my $user (@user_rules) {
  695. if ($hostname=~/$user->{rule}/i) { $result->{ou_id}=$user->{ou_id}; }
  696. }
  697. }
  698. if (!$result->{ou_id}) { $result->{ou_id}=$default_user_ou_id; }
  699. return $result;
  700. }
  701. #---------------------------------------------------------------------------------------------------------------
  702. sub set_changed {
  703. my $db = shift;
  704. my $id = shift;
  705. return if (!$db or !$id);
  706. my $update_record;
  707. $update_record->{changed}=1;
  708. update_record($db,'User_auth',$update_record,"id=$id");
  709. }
  710. #---------------------------------------------------------------------------------------------------------------
  711. sub update_dns_record {
  712. my $hdb = shift;
  713. my $auth_id = shift;
  714. return if (!$config_ref{enable_dns_updates});
  715. #get domain
  716. my $ad_zone = get_option($hdb,33);
  717. #get dns server
  718. my $ad_dns = get_option($hdb,3);
  719. my $enable_ad_dns_update = ($ad_zone and $ad_dns and $config_ref{enable_dns_updates});
  720. log_debug("Auth id: ".$auth_id);
  721. log_debug("enable_ad_dns_update: ".$enable_ad_dns_update);
  722. log_debug("DNS update flags - zone: ".$ad_zone.", dns: ".$ad_dns.", enable_ad_dns_update: ".$enable_ad_dns_update);
  723. my @dns_queue = get_records_sql($hdb,"SELECT * FROM dns_queue WHERE auth_id=".$auth_id." ORDER BY id ASC");
  724. if (!@dns_queue or !scalar @dns_queue) { return; }
  725. foreach my $dns_cmd (@dns_queue) {
  726. my $fqdn = '';
  727. my $fqdn_ip = '';
  728. my $fqdn_parent = '';
  729. my $static_exists = 0;
  730. my $static_ref = '';
  731. my $static_ok = 0;
  732. eval {
  733. if ($dns_cmd->{name_type}=~/^cname$/i) {
  734. $fqdn=lc($dns_cmd->{name});
  735. $fqdn=~s/\.$ad_zone$//i;
  736. $fqdn=~s/\.$//;
  737. if ($dns_cmd->{value}) {
  738. $fqdn_parent=lc($dns_cmd->{value});
  739. $fqdn_parent=~s/\.$ad_zone$//i;
  740. $fqdn_parent=~s/\.$//;
  741. }
  742. #skip update unknown domain
  743. if ($fqdn =~/\./ or $fqdn_parent =~/\./) { next; }
  744. $fqdn = $fqdn.".".$ad_zone;
  745. $fqdn_parent = $fqdn_parent.".".$ad_zone;
  746. #remove cname
  747. if ($dns_cmd->{type} eq 'del') {
  748. delete_dns_cname($fqdn_parent,$fqdn,$ad_zone,$ad_dns,$hdb);
  749. }
  750. #create cname
  751. if ($dns_cmd->{type} eq 'add') {
  752. create_dns_cname($fqdn_parent,$fqdn,$ad_zone,$ad_dns,$hdb);
  753. }
  754. }
  755. if ($dns_cmd->{name_type}=~/^a$/i) {
  756. $fqdn=lc($dns_cmd->{name});
  757. $fqdn=~s/\.$ad_zone$//i;
  758. $fqdn=~s/\.$//;
  759. if (!$dns_cmd->{value}) { next; }
  760. $fqdn_ip=lc($dns_cmd->{value});
  761. #skip update unknown domain
  762. if ($fqdn =~/\./) { next; }
  763. $fqdn = $fqdn.".".$ad_zone;
  764. #dns update disabled?
  765. my $maybe_update_dns=( $enable_ad_dns_update and $office_networks->match_string($fqdn_ip) );
  766. if (!$maybe_update_dns) {
  767. db_log_info($hdb,"FOUND Auth_id: $auth_id. DNS update disabled.");
  768. next;
  769. }
  770. #get aliases
  771. my @aliases = get_records_sql($hdb,"SELECT * FROM User_auth_alias WHERE auth_id=".$auth_id);
  772. #remove A & PTR
  773. if ($dns_cmd->{type} eq 'del') {
  774. #remove aliases
  775. if (@aliases and scalar @aliases) {
  776. foreach my $alias (@aliases) {
  777. delete_dns_cname($fqdn,$alias->{alias},$ad_zone,$ad_dns,$hdb) if ($alias->{alias});
  778. delete_dns_hostname($fqdn,$alias->{alias},$ad_zone,$ad_dns,$hdb) if ($alias->{alias});
  779. }
  780. }
  781. #remove main record
  782. delete_dns_hostname($fqdn,$fqdn_ip,$ad_zone,$ad_dns,$hdb);
  783. delete_dns_ptr($fqdn,$fqdn_ip,$ad_zone,$ad_dns,$hdb);
  784. }
  785. #create A & PTR
  786. if ($dns_cmd->{type} eq 'add') {
  787. my @dns_record=ResolveNames($fqdn,$dns_server);
  788. $static_exists = (scalar @dns_record>0);
  789. if ($static_exists) {
  790. $static_ref = join(' ',@dns_record);
  791. foreach my $dns_a (@dns_record) {
  792. if ($dns_a=~/^$fqdn_ip$/) { $static_ok = 1; }
  793. }
  794. db_log_debug($hdb,"Dns record for static record $fqdn: $static_ref");
  795. }
  796. #skip update if already exists
  797. if ($static_ok) {
  798. db_log_debug($hdb,"Static record for $fqdn [$static_ok] correct.");
  799. next;
  800. }
  801. #create record
  802. create_dns_hostname($fqdn,$fqdn_ip,$ad_zone,$ad_dns,$hdb);
  803. create_dns_ptr($fqdn,$fqdn_ip,$ad_zone,$ad_dns,$hdb);
  804. #create aliases
  805. if (@aliases and scalar @aliases) {
  806. foreach my $alias (@aliases) {
  807. create_dns_cname($fqdn,$alias->{alias},$ad_zone,$ad_dns,$hdb) if ($alias->{alias});
  808. }
  809. }
  810. }
  811. }
  812. };
  813. if ($@) { log_error("Error dns commands: $@"); }
  814. }
  815. }
  816. #---------------------------------------------------------------------------------------------------------------
  817. sub is_ad_computer {
  818. my $hdb = shift;
  819. my $computer_name = shift;
  820. if (!$computer_name or $computer_name =~/UNDEFINED/i) { return 0; }
  821. my $ad_check = get_option($hdb,73);
  822. if (!$ad_check) { return 1; }
  823. my $ad_zone = get_option($hdb,33);
  824. if ($computer_name =~/\./) {
  825. if ($computer_name!~/\.$ad_zone$/i) {
  826. db_log_verbose($hdb,"The domain of the computer $computer_name does not match the domain of the organization $ad_zone. Skip update.");
  827. return 0;
  828. }
  829. }
  830. if ($computer_name =~/^(.+)\./) {
  831. $computer_name = $1;
  832. }
  833. my $ad_computer_name = trim($computer_name).'$';
  834. my $name_in_cache = get_record_sql($hdb,"SELECT * FROM ad_comp_cache WHERE name='".$computer_name."'");
  835. if ($name_in_cache) { return 1; }
  836. my %name_found=do_exec_ref('/usr/bin/getent passwd '.$ad_computer_name);
  837. if (!$name_found{output} or $name_found{status} ne 0) {
  838. db_log_verbose($hdb,"The computer ".uc($ad_computer_name)." was not found in the domain $ad_zone. Skip update.");
  839. return 0;
  840. }
  841. do_sql($hdb,"INSERT INTO ad_comp_cache(name) VALUES('".$computer_name."') ON DUPLICATE KEY UPDATE name='".$computer_name."';");
  842. return 1;
  843. }
  844. #---------------------------------------------------------------------------------------------------------------
  845. sub update_dns_record_by_dhcp {
  846. my $hdb = shift;
  847. my $dhcp_record = shift;
  848. my $auth_record = shift;
  849. return if (!$config_ref{enable_dns_updates});
  850. my $ad_zone = get_option($hdb,33);
  851. my $ad_dns = get_option($hdb,3);
  852. $update_hostname_from_dhcp = get_option($hdb,46) || 0;
  853. my $subnets_dhcp = get_subnets_ref($hdb);
  854. my $enable_ad_dns_update = ($ad_zone and $ad_dns and $update_hostname_from_dhcp);
  855. log_debug("Dhcp record: ".Dumper($dhcp_record));
  856. log_debug("Subnets: ".Dumper($subnets_dhcp->{$dhcp_record->{network}->{subnet}}));
  857. log_debug("enable_ad_dns_update: ".$enable_ad_dns_update);
  858. 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);
  859. 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});
  860. if (!$maybe_update_dns) {
  861. db_log_debug($hdb,"FOUND Auth_id: $auth_record->{id}. DNS update don't needed.");
  862. return 0;
  863. }
  864. log_debug("DNS update enabled.");
  865. #update dns block
  866. my $fqdn_static;
  867. if ($auth_record->{dns_name}) {
  868. $fqdn_static=lc($auth_record->{dns_name});
  869. if ($fqdn_static!~/\.$ad_zone$/i) {
  870. $fqdn_static=~s/\.$//;
  871. $fqdn_static=lc($fqdn_static.'.'.$ad_zone);
  872. }
  873. }
  874. my $fqdn=lc(trim($dhcp_record->{hostname_utf8}));
  875. if ($fqdn!~/\.$ad_zone$/i) {
  876. $fqdn=~s/\.$//;
  877. $fqdn=lc($fqdn.'.'.$ad_zone);
  878. }
  879. db_log_debug($hdb,"FOUND Auth_id: $auth_record->{id} dns_name: $fqdn_static dhcp_hostname: $fqdn");
  880. #check exists static dns name
  881. my $static_exists = 0;
  882. my $dynamic_exists = 0;
  883. my $static_ok = 0;
  884. my $dynamic_ok = 0;
  885. my $static_ref;
  886. my $dynamic_ref;
  887. if ($fqdn_static ne '') {
  888. my @dns_record=ResolveNames($fqdn_static,$dns_server);
  889. $static_exists = (scalar @dns_record>0);
  890. if ($static_exists) {
  891. $static_ref = join(' ',@dns_record);
  892. foreach my $dns_a (@dns_record) {
  893. if ($dns_a=~/^$dhcp_record->{ip}$/) { $static_ok = $dns_a; }
  894. }
  895. }
  896. } else { $static_ok = 1; }
  897. if ($fqdn ne '') {
  898. my @dns_record=ResolveNames($fqdn,$dns_server);
  899. $dynamic_exists = (scalar @dns_record>0);
  900. if ($dynamic_exists) {
  901. $dynamic_ref = join(' ',@dns_record);
  902. foreach my $dns_a (@dns_record) {
  903. if ($dns_a=~/^$dhcp_record->{ip}$/) { $dynamic_ok = $dns_a; }
  904. }
  905. }
  906. }
  907. db_log_debug($hdb,"Dns record for static record $fqdn_static: $static_ok");
  908. db_log_debug($hdb,"Dns record for dhcp-hostname $fqdn: $dynamic_ok");
  909. if ($fqdn_static ne '') {
  910. if (!$static_ok) {
  911. db_log_info($hdb,"Static record mismatch! Expected $fqdn_static => $dhcp_record->{ip}, recivied: $static_ref");
  912. if (!$static_exists) {
  913. db_log_info($hdb,"Static dns hostname defined but not found. Create it ($fqdn_static => $dhcp_record->{ip})!");
  914. create_dns_hostname($fqdn_static,$dhcp_record->{ip},$ad_zone,$ad_dns,$hdb);
  915. }
  916. } else {
  917. db_log_debug($hdb,"Static record for $fqdn_static [$static_ok] correct.");
  918. }
  919. }
  920. if ($fqdn ne '' and $dynamic_ok ne '') { db_log_debug($hdb,"Dynamic record for $fqdn [$dynamic_ok] correct. No changes required."); }
  921. if ($fqdn ne '' and !$dynamic_ok) {
  922. #log event without email alert
  923. log_error("Dynamic record mismatch! Expected: $fqdn => $dhcp_record->{ip}, recivied: $dynamic_ref. Checking the status.");
  924. #check exists hostname
  925. my $another_hostname_exists = 0;
  926. my $hostname_filter = ' LOWER(dns_name) REGEXP("^'.lc($dhcp_record->{hostname_utf8}).'\.*$")';
  927. if ($fqdn_static ne '' and $fqdn !~/$fqdn_static/) {
  928. $hostname_filter = $hostname_filter . ' or LOWER(dns_name) REGEXP("^'.lc($auth_record->{dns_name}).'\.*$")';
  929. }
  930. #check exists another records with some static hostname
  931. my $filter_sql = 'SELECT * FROM User_auth WHERE id<>'.$auth_record->{id}.' and deleted=0 and ('.$hostname_filter.') ORDER BY last_found DESC';
  932. db_log_debug($hdb,"Search dhcp hostname by: ".$filter_sql);
  933. my $name_record = get_record_sql($hdb,$filter_sql);
  934. if ($name_record->{dns_name} =~/^$fqdn$/i or $name_record->{dns_name} =~/^$dhcp_record->{hostname_utf8}$/i) {
  935. $another_hostname_exists = 1;
  936. }
  937. if (!$another_hostname_exists) {
  938. if ($fqdn_static and $fqdn_static ne '') {
  939. if ($fqdn_static!~/$fqdn/) {
  940. db_log_info($hdb,"Hostname from dhcp request $fqdn differs from static dns hostname $fqdn_static. Ignore dynamic binding!");
  941. # delete_dns_hostname($fqdn,$dhcp_record->{ip},$ad_zone,$ad_dns,$hdb);
  942. # create_dns_hostname($fqdn,$dhcp_record->{ip},$ad_zone,$ad_dns,$hdb);
  943. }
  944. } else {
  945. db_log_info($hdb,"Rewrite aliases if exists for $fqdn => $dhcp_record->{ip}");
  946. #get and remove aliases
  947. my @aliases = get_records_sql($hdb,"SELECT * FROM User_auth_alias WHERE auth_id=".$auth_record->{id});
  948. if (@aliases and scalar @aliases) {
  949. foreach my $alias (@aliases) {
  950. delete_dns_cname($fqdn_static,$alias->{alias},$ad_zone,$ad_dns,$hdb) if ($alias->{alias});
  951. }
  952. }
  953. db_log_info($hdb,"Static dns hostname not defined. Create dns record by dhcp request. $fqdn => $dhcp_record->{ip}");
  954. create_dns_hostname($fqdn,$dhcp_record->{ip},$ad_zone,$ad_dns,$hdb);
  955. if (@aliases and scalar @aliases) {
  956. foreach my $alias (@aliases) {
  957. create_dns_cname($fqdn_static,$alias->{alias},$ad_zone,$ad_dns,$hdb) if ($alias->{alias});
  958. }
  959. }
  960. }
  961. } else {
  962. 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.");
  963. }
  964. }
  965. #end update dns block
  966. }
  967. #------------------------------------------------------------------------------------------------------------
  968. sub apply_device_lock {
  969. my $db = shift;
  970. my $device_id = shift;
  971. my $iteration = shift || 0;
  972. $iteration++;
  973. if ($iteration>2) { return 0; }
  974. 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);
  975. if (!$dev) { return 0; }
  976. if (!$dev->{'discovery_locked'}) { return set_lock_discovery($db,$device_id); }
  977. #if timestamp undefined, set and return
  978. if (!$dev->{'locked_timestamp'}) { return set_lock_discovery($db,$device_id); }
  979. #wait for discovery
  980. my $wait_time = $dev->{'locked_timestamp'} + 30 - time();
  981. if ($wait_time<0) { return set_lock_discovery($db,$device_id); }
  982. sleep($wait_time);
  983. return apply_device_lock($db,$device_id,$iteration);
  984. }
  985. #------------------------------------------------------------------------------------------------------------
  986. sub set_lock_discovery {
  987. my $db = shift;
  988. my $device_id = shift;
  989. my $new;
  990. $new->{'discovery_locked'} = 1;
  991. $new->{'locked_timestamp'} = GetNowTime();
  992. if (update_record($db,'devices',$new,'id='.$device_id)) { return 1; }
  993. return 0;
  994. }
  995. #------------------------------------------------------------------------------------------------------------
  996. sub unset_lock_discovery {
  997. my $db = shift;
  998. my $device_id = shift;
  999. my $new;
  1000. $new->{'discovery_locked'} = 0;
  1001. $new->{'locked_timestamp'} = GetNowTime();
  1002. if (update_record($db,'devices',$new,'id='.$device_id)) { return 1; }
  1003. return 0;
  1004. }
  1005. #------------------------------------------------------------------------------------------------------------
  1006. sub create_dns_cname {
  1007. my $fqdn = shift;
  1008. my $alias = shift;
  1009. my $zone = shift;
  1010. my $server = shift;
  1011. my $db = shift;
  1012. #skip update domain controllers
  1013. if (!$db) {
  1014. log_info("DNS-UPDATE: Zone $zone Server: $server CNAME: $alias for $fqdn");
  1015. } else {
  1016. db_log_info($db,"DNS-UPDATE: Zone $zone Server: $server CNAME: $alias for $fqdn ");
  1017. }
  1018. my $ad_zone = get_option($db,33);
  1019. my $nsupdate_file = "/tmp/".$fqdn."-nsupdate";
  1020. my @add_dns;
  1021. if ($config_ref{dns_server_type}=~/windows/i) {
  1022. push(@add_dns,"gsstsig");
  1023. push(@add_dns,"server $server");
  1024. push(@add_dns,"zone $zone");
  1025. push(@add_dns,"update add $alias 3600 cname $fqdn.");
  1026. push(@add_dns,"send");
  1027. write_to_file($nsupdate_file,\@add_dns);
  1028. do_exec('/usr/bin/kinit -k -t /opt/Eye/scripts/cfg/dns_updater.keytab dns_updater@'.uc($ad_zone).' && /usr/bin/nsupdate "'.$nsupdate_file.'"');
  1029. }
  1030. if ($config_ref{dns_server_type}=~/bind/i) {
  1031. push(@add_dns,"server $server");
  1032. push(@add_dns,"zone $zone");
  1033. push(@add_dns,"update add $alias 3600 cname $fqdn.");
  1034. push(@add_dns,"send");
  1035. write_to_file($nsupdate_file,\@add_dns);
  1036. do_exec('/usr/bin/nsupdate -k /etc/bind/rndc.key "'.$nsupdate_file.'"');
  1037. }
  1038. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  1039. }
  1040. #---------------------------------------------------------------------------------------------------------------
  1041. sub delete_dns_cname {
  1042. my $fqdn = shift;
  1043. my $alias = shift;
  1044. my $zone = shift;
  1045. my $server = shift;
  1046. my $db = shift;
  1047. if (!$db) {
  1048. log_info("DNS-UPDATE: Delete => Zone $zone Server: $server CNAME: $alias for $fqdn ");
  1049. } else {
  1050. db_log_info($db,"DNS-UPDATE: Delete => Zone $zone Server: $server CNAME: $alias for $fqdn");
  1051. }
  1052. my $ad_zone = get_option($db,33);
  1053. my $nsupdate_file = "/tmp/".$fqdn."-nsupdate";
  1054. my @add_dns;
  1055. if ($config_ref{dns_server_type}=~/windows/i) {
  1056. push(@add_dns,"gsstsig");
  1057. push(@add_dns,"server $server");
  1058. push(@add_dns,"zone $zone");
  1059. push(@add_dns,"update delete $alias cname ");
  1060. push(@add_dns,"send");
  1061. write_to_file($nsupdate_file,\@add_dns);
  1062. do_exec('/usr/bin/kinit -k -t /opt/Eye/scripts/cfg/dns_updater.keytab dns_updater@'.uc($ad_zone).' && /usr/bin/nsupdate "'.$nsupdate_file.'"');
  1063. }
  1064. if ($config_ref{dns_server_type}=~/bind/i) {
  1065. push(@add_dns,"server $server");
  1066. push(@add_dns,"zone $zone");
  1067. push(@add_dns,"update delete $alias cname");
  1068. push(@add_dns,"send");
  1069. write_to_file($nsupdate_file,\@add_dns);
  1070. do_exec('/usr/bin/nsupdate -k /etc/bind/rndc.key "'.$nsupdate_file.'"');
  1071. }
  1072. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  1073. }
  1074. #------------------------------------------------------------------------------------------------------------
  1075. sub create_dns_hostname {
  1076. my $fqdn = shift;
  1077. my $ip = shift;
  1078. my $zone = shift;
  1079. my $server = shift;
  1080. my $db = shift;
  1081. #skip update domain controllers
  1082. if ($fqdn=~/^dc[0-9]{1,2}\./i) { return; }
  1083. if (!$db) {
  1084. log_info("DNS-UPDATE: Zone $zone Server: $server A: $fqdn IP: $ip");
  1085. } else {
  1086. db_log_info($db,"DNS-UPDATE: Zone $zone Server: $server A: $fqdn IP: $ip");
  1087. }
  1088. my $ad_zone = get_option($db,33);
  1089. my $nsupdate_file = "/tmp/".$fqdn."-nsupdate";
  1090. my @add_dns;
  1091. if ($config_ref{dns_server_type}=~/windows/i) {
  1092. push(@add_dns,"gsstsig");
  1093. push(@add_dns,"server $server");
  1094. push(@add_dns,"zone $zone");
  1095. push(@add_dns,"update add $fqdn 3600 A $ip");
  1096. push(@add_dns,"send");
  1097. write_to_file($nsupdate_file,\@add_dns);
  1098. do_exec('/usr/bin/kinit -k -t /opt/Eye/scripts/cfg/dns_updater.keytab dns_updater@'.uc($ad_zone).' && /usr/bin/nsupdate "'.$nsupdate_file.'"');
  1099. }
  1100. if ($config_ref{dns_server_type}=~/bind/i) {
  1101. push(@add_dns,"server $server");
  1102. push(@add_dns,"zone $zone");
  1103. push(@add_dns,"update add $fqdn 3600 A $ip");
  1104. push(@add_dns,"send");
  1105. write_to_file($nsupdate_file,\@add_dns);
  1106. do_exec('/usr/bin/nsupdate -k /etc/bind/rndc.key "'.$nsupdate_file.'"');
  1107. }
  1108. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  1109. }
  1110. #---------------------------------------------------------------------------------------------------------------
  1111. sub delete_dns_hostname {
  1112. my $fqdn = shift;
  1113. my $ip = shift;
  1114. my $zone = shift;
  1115. my $server = shift;
  1116. my $db = shift;
  1117. #skip update domain controllers
  1118. if ($fqdn=~/^dc[0-9]{1,2}\./i) { return; }
  1119. if (!$db) {
  1120. log_info("DNS-UPDATE: Delete => Zone $zone Server: $server A: $fqdn IP: $ip");
  1121. } else {
  1122. db_log_info($db,"DNS-UPDATE: Delete => Zone $zone Server: $server A: $fqdn IP: $ip");
  1123. }
  1124. my $ad_zone = get_option($db,33);
  1125. my $nsupdate_file = "/tmp/".$fqdn."-nsupdate";
  1126. my @add_dns;
  1127. if ($config_ref{dns_server_type}=~/windows/i) {
  1128. push(@add_dns,"gsstsig");
  1129. push(@add_dns,"server $server");
  1130. push(@add_dns,"zone $zone");
  1131. push(@add_dns,"update delete $fqdn A");
  1132. push(@add_dns,"send");
  1133. write_to_file($nsupdate_file,\@add_dns);
  1134. do_exec('/usr/bin/kinit -k -t /opt/Eye/scripts/cfg/dns_updater.keytab dns_updater@'.uc($ad_zone).' && /usr/bin/nsupdate "'.$nsupdate_file.'"');
  1135. }
  1136. if ($config_ref{dns_server_type}=~/bind/i) {
  1137. push(@add_dns,"server $server");
  1138. push(@add_dns,"zone $zone");
  1139. push(@add_dns,"update delete $fqdn A");
  1140. push(@add_dns,"send");
  1141. write_to_file($nsupdate_file,\@add_dns);
  1142. do_exec('/usr/bin/nsupdate -k /etc/bind/rndc.key "'.$nsupdate_file.'"');
  1143. }
  1144. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  1145. }
  1146. #---------------------------------------------------------------------------------------------------------------
  1147. sub create_dns_ptr {
  1148. my $fqdn = shift;
  1149. my $ip = shift;
  1150. my $ad_zone = shift;
  1151. my $server = shift;
  1152. my $db = shift;
  1153. my $radr;
  1154. my $zone;
  1155. #skip update domain controllers
  1156. if ($fqdn=~/^dc[0-9]{1,2}\./i) { return; }
  1157. if ($ip =~ /([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})(\/[0-9]{1,2}){0,1}/) {
  1158. return 0 if($1 > 255 || $2 > 255 || $3 > 255 || $4 > 255);
  1159. $radr = "$4.$3.$2.$1.in-addr.arpa";
  1160. $zone = "$3.$2.$1.in-addr.arpa";
  1161. }
  1162. if (!$radr or !$zone) { return 0; }
  1163. if (!$db) { return 0; }
  1164. db_log_info($db,"DNS-UPDATE: Zone $zone Server: $server A: $fqdn PTR: $ip");
  1165. my $nsupdate_file = "/tmp/".$radr."-nsupdate";
  1166. my @add_dns;
  1167. if ($config_ref{dns_server_type}=~/windows/i) {
  1168. push(@add_dns,"gsstsig");
  1169. push(@add_dns,"server $server");
  1170. push(@add_dns,"zone $zone");
  1171. push(@add_dns,"update add $radr 3600 PTR $fqdn.");
  1172. push(@add_dns,"send");
  1173. write_to_file($nsupdate_file,\@add_dns);
  1174. 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.'"';
  1175. do_exec($run_cmd);
  1176. }
  1177. if ($config_ref{dns_server_type}=~/bind/i) {
  1178. push(@add_dns,"server $server");
  1179. push(@add_dns,"zone $zone");
  1180. push(@add_dns,"update add $radr 3600 PTR $fqdn.");
  1181. push(@add_dns,"send");
  1182. write_to_file($nsupdate_file,\@add_dns);
  1183. my $run_cmd = '/usr/bin/nsupdate -k /etc/bind/rndc.key "'.$nsupdate_file.'"';
  1184. do_exec($run_cmd);
  1185. }
  1186. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  1187. }
  1188. #---------------------------------------------------------------------------------------------------------------
  1189. sub delete_dns_ptr {
  1190. my $fqdn = shift;
  1191. my $ip = shift;
  1192. my $ad_zone = shift;
  1193. my $server = shift;
  1194. my $db = shift;
  1195. my $radr;
  1196. my $zone;
  1197. #skip update domain controllers
  1198. if ($fqdn=~/^dc[0-9]{1,2}\./i) { return; }
  1199. if ($ip =~ /([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})(\/[0-9]{1,2}){0,1}/) {
  1200. return 0 if($1 > 255 || $2 > 255 || $3 > 255 || $4 > 255);
  1201. $radr = "$4.$3.$2.$1.in-addr.arpa";
  1202. $zone = "$3.$2.$1.in-addr.arpa";
  1203. }
  1204. if (!$radr or !$zone) { return 0; }
  1205. if (!$db) { return 0 ; }
  1206. db_log_info($db,"DNS-UPDATE: Delete => Zone $zone Server: $server A: $fqdn PTR: $ip");
  1207. my $nsupdate_file = "/tmp/".$radr."-nsupdate";
  1208. my @add_dns;
  1209. if ($config_ref{dns_server_type}=~/windows/i) {
  1210. push(@add_dns,"gsstsig");
  1211. push(@add_dns,"server $server");
  1212. push(@add_dns,"zone $zone");
  1213. push(@add_dns,"update delete $radr PTR");
  1214. push(@add_dns,"send");
  1215. write_to_file($nsupdate_file,\@add_dns);
  1216. 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.'"';
  1217. do_exec($run_cmd);
  1218. }
  1219. if ($config_ref{dns_server_type}=~/bind/i) {
  1220. push(@add_dns,"server $server");
  1221. push(@add_dns,"zone $zone");
  1222. push(@add_dns,"update delete $radr PTR");
  1223. push(@add_dns,"send");
  1224. write_to_file($nsupdate_file,\@add_dns);
  1225. my $run_cmd = '/usr/bin/nsupdate -k /etc/bind/rndc.key "'.$nsupdate_file.'"';
  1226. do_exec($run_cmd);
  1227. }
  1228. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  1229. }
  1230. #---------------------------------------------------------------------------------------------------------------
  1231. sub new_user {
  1232. my $db = shift;
  1233. my $user_info = shift;
  1234. my $user;
  1235. if ($user_info->{mac}) {
  1236. $user->{login}=mac_splitted($user_info->{mac});
  1237. } else {
  1238. $user->{login}=$user_info->{ip};
  1239. }
  1240. if ($user_info->{dhcp_hostname}) { $user->{fio}=$user_info->{dhcp_hostname}; }
  1241. if (!$user->{fio}) { $user->{fio}=$user_info->{ip}; }
  1242. my $login_count = get_count_records($db,"User_list","(login LIKE '".$user->{login}."(%)') OR (login='".$user->{login}."')");
  1243. if ($login_count) { $login_count++; $user->{login} .="(".$login_count.")"; }
  1244. $user->{ou_id} = $user_info->{ou_id};
  1245. my $ou_info = get_record_sql($db,"SELECT * FROM OU WHERE id=".$user_info->{'ou_id'});
  1246. if ($ou_info) {
  1247. $user->{'enabled'} = $ou_info->{'enabled'};
  1248. $user->{'queue_id'} = $ou_info->{'queue_id'};
  1249. $user->{'filter_group_id'} = $ou_info->{'filter_group_id'};
  1250. }
  1251. my $result = insert_record($db,"User_list",$user);
  1252. if ($result and $config_ref{auto_mac_rule} and $user_info->{mac}) {
  1253. my $auth_rule;
  1254. $auth_rule->{user_id} = $result;
  1255. $auth_rule->{type} = 2;
  1256. $auth_rule->{rule} = mac_splitted($user_info->{mac});
  1257. insert_record($db,"auth_rules",$auth_rule);
  1258. }
  1259. return $result;
  1260. }
  1261. #---------------------------------------------------------------------------------------------------------------
  1262. sub get_ip_subnet {
  1263. my $db = shift;
  1264. my $ip = shift;
  1265. if (!$ip) { return; }
  1266. my $ip_aton = StrToIp($ip);
  1267. 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)");
  1268. return $user_subnet;
  1269. }
  1270. #---------------------------------------------------------------------------------------------------------------
  1271. sub find_mac_in_subnet {
  1272. my $db = shift;
  1273. my $ip = shift;
  1274. my $mac = shift;
  1275. if (!$ip or !$mac) { return; }
  1276. my $ip_subnet = get_ip_subnet($db, $ip);
  1277. if (!$ip_subnet) { return; }
  1278. 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");
  1279. my $auth_count = 0;
  1280. my $result;
  1281. $result->{'count'} = 0;
  1282. foreach my $row (@t_auth) {
  1283. next if (!$row);
  1284. $auth_count++;
  1285. $result->{'count'} = $auth_count;
  1286. $result->{$auth_count} = $row->{'id'};
  1287. push(@{$result->{'users_id'}}, $row->{'user_id'});
  1288. }
  1289. return $result;
  1290. }
  1291. #---------------------------------------------------------------------------------------------------------------
  1292. sub resurrection_auth {
  1293. my $db = shift;
  1294. my $ip_record = shift;
  1295. my $ip = $ip_record->{'ip'};
  1296. my $mac = $ip_record->{'mac'};
  1297. my $action = $ip_record->{'type'};
  1298. my $hostname = $ip_record->{'hostname_utf8'};
  1299. my $client_id = $ip_record->{'client-id'};
  1300. if (!exists $ip_record->{ip_aton}) { $ip_record->{ip_aton}=StrToIp($ip); }
  1301. if (!exists $ip_record->{hotspot}) { $ip_record->{hotspot}=is_hotspot($db,$ip); }
  1302. my $ip_aton=$ip_record->{ip_aton};
  1303. my $timestamp=GetNowTime();
  1304. my $record=get_record_sql($db,'SELECT * FROM User_auth WHERE `deleted`=0 AND `ip_int`='.$ip_aton.' AND `mac`="'.$mac.'"');
  1305. my $new_record;
  1306. $new_record->{last_found}=$timestamp;
  1307. $new_record->{arp_found}=$timestamp;
  1308. if ($client_id) { $new_record->{'client-id'} = $client_id; }
  1309. #auth found?
  1310. if ($record->{user_id}) {
  1311. #update timestamp and return
  1312. if ($action=~/^(add|old|del)$/i) {
  1313. $new_record->{dhcp_action}=$action;
  1314. $new_record->{created_by}='dhcp';
  1315. $new_record->{dhcp_time}=$timestamp;
  1316. if ($hostname) { $new_record->{dhcp_hostname} = $hostname; }
  1317. update_record($db,'User_auth',$new_record,"id=$record->{id}");
  1318. } else {
  1319. update_record($db,'User_auth',$new_record,"id=$record->{id}");
  1320. }
  1321. return $record->{id};
  1322. }
  1323. my $user_subnet=$office_networks->match_string($ip);
  1324. if ($user_subnet->{static}) {
  1325. db_log_warning($db,"Unknown ip+mac found in static subnet! Abort create record for ip: $ip mac: [".$mac."]");
  1326. return 0;
  1327. }
  1328. #search changed mac
  1329. $record=get_record_sql($db,'SELECT * FROM User_auth WHERE `ip_int`='.$ip_aton." and deleted=0");
  1330. if ($record->{id}) {
  1331. #if found record with same ip but another mac
  1332. if (!$record->{mac}) {
  1333. db_log_verbose($db,"use empty auth record...");
  1334. $new_record->{mac}=$mac;
  1335. if ($action=~/^(add|old|del)$/i) {
  1336. $new_record->{dhcp_action}=$action;
  1337. $new_record->{dhcp_time}=$timestamp;
  1338. $new_record->{created_by}='dhcp';
  1339. if ($hostname) { $new_record->{dhcp_hostname} = $hostname; }
  1340. update_record($db,'User_auth',$new_record,"id=$record->{id}");
  1341. } else {
  1342. update_record($db,'User_auth',$new_record,"id=$record->{id}");
  1343. }
  1344. return $record->{id};
  1345. }
  1346. if ($record->{mac}) {
  1347. 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});
  1348. my $disable_record;
  1349. $disable_record->{deleted}="1";
  1350. update_record($db,'User_auth',$disable_record,"id=".$record->{id});
  1351. }
  1352. }
  1353. #default user
  1354. my $new_user_info=get_new_user_id($db,$ip,$mac,$hostname);
  1355. my $new_user_id;
  1356. if ($new_user_info->{user_id}) { $new_user_id = $new_user_info->{user_id}; }
  1357. if (!$new_user_id) { $new_user_id = new_user($db,$new_user_info); }
  1358. my $mac_exists=find_mac_in_subnet($db,$ip,$mac);
  1359. #disable dhcp for same mac in one ip subnet
  1360. if ($mac_exists and $mac_exists->{'count'}) { $new_record->{dhcp}=0; }
  1361. #seek old auth with same ip and mac
  1362. my $auth_exists=get_count_records($db,'User_auth',"ip_int=".$ip_aton." and mac='".$mac."'");
  1363. $new_record->{ip_int}=$ip_aton;
  1364. $new_record->{ip}=$ip;
  1365. $new_record->{mac}=$mac;
  1366. $new_record->{user_id}=$new_user_id;
  1367. $new_record->{save_traf}="$save_detail";
  1368. $new_record->{deleted}="0";
  1369. if ($action=~/^(add|old|del)$/i) {
  1370. $new_record->{dhcp_action}=$action;
  1371. $new_record->{dhcp_time}=$timestamp;
  1372. $new_record->{created_by}='dhcp';
  1373. } else {
  1374. $new_record->{created_by}=$action;
  1375. }
  1376. if ($auth_exists) {
  1377. #found ->Resurrection old record
  1378. my $resurrection_id = get_id_record($db,'User_auth',"ip_int=".$ip_aton." and mac='".$mac."'");
  1379. if (!$ip_record->{hotspot}) { db_log_warning($db,"Resurrection auth_id: $resurrection_id with ip: $ip and mac: $mac"); }
  1380. else { db_log_info($db,"Resurrection auth_id: $resurrection_id with ip: $ip and mac: $mac"); }
  1381. update_record($db,'User_auth',$new_record,"id=$resurrection_id");
  1382. } else {
  1383. #not found ->create new record
  1384. 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"); }
  1385. insert_record($db,'User_auth',$new_record);
  1386. }
  1387. #filter and status
  1388. my $cur_auth_id=get_id_record($db,'User_auth',"ip='$ip' and mac='$mac' and deleted=0 ORDER BY last_found DESC");
  1389. if ($cur_auth_id) {
  1390. my $user_record=get_record_sql($db,"SELECT * FROM User_list WHERE id=".$new_user_id);
  1391. if ($user_record) {
  1392. my $ou_info = get_record_sql($db,'SELECT * FROM OU WHERE id='.$user_record->{ou_id});
  1393. if ($ou_info and $ou_info->{'dynamic'}) {
  1394. if (!$ou_info->{'life_duration'}) { $ou_info->{'life_duration'} = 24; }
  1395. my $now = DateTime->now(time_zone=>'local');
  1396. my $hours_dur = DateTime::Duration->new( hours => $ou_info->{'life_duration'} );
  1397. my $eof = $now + $hours_dur;
  1398. $new_record->{'dynamic'} = 1;
  1399. $new_record->{'eof'}=$eof->strftime('%Y-%m-%d %H:%M:%S');
  1400. }
  1401. $new_record->{ou_id}=$user_record->{ou_id};
  1402. $new_record->{comments}=$user_record->{fio};
  1403. $new_record->{filter_group_id}=$user_record->{filter_group_id};
  1404. $new_record->{queue_id}=$user_record->{queue_id};
  1405. $new_record->{enabled}="$user_record->{enabled}";
  1406. update_record($db,'User_auth',$new_record,"id=$cur_auth_id");
  1407. }
  1408. } else { return; }
  1409. return $cur_auth_id;
  1410. }
  1411. #---------------------------------------------------------------------------------------------------------------
  1412. sub new_auth {
  1413. my $db = shift;
  1414. my $ip = shift;
  1415. my $ip_aton=StrToIp($ip);
  1416. my $record=get_record_sql($db,'SELECT id FROM User_auth WHERE `deleted`=0 AND `ip_int`='.$ip_aton);
  1417. if ($record->{id}) { return $record->{id}; }
  1418. #default user
  1419. my $new_user_info=get_new_user_id($db,$ip,undef,undef);
  1420. my $new_user_id;
  1421. if ($new_user_info->{user_id}) { $new_user_id = $new_user_info->{user_id}; }
  1422. if ($new_user_info->{ou_id}) { $new_user_id = new_user($db,$new_user_info); }
  1423. my $user_record=get_record_sql($db,"SELECT * FROM User_list WHERE id=".$new_user_id);
  1424. my $timestamp=GetNowTime();
  1425. my $new_record;
  1426. $new_record->{ip_int}=$ip_aton;
  1427. $new_record->{ip}=$ip;
  1428. $new_record->{user_id}=$new_user_id;
  1429. $new_record->{save_traf}="$save_detail";
  1430. $new_record->{deleted}="0";
  1431. $new_record->{created_by}='netflow';
  1432. $new_record->{ou_id}=$user_record->{ou_id};
  1433. $new_record->{filter_group_id}=$user_record->{filter_group_id};
  1434. $new_record->{queue_id}=$user_record->{queue_id};
  1435. $new_record->{enabled}="$user_record->{enabled}";
  1436. if ($user_record->{fio}) { $new_record->{comments}=$user_record->{fio}; }
  1437. my $cur_auth_id=insert_record($db,'User_auth',$new_record);
  1438. db_log_warning($db,"New ip created by netflow! ip: $ip") if ($cur_auth_id);
  1439. return $cur_auth_id;
  1440. }
  1441. #---------------------------------------------------------------------------------------------------------------
  1442. sub get_option {
  1443. my $db=shift;
  1444. my $option_id=shift;
  1445. return if (!$option_id);
  1446. return if (!$db);
  1447. my $default_option = get_record_sql($db,'SELECT * FROM config_options WHERE id='.$option_id);
  1448. my $config_options = get_record_sql($db,'SELECT * FROM config WHERE option_id='.$option_id);
  1449. my $result;
  1450. if (!$config_options) {
  1451. if ($default_option->{'type'}=~/^(int|bool)/i) { $result = $default_option->{'default_value'}*1; };
  1452. if ($default_option->{'type'}=~/^(string|text)/i) { $result = $default_option->{'default_value'}; }
  1453. if ($default_option->{'type'}=~/^list/i) { $result = $default_option->{'default_value'}; }
  1454. return $result;
  1455. }
  1456. $result = $config_options->{'value'};
  1457. return $result;
  1458. }
  1459. #---------------------------------------------------------------------------------------------------------------
  1460. sub init_option {
  1461. my $db=shift;
  1462. $last_refresh_config = time();
  1463. $config_ref{version}='';
  1464. my $version_record = get_record_sql($db,"SELECT version FROM version WHERE version is NOT NULL");
  1465. if ($version_record) { $config_ref{version}=$version_record->{version}; }
  1466. $config_ref{dbh}=$db;
  1467. $config_ref{save_detail}=get_option($db,23);
  1468. $config_ref{add_unknown_user}=get_option($db,22);
  1469. $config_ref{dhcp_server}=get_option($db,5);
  1470. $config_ref{snmp_default_version}=get_option($db,9);
  1471. $config_ref{snmp_default_community}=get_option($db,11);
  1472. $config_ref{KB}=get_option($db,1);
  1473. if ($config_ref{KB} ==0) { $config_ref{KB}=1000; }
  1474. if ($config_ref{KB} ==1) { $config_ref{KB}=1024; }
  1475. $config_ref{admin_email}=get_option($db,21);
  1476. $config_ref{sender_email}=get_option($db,52);
  1477. $config_ref{send_email}=get_option($db,51);
  1478. $config_ref{history}=get_option($db,26);
  1479. $config_ref{history_dhcp}=get_option($db,27);
  1480. $config_ref{router_login}=get_option($db,28);
  1481. $config_ref{router_password}=get_option($db,29);
  1482. $config_ref{router_port}=get_option($db,30);
  1483. $config_ref{org_name}=get_option($db,32);
  1484. $config_ref{domain_name}=get_option($db,33);
  1485. $config_ref{connections_history}=get_option($db,35);
  1486. $config_ref{debug}=get_option($db,34);
  1487. $config_ref{log_level} = get_option($db,53);
  1488. if ($config_ref{debug}) { $config_ref{log_level} = 255; }
  1489. $config_ref{urgent_sync}=get_option($db,50);
  1490. $config_ref{ignore_hotspot_dhcp_log} = get_option($db,44);
  1491. $config_ref{ignore_update_dhcp_event} = get_option($db,45);
  1492. $config_ref{update_hostname_from_dhcp} = get_option($db,46);
  1493. $config_ref{history_log_day}=get_option($db,47);
  1494. $config_ref{history_syslog_day} = get_option($db,48);
  1495. $config_ref{history_trafstat_day} = get_option($db,49);
  1496. $config_ref{enable_quotes} = get_option($db,54);
  1497. $config_ref{netflow_step} = get_option($db,55);
  1498. $config_ref{traffic_ipstat_history} = get_option($db,56);
  1499. $config_ref{nagios_url} = get_option($db,57);
  1500. $config_ref{cacti_url} = get_option($db,58);
  1501. $config_ref{torrus_url} = get_option($db,59);
  1502. $config_ref{wiki_url} = get_option($db,60);
  1503. $config_ref{stat_url} = get_option($db,62);
  1504. $config_ref{wiki_path} = get_option($db,61);
  1505. $config_ref{auto_mac_rule} = get_option($db,64);
  1506. #network configuration mode
  1507. $config_ref{config_mode}=get_option($db,68);
  1508. #auto clean old user record
  1509. $config_ref{clean_empty_user}=get_option($db,69);
  1510. #dns_server_type
  1511. $config_ref{dns_server}=get_option($db,3);
  1512. $config_ref{dns_server_type}=get_option($db,70);
  1513. $config_ref{enable_dns_updates}=get_option($db,71);
  1514. #$save_detail = 1; id=23
  1515. $save_detail=get_option($db,23);
  1516. #$add_unknown_user = 1; id=22
  1517. $add_unknown_user=get_option($db,22);
  1518. #$dns_server='192.168.2.12'; id=3
  1519. $dns_server=get_option($db,3);
  1520. #$dhcp_server='192.168.2.12'; id=5
  1521. $dhcp_server=get_option($db,5);
  1522. #$snmp_default_version='2'; id=9
  1523. $snmp_default_version=get_option($db,9);
  1524. #$snmp_default_community='public'; id=11
  1525. $snmp_default_community=get_option($db,11);
  1526. #$KB=1024; id=1
  1527. $KB=$config_ref{KB};
  1528. #$admin_email; id=21
  1529. $admin_email=get_option($db,21);
  1530. #sender email
  1531. $sender_email=get_option($db,52);
  1532. #send email
  1533. $send_email=get_option($db,51);
  1534. #$history=15; id=26
  1535. $history=get_option($db,26);
  1536. #$history_dhcp=7; id=27
  1537. $history_dhcp=get_option($db,27);
  1538. #$router_login="admin"; id=28
  1539. $router_login=get_option($db,28);
  1540. #$router_password="admin"; id=29
  1541. $router_password=get_option($db,29);
  1542. #$router_port=23; id=30
  1543. $router_port=get_option($db,30);
  1544. #32
  1545. $org_name=get_option($db,32);
  1546. #33
  1547. $domain_name=get_option($db,33);
  1548. #35
  1549. $connections_history=get_option($db,35);
  1550. #debug
  1551. $debug=get_option($db,34);
  1552. #log level
  1553. $log_level = get_option($db,53);
  1554. if ($debug) { $log_level = 255; }
  1555. #urgent sync access
  1556. $urgent_sync=get_option($db,50);
  1557. $ignore_hotspot_dhcp_log = get_option($db,44);
  1558. $ignore_update_dhcp_event = get_option($db,45);
  1559. $update_hostname_from_dhcp = get_option($db,46);
  1560. $history_log_day=get_option($db,47);
  1561. $history_syslog_day = get_option($db,48);
  1562. $history_trafstat_day = get_option($db,49);
  1563. my $ou = get_record_sql($db,"SELECT id FROM OU WHERE default_users = 1");
  1564. if (!$ou) { $default_user_ou_id = 0; } else { $default_user_ou_id = $ou->{'id'}; }
  1565. $ou = get_record_sql($db,"SELECT id FROM OU WHERE default_hotspot = 1");
  1566. if (!$ou) { $default_hotspot_ou_id = $default_user_ou_id; } else { $default_hotspot_ou_id = $ou->{'id'}; }
  1567. @subnets=get_records_sql($db,'SELECT * FROM subnets ORDER BY ip_int_start');
  1568. if (defined $office_networks) { undef $office_networks; }
  1569. if (defined $free_networks) { undef $free_networks; }
  1570. if (defined $vpn_networks) { undef $vpn_networks; }
  1571. if (defined $hotspot_networks) { undef $hotspot_networks; }
  1572. if (defined $all_networks) { undef $all_networks; }
  1573. $office_networks = new Net::Patricia;
  1574. $free_networks = new Net::Patricia;
  1575. $vpn_networks = new Net::Patricia;
  1576. $hotspot_networks = new Net::Patricia;
  1577. $all_networks = new Net::Patricia;
  1578. @office_network_list=();
  1579. @free_network_list=();
  1580. @free_network_list=();
  1581. @vpn_network_list=();
  1582. @hotspot_network_list=();
  1583. @all_network_list=();
  1584. foreach my $net (@subnets) {
  1585. next if (!$net->{subnet});
  1586. $subnets_ref{$net->{subnet}}=$net;
  1587. if ($net->{office}) {
  1588. push(@office_network_list,$net->{subnet});
  1589. $office_networks->add_string($net->{subnet},$net);
  1590. }
  1591. if ($net->{free}) {
  1592. push(@free_network_list,$net->{subnet});
  1593. $free_networks->add_string($net->{subnet},$net);
  1594. }
  1595. if ($net->{vpn}) {
  1596. push(@vpn_network_list,$net->{subnet});
  1597. $vpn_networks->add_string($net->{subnet},$net);
  1598. }
  1599. if ($net->{hotspot}) {
  1600. push(@hotspot_network_list,$net->{subnet});
  1601. push(@all_network_list,$net->{subnet});
  1602. $hotspot_networks->add_string($net->{subnet},$net);
  1603. }
  1604. push(@all_network_list,$net->{subnet});
  1605. $all_networks->add_string($net->{subnet},$net);
  1606. }
  1607. }
  1608. #---------------------------------------------------------------------------------------------------------------
  1609. sub get_subnets_ref {
  1610. my $db = shift;
  1611. my @list=get_records_sql($db,'SELECT * FROM subnets ORDER BY ip_int_start');
  1612. my $list_ref;
  1613. foreach my $net (@list) {
  1614. next if (!$net->{subnet});
  1615. $list_ref->{$net->{subnet}}=$net;
  1616. }
  1617. return $list_ref;
  1618. }
  1619. #---------------------------------------------------------------------------------------------------------------
  1620. sub get_device_by_ip {
  1621. my $db = shift;
  1622. my $ip = shift;
  1623. my $netdev=get_record_sql($db,'SELECT * FROM devices WHERE ip="'.$ip.'"');
  1624. if ($netdev and $netdev->{id}>0) { return $netdev; }
  1625. my $auth_rec=get_record_sql($db,'SELECT user_id FROM User_auth WHERE ip="'.$ip.'" and deleted=0');
  1626. if ($auth_rec and $auth_rec->{user_id}>0) {
  1627. $netdev=get_record_sql($db,'SELECT * FROM devices WHERE user_id='.$auth_rec->{user_id});
  1628. return $netdev;
  1629. }
  1630. return;
  1631. }
  1632. #---------------------------------------------------------------------------------------------------------------
  1633. sub GetUnixTimeByStr {
  1634. my $time_str = shift;
  1635. $time_str =~s/\//-/g;
  1636. $time_str = trim($time_str);
  1637. my ($sec,$min,$hour,$day,$mon,$year) = (localtime())[0,1,2,3,4,5];
  1638. $year+=1900;
  1639. $mon++;
  1640. if ($time_str =~/^([0-9]{2,4})\-([0-9]{1,2})-([0-9]{1,2})\s+/) {
  1641. $year = $1; $mon = $2; $day = $3;
  1642. }
  1643. if ($time_str =~/([0-9]{1,2})\:([0-9]{1,2})\:([0-9]{1,2})$/) {
  1644. $hour = $1; $min = $2; $sec = $3;
  1645. }
  1646. my $result = mktime($sec,$min,$hour,$day,$mon-1,$year-1900);
  1647. return $result;
  1648. }
  1649. #---------------------------------------------------------------------------------------------------------------
  1650. sub GetTimeStrByUnixTime {
  1651. my $time = shift || time();
  1652. my ($sec, $min, $hour, $mday, $mon, $year) = (localtime($time))[0,1,2,3,4,5];
  1653. my $result = strftime("%Y-%m-%d %H:%M:%S",$sec, $min, $hour, $mday, $mon, $year);
  1654. return $result;
  1655. }
  1656. #---------------------------------------------------------------------------------------------------------------
  1657. sub Set_Variable {
  1658. my $db = shift;
  1659. my $name = shift || $MY_NAME;
  1660. my $value = shift || $$;
  1661. my $timeshift = shift || 60;
  1662. Del_Variable($db,$name);
  1663. my $clean_variables = time() + $timeshift;
  1664. my ($sec,$min,$hour,$day,$month,$year,$zone) = localtime($clean_variables);
  1665. $month++;
  1666. $year += 1900;
  1667. my $clean_str=sprintf "%04d-%02d-%02d %02d:%02d:%02d",$year,$month,$day,$hour,$min,$sec;
  1668. my $clean_variables_date=$db->quote($clean_str);
  1669. do_sql($db,"INSERT INTO variables(name,value,clear_time) VALUES('".$name."','".$value."',".$clean_variables_date.");");
  1670. }
  1671. #---------------------------------------------------------------------------------------------------------------
  1672. sub Get_Variable {
  1673. my $db = shift;
  1674. my $name = shift || $MY_NAME;
  1675. my $variable=get_record_sql($db,'SELECT `value` FROM `variables` WHERE name="'.$name.'"');
  1676. if (!$variable and $variable->{'value'}) { return $variable->{'value'}; }
  1677. return;
  1678. }
  1679. #---------------------------------------------------------------------------------------------------------------
  1680. sub Del_Variable {
  1681. my $db = shift;
  1682. my $name = shift || $MY_NAME;
  1683. do_sql($db,"DELETE FROM `variables` WHERE name='".$name."';");
  1684. }
  1685. #---------------------------------------------------------------------------------------------------------------
  1686. sub recalc_quotes {
  1687. my $db = shift;
  1688. my $calc_id = shift || $$;
  1689. return if (!get_option($db,54));
  1690. clean_variables($db);
  1691. return if (Get_Variable($db,'RECALC'));
  1692. my $timeshift = get_option($db,55);
  1693. Set_Variable($db,'RECALC',$calc_id,time()+$timeshift*60);
  1694. my $now = DateTime->now(time_zone=>'local');
  1695. my $day_start = $db->quote($now->ymd("-")." 00:00:00");
  1696. my $day_dur = DateTime::Duration->new( days => 1 );
  1697. my $tomorrow = $now+$day_dur;
  1698. my $day_stop = $db->quote($tomorrow->ymd("-")." 00:00:00");
  1699. $now->set(day=>1);
  1700. my $month_start=$db->quote($now->ymd("-")." 00:00:00");
  1701. my $month_dur = DateTime::Duration->new( months => 1 );
  1702. my $next_month = $now + $month_dur;
  1703. $next_month->set(day=>1);
  1704. my $month_stop = $db->quote($next_month->ymd("-")." 00:00:00");
  1705. #get user limits
  1706. 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";
  1707. my @authlist_ref = get_records_sql($db,$user_auth_list_sql);
  1708. my %user_stats;
  1709. my %auth_info;
  1710. foreach my $row (@authlist_ref) {
  1711. $auth_info{$row->{auth_id}}{user_id}=$row->{id};
  1712. $auth_info{$row->{auth_id}}{day_limit}=$row->{auth_day};
  1713. $auth_info{$row->{auth_id}}{month_limit}=$row->{auth_month};
  1714. $auth_info{$row->{auth_id}}{day}=0;
  1715. $auth_info{$row->{auth_id}}{month}=0;
  1716. $user_stats{$row->{id}}{day_limit}=$row->{day_quota};
  1717. $user_stats{$row->{id}}{month_limit}=$row->{month_quota};
  1718. $user_stats{$row->{id}}{day}=0;
  1719. $user_stats{$row->{id}}{month}=0;
  1720. }
  1721. #recalc quotes - global
  1722. #day
  1723. my $day_sql="SELECT User_stats.auth_id, SUM( byte_in + byte_out ) AS traf_all FROM User_stats
  1724. WHERE User_stats.`timestamp`>= $day_start AND User_stats.`timestamp`< $day_stop GROUP BY User_stats.auth_id";
  1725. my @day_stats = get_records_sql($db,$day_sql);
  1726. foreach my $row (@day_stats) {
  1727. my $user_id=$auth_info{$row->{auth_id}}{user_id};
  1728. $auth_info{$row->{auth_id}}{day}=$row->{traf_all};
  1729. $user_stats{$user_id}{day}+=$row->{traf_all};
  1730. }
  1731. #month
  1732. my $month_sql="SELECT User_stats.auth_id, SUM( byte_in + byte_out ) AS traf_all FROM User_stats
  1733. WHERE User_stats.`timestamp`>= $month_start AND User_stats.`timestamp`< $month_stop GROUP BY User_stats.auth_id";
  1734. my @month_stats = get_records_sql($db,$month_sql);
  1735. foreach my $row (@month_stats) {
  1736. my $user_id=$auth_info{$row->{auth_id}}{user_id};
  1737. $auth_info{$row->{auth_id}}{month}=$row->{traf_all};
  1738. $user_stats{$user_id}{month}+=$row->{traf_all};
  1739. }
  1740. foreach my $auth_id (keys %auth_info) {
  1741. next if (!$auth_info{$auth_id}{day_limit});
  1742. next if (!$auth_info{$auth_id}{month_limit});
  1743. my $day_limit=$auth_info{$auth_id}{day_limit}*$KB*$KB;
  1744. my $month_limit=$auth_info{$auth_id}{month_limit}*$KB*$KB;
  1745. my $blocked_d=($auth_info{$auth_id}{day}>$day_limit);
  1746. my $blocked_m=($auth_info{$auth_id}{month}>$month_limit);
  1747. if ($blocked_d or $blocked_m) {
  1748. my $history_msg;
  1749. 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; }
  1750. 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; }
  1751. do_sql($db,"UPDATE User_auth set blocked=1, changed=1 where id=$auth_id");
  1752. db_log_verbose($db,$history_msg);
  1753. }
  1754. }
  1755. foreach my $user_id (keys %user_stats) {
  1756. next if (!$user_stats{$user_id}{day_limit});
  1757. next if (!$user_stats{$user_id}{month_limit});
  1758. my $day_limit=$user_stats{$user_id}{day_limit}*$KB*$KB;
  1759. my $month_limit=$user_stats{$user_id}{month_limit}*$KB*$KB;
  1760. my $blocked_d=($user_stats{$user_id}{day}>$day_limit);
  1761. my $blocked_m=($user_stats{$user_id}{month}>$month_limit);
  1762. if ($blocked_d or $blocked_m) {
  1763. my $history_msg;
  1764. 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; }
  1765. 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; }
  1766. do_sql($db,"UPDATE User_user set blocked=1 where id=$user_id");
  1767. do_sql($db,"UPDATE User_auth set blocked=1, changed=1 where user_id=$user_id");
  1768. db_log_verbose($db,$history_msg);
  1769. }
  1770. }
  1771. Del_Variable($db,'RECALC');
  1772. }
  1773. #---------------------------------------------------------------------------------------------------------------
  1774. sub clean_variables {
  1775. my $db = shift;
  1776. #clean temporary variables
  1777. my $clean_variables = time();
  1778. my ($sec,$min,$hour,$day,$month,$year,$zone) = localtime($clean_variables);
  1779. $month++;
  1780. $year += 1900;
  1781. my $now_str=sprintf "%04d-%02d-%02d %02d:%02d:%02d",$year,$month,$day,$hour,$min,$sec;
  1782. my $clean_variables_date=$db->quote($now_str);
  1783. do_sql($db,"DELETE FROM `variables` WHERE clear_time<=$clean_variables_date");
  1784. #clean old AD computer cache
  1785. my $now = DateTime->now(time_zone=>'local');
  1786. my $day_dur = DateTime::Duration->new( days => 1 );
  1787. my $clean_date = $now - $day_dur;
  1788. my $clean_str = $dbh->quote($clean_date->ymd("-")." 00:00:00");
  1789. do_sql($db,"DELETE FROM `ad_comp_cache` WHERE last_found<=$clean_str");
  1790. }
  1791. #---------------------------------------------------------------------------------------------------------------
  1792. #skip init for upgrade
  1793. if ($MY_NAME!~/upgrade.pl/) {
  1794. $dbh=init_db();
  1795. init_option($dbh);
  1796. clean_variables($dbh);
  1797. Set_Variable($dbh);
  1798. }
  1799. 1;
  1800. }