mysql.pm 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216
  1. package Rstat::mysql;
  2. #
  3. # Copyright (C) Roman Dmitiriev, rnd@rajven.ru
  4. #
  5. use strict;
  6. use English;
  7. use FindBin '$Bin';
  8. use lib "$Bin";
  9. use base 'Exporter';
  10. use vars qw(@EXPORT @ISA);
  11. use Rstat::config;
  12. use Rstat::main;
  13. use Net::Patricia;
  14. use Rstat::net_utils;
  15. use Data::Dumper;
  16. use DateTime;
  17. use POSIX;
  18. use DBI;
  19. our @ISA = qw(Exporter);
  20. our @EXPORT = qw(
  21. batch_db_sql
  22. batch_db_sql_cached
  23. db_log_warning
  24. db_log_debug
  25. db_log_error
  26. db_log_info
  27. db_log_verbose
  28. delete_record
  29. do_sql
  30. Get_Variable
  31. Set_Variable
  32. Del_Variable
  33. get_count_records
  34. get_record_sql
  35. get_records_sql
  36. get_device_by_ip
  37. get_diff_rec
  38. get_id_record
  39. get_new_user_id
  40. is_hotspot
  41. GetNowTime
  42. GetUnixTimeByStr
  43. GetTimeStrByUnixTime
  44. get_option
  45. get_subnets_ref
  46. init_db
  47. init_option
  48. insert_record
  49. IpToStr
  50. resurrection_auth
  51. new_auth
  52. StrToIp
  53. update_dns_record
  54. update_ad_hostname
  55. update_record
  56. write_db_log
  57. set_changed
  58. recalc_quotes
  59. clean_variables
  60. $add_rules
  61. $L_WARNING
  62. $L_INFO
  63. $L_DEBUG
  64. $L_ERROR
  65. $L_VERBOSE
  66. );
  67. BEGIN
  68. {
  69. #---------------------------------------------------------------------------------------------------------------
  70. our $add_rules;
  71. our $L_ERROR = 0;
  72. our $L_WARNING = 1;
  73. our $L_INFO = 2;
  74. our $L_VERBOSE = 3;
  75. our $L_DEBUG = 255;
  76. our %acl_fields = (
  77. 'ip' => '1',
  78. 'ip_int' => '1',
  79. 'enabled'=>'1',
  80. 'dhcp'=>'1',
  81. 'filter_group_id'=>'1',
  82. 'deleted'=>'1',
  83. 'dhcp_acl'=>'1',
  84. 'queue_id'=>'1',
  85. 'mac'=>'1',
  86. 'blocked'=>'1'
  87. );
  88. #---------------------------------------------------------------------------------------------------------------
  89. sub StrToIp{
  90. return unpack('N',pack('C4',split(/\./,$_[0])));
  91. }
  92. #---------------------------------------------------------------------------------------------------------------
  93. sub IpToStr{
  94. my $nIP = shift;
  95. my $res = (($nIP>>24) & 255) .".". (($nIP>>16) & 255) .".". (($nIP>>8) & 255) .".". ($nIP & 255);
  96. return $res;
  97. }
  98. #---------------------------------------------------------------------------------------------------------------
  99. sub batch_db_sql {
  100. my $db=shift;
  101. my $batch_sql=shift;
  102. return if (!$db);
  103. $db->{AutoCommit} = 0;
  104. my $apply = 0;
  105. my $sth;
  106. if (ref($batch_sql) eq 'ARRAY') {
  107. foreach my $sSQL (@$batch_sql) {
  108. next if (!$sSQL);
  109. $sth = $db->prepare($sSQL);
  110. $sth->execute;
  111. $apply = 1;
  112. }
  113. } else {
  114. my @msg = split("\n",$batch_sql);
  115. foreach my $sSQL (@msg) {
  116. next if (!$sSQL);
  117. $sth = $db->prepare($sSQL);
  118. $sth->execute;
  119. $apply = 1;
  120. }
  121. }
  122. if ($apply) { $sth->finish; }
  123. $db->{AutoCommit} = 1;
  124. }
  125. #---------------------------------------------------------------------------------------------------------------
  126. sub batch_db_sql_cached {
  127. my $db = DBI->connect("dbi:mysql:database=$DBNAME;host=$DBHOST","$DBUSER","$DBPASS", { RaiseError => 1, AutoCommit => 0 });
  128. if ( !defined $db ) { die "Cannot connect to mySQL server: $DBI::errstr\n"; }
  129. $db->do('SET NAMES utf8');
  130. $db->{mysql_auto_reconnect} = 1;
  131. my $table= shift;
  132. my $batch_sql=shift;
  133. return if (!$db);
  134. if (ref($batch_sql) eq 'ARRAY') {
  135. my $sth = $dbh->prepare_cached($table);
  136. db_log_debug($db,"Start prepare data");
  137. foreach my $sSQL (@$batch_sql) {
  138. next if (!$sSQL);
  139. $sth->execute(@$sSQL);
  140. }
  141. db_log_debug($db,"End prepare data");
  142. }
  143. db_log_debug($db,"Start commit");
  144. $db->commit();
  145. db_log_debug($db,"End commit");
  146. $db->disconnect();
  147. }
  148. #---------------------------------------------------------------------------------------------------------------
  149. sub do_sql {
  150. my $db=shift;
  151. my $sql=shift;
  152. return if (!$db);
  153. return if (!$sql);
  154. if ($sql!~/^select /i) { db_log_debug($db,$sql); }
  155. my $sql_prep = $db->prepare($sql);
  156. my $sql_ref;
  157. if ( !defined $sql_prep ) { die "Cannot prepare statement: $DBI::errstr\n"; }
  158. $sql_prep->execute;
  159. if ($sql=~/^insert/i) { $sql_ref = $sql_prep->{mysql_insertid}; }
  160. if ($sql=~/^select /i) { $sql_ref = $sql_prep->fetchall_arrayref(); };
  161. $sql_prep->finish();
  162. return $sql_ref;
  163. }
  164. #---------------------------------------------------------------------------------------------------------------
  165. sub write_db_log {
  166. my $db=shift;
  167. my $msg=shift;
  168. my $level = shift || $L_VERBOSE;
  169. my $auth_id = shift || 0;
  170. return if (!$db);
  171. return if (!$msg);
  172. $msg=~s/[\'\"]//g;
  173. my $db_log = 0;
  174. my $history_sql="INSERT INTO syslog(customer,message,level,auth_id) VALUES(".$db->quote($MY_NAME).",".$db->quote($msg).",$level,$auth_id)";
  175. if ($level eq $L_ERROR and $log_level >= $L_ERROR) { log_error($msg); $db_log = 1; }
  176. if ($level eq $L_WARNING and $log_level >= $L_WARNING) { log_warning($msg); $db_log = 1; }
  177. if ($level eq $L_INFO and $log_level >= $L_INFO) { log_info($msg); $db_log = 1; }
  178. if ($level eq $L_DEBUG and $log_level >= $L_DEBUG) { log_debug($msg); $db_log = 1; }
  179. if ($db_log) {
  180. my $history_rf=$db->prepare($history_sql);
  181. $history_rf->execute;
  182. }
  183. }
  184. #---------------------------------------------------------------------------------------------------------------
  185. sub db_log_debug {
  186. my $db = shift;
  187. my $msg = shift;
  188. my $id = shift;
  189. if ($debug) { write_db_log($db,$msg,$L_DEBUG,$id); }
  190. }
  191. #---------------------------------------------------------------------------------------------------------------
  192. sub db_log_error {
  193. my $db = shift;
  194. my $msg = shift;
  195. if ($log_level >= $L_ERROR) {
  196. sendEmail("ERROR! ".substr($msg,0,30),$msg,1);
  197. write_db_log($db,$msg,$L_ERROR);
  198. }
  199. }
  200. #---------------------------------------------------------------------------------------------------------------
  201. sub db_log_info {
  202. my $db = shift;
  203. my $msg = shift;
  204. if ($log_level >= $L_INFO) { write_db_log($db,$msg,$L_INFO); }
  205. }
  206. #---------------------------------------------------------------------------------------------------------------
  207. sub db_log_verbose {
  208. my $db = shift;
  209. my $msg = shift;
  210. if ($log_level >= $L_VERBOSE) { write_db_log($db,$msg,$L_VERBOSE); }
  211. }
  212. #---------------------------------------------------------------------------------------------------------------
  213. sub db_log_warning {
  214. my $db = shift;
  215. my $msg = shift;
  216. if ($log_level >= $L_WARNING) {
  217. sendEmail("WARN! ".substr($msg,0,30),$msg,1);
  218. write_db_log($db,$msg,$L_WARNING);
  219. }
  220. }
  221. #---------------------------------------------------------------------------------------------------------------
  222. sub init_db {
  223. # Create new database handle. If we can't connect, die()
  224. my $db = DBI->connect("dbi:mysql:database=$DBNAME;host=$DBHOST","$DBUSER","$DBPASS");
  225. if ( !defined $db ) { die "Cannot connect to mySQL server: $DBI::errstr\n"; }
  226. $db->do('SET NAMES utf8');
  227. $db->{mysql_auto_reconnect} = 1;
  228. return $db;
  229. }
  230. #---------------------------------------------------------------------------------------------------------------
  231. sub get_count_records {
  232. my $db = shift;
  233. my $table = shift;
  234. my $filter = shift;
  235. my $result = 0;
  236. return $result if (!$db);
  237. return $result if (!$table);
  238. my $sSQL='SELECT COUNT(*) as rec_cnt FROM '.$table;
  239. if ($filter) { $sSQL=$sSQL." where ".$filter; }
  240. my $record = get_record_sql($db,$sSQL);
  241. if ($record->{rec_cnt}) { $result = $record->{rec_cnt}; }
  242. return $result;
  243. }
  244. #---------------------------------------------------------------------------------------------------------------
  245. sub get_id_record {
  246. my $db = shift;
  247. my $table = shift;
  248. my $filter = shift;
  249. my $result = 0;
  250. return $result if (!$db);
  251. return $result if (!$table);
  252. my $record = get_record_sql($db,"SELECT id FROM $table WHERE $filter");
  253. if ($record->{id}) { $result = $record->{id}; }
  254. return $result;
  255. }
  256. #---------------------------------------------------------------------------------------------------------------
  257. sub get_records_sql {
  258. my $db = shift;
  259. my $table = shift;
  260. my @result;
  261. return @result if (!$db);
  262. return @result if (!$table);
  263. my $list = $db->prepare( $table );
  264. if ( !defined $list ) { die "Cannot prepare statement: $DBI::errstr\n"; }
  265. $list->execute;
  266. while(my $row_ref = $list ->fetchrow_hashref) {
  267. push(@result,$row_ref);
  268. }
  269. $list->finish();
  270. return @result;
  271. }
  272. #---------------------------------------------------------------------------------------------------------------
  273. sub get_record_sql {
  274. my $db = shift;
  275. my $tsql = shift;
  276. my @result;
  277. return @result if (!$db);
  278. return @result if (!$tsql);
  279. my $list = $db->prepare( $tsql . ' LIMIT 1' );
  280. if ( !defined $list ) { die "Cannot prepare statement: $DBI::errstr\n"; }
  281. $list->execute;
  282. my $row_ref = $list ->fetchrow_hashref;
  283. $list->finish();
  284. return $row_ref;
  285. }
  286. #---------------------------------------------------------------------------------------------------------------
  287. sub get_diff_rec {
  288. my $db = shift;
  289. my $table = shift;
  290. my $value = shift;
  291. my $filter = shift;
  292. return if (!$db);
  293. return if (!$table);
  294. return if (!$filter);
  295. my $old_value = get_record_sql($db,"SELECT * FROM $table WHERE $filter");
  296. my $result='';
  297. foreach my $field (keys %$value) {
  298. if (!$value->{$field}) { $value->{$field}=''; }
  299. if (!$old_value->{$field}) { $old_value->{$field}=''; }
  300. if ($value->{$field}!~/^$old_value->{$field}$/) { $result = $result." $field => $value->{$field} (old: $old_value->{$field}),"; }
  301. }
  302. $result=~s/,$//;
  303. return $result;
  304. }
  305. #---------------------------------------------------------------------------------------------------------------
  306. sub update_record {
  307. my $db = shift;
  308. my $table = shift;
  309. my $record = shift;
  310. my $filter = shift;
  311. return if (!$db);
  312. return if (!$table);
  313. return if (!$filter);
  314. my $old_record = get_record_sql($db,"SELECT * FROM $table WHERE $filter");
  315. my $diff='';
  316. my $change_str='';
  317. my $found_changed=0;
  318. my $auth_id = 0;
  319. if ($table eq "User_auth") {
  320. $auth_id = $old_record->{'id'};
  321. foreach my $field (keys %$record) {
  322. next if (!exists $acl_fields{$field});
  323. $record->{changed}="1";
  324. }
  325. }
  326. foreach my $field (keys %$record) {
  327. if (!defined $record->{$field}) { $record->{$field}=''; }
  328. if (!defined $old_record->{$field}) { $old_record->{$field}=''; }
  329. my $old_value = quotemeta($old_record->{$field});
  330. my $new_value = $record->{$field};
  331. $new_value=~s/\'//g;
  332. $new_value=~s/\"//g;
  333. if ($new_value!~/^$old_value$/) {
  334. $diff = $diff." $field => $record->{$field} (old: $old_record->{$field}),";
  335. $change_str = $change_str." `$field`=".$db->quote($record->{$field}).",";
  336. $found_changed++;
  337. }
  338. }
  339. if ($found_changed) {
  340. $change_str=~s/\,$//;
  341. $diff=~s/\,$//;
  342. if ($table eq 'User_auth') { $change_str .= ", `changed_time`='".GetNowTime()."'"; }
  343. my $sSQL = "UPDATE $table SET $change_str WHERE $filter";
  344. db_log_debug($db,'Change table '.$table.' for '.$filter.' set: '.$diff,$auth_id);
  345. do_sql($db,$sSQL);
  346. } else {
  347. db_log_debug($db,'Nothing change. Skip update.');
  348. }
  349. }
  350. #---------------------------------------------------------------------------------------------------------------
  351. sub insert_record {
  352. my $db = shift;
  353. my $table = shift;
  354. my $record = shift;
  355. return if (!$db);
  356. return if (!$table);
  357. my $change_str='';
  358. my $fields='';
  359. my $values='';
  360. my $new_str='';
  361. if ($table eq 'User_auth') {
  362. foreach my $field (keys %$record) {
  363. next if (!exists $acl_fields{$field});
  364. $record->{changed}="1";
  365. }
  366. }
  367. foreach my $field (keys %$record) {
  368. if (!defined $record->{$field}) { $record->{$field}=''; }
  369. my $new_value = $record->{$field};
  370. $new_value=~s/\'//g;
  371. $new_value=~s/\"//g;
  372. $fields = $fields."`$field`,";
  373. $values = $values." ".$db->quote($new_value).",";
  374. $new_str = $new_str." $field => $new_value,";
  375. }
  376. $fields=~s/,$//;
  377. $values=~s/,$//;
  378. $new_str=~s/,$//;
  379. my $sSQL = "INSERT INTO $table($fields) VALUES($values)";
  380. my $result = do_sql($db,$sSQL);
  381. if ($result) { $new_str='id: '.$result.' '.$new_str; }
  382. db_log_debug($db,'Add record to table '.$table.' '.$new_str);
  383. return $result;
  384. }
  385. #---------------------------------------------------------------------------------------------------------------
  386. sub delete_record {
  387. my $db = shift;
  388. my $table = shift;
  389. my $filter = shift;
  390. return if (!$db);
  391. return if (!$table);
  392. return if (!$filter);
  393. my $old_record = get_record_sql($db,"SELECT * FROM $table WHERE $filter");
  394. my $diff='';
  395. foreach my $field (keys %$old_record) {
  396. if (!$old_record->{$field}) { $old_record->{$field}=''; }
  397. $diff = $diff." $field => $old_record->{$field},";
  398. }
  399. $diff=~s/,$//;
  400. db_log_debug($db,'Delete record from table '.$table.' value: '.$diff);
  401. #never delete user ip record!
  402. if ($table eq 'User_auth') {
  403. my $sSQL = "UPDATE User_auth SET deleted=1, changed_time='".GetNowTime()."' WHERE ".$filter;
  404. do_sql($db,$sSQL);
  405. } else {
  406. my $sSQL = "DELETE FROM ".$table." WHERE ".$filter;
  407. do_sql($db,$sSQL);
  408. }
  409. }
  410. #---------------------------------------------------------------------------------------------------------------
  411. sub GetNowTime {
  412. my ($sec,$min,$hour,$day,$month,$year,$zone) = localtime(time());
  413. $month += 1;
  414. $year += 1900;
  415. my $now_str=sprintf "%04d-%02d-%02d %02d:%02d:%02d",$year,$month,$day,$hour,$min,$sec;
  416. return $now_str;
  417. }
  418. #---------------------------------------------------------------------------------------------------------------
  419. sub is_hotspot {
  420. my $db = shift;
  421. my $ip = shift;
  422. my $users = new Net::Patricia;
  423. #check hotspot
  424. my @ip_rules = get_records_sql($db,'SELECT * FROM subnets WHERE hotspot=1 AND LENGTH(subnet)>0');
  425. foreach my $row (@ip_rules) { $users->add_string($row->{subnet},$config_ref{hotspot_user_id}); }
  426. if ($users->match_string($ip)) { return 1; }
  427. return 0;
  428. }
  429. #---------------------------------------------------------------------------------------------------------------
  430. sub get_new_user_id {
  431. my $db = shift;
  432. my $ip = shift;
  433. my $mac = shift;
  434. my $hostname = shift;
  435. #check ip
  436. if (defined $ip and $ip) {
  437. my $users = new Net::Patricia;
  438. #check hotspot
  439. my @ip_rules = get_records_sql($db,'SELECT * FROM subnets WHERE hotspot=1 AND LENGTH(subnet)>0');
  440. foreach my $row (@ip_rules) { $users->add_string($row->{subnet},$config_ref{hotspot_user_id}); }
  441. if ($users->match_string($ip)) { return $users->match_string($ip); }
  442. #check ip rules
  443. @ip_rules = get_records_sql($db,'SELECT * FROM auth_rules WHERE type=1 and LENGTH(rule)>0');
  444. foreach my $row (@ip_rules) { $users->add_string($row->{rule},$row->{user_id}); }
  445. if ($users->match_string($ip)) { return $users->match_string($ip); }
  446. }
  447. #check mac
  448. if (defined $mac and $mac) {
  449. my @user_rules=get_records_sql($db,'SELECT * FROM auth_rules WHERE type=2 AND LENGTH(rule)>0');
  450. foreach my $user (@user_rules) {
  451. if ($mac=~/$user->{rule}/i) { return $user->{user_id}; }
  452. }
  453. }
  454. #check hostname
  455. if (defined $hostname and $hostname) {
  456. my @user_rules=get_records_sql($db,'SELECT * FROM auth_rules WHERE type=3 AND LENGTH(rule)>0');
  457. foreach my $user (@user_rules) {
  458. if ($hostname=~/$user->{rule}/i) { return $user->{user_id}; }
  459. }
  460. }
  461. return $default_user_id;
  462. }
  463. #---------------------------------------------------------------------------------------------------------------
  464. sub set_changed {
  465. my $db = shift;
  466. my $id = shift;
  467. return if (!$db or !$id);
  468. my $update_record;
  469. $update_record->{changed}=1;
  470. update_record($db,'User_auth',$update_record,"id=$id");
  471. }
  472. #---------------------------------------------------------------------------------------------------------------
  473. sub update_dns_record {
  474. my $hdb = shift;
  475. my $dhcp_record = shift;
  476. my $auth_record = shift;
  477. my $ad_zone = get_option($hdb,33);
  478. my $ad_dns = get_option($hdb,3);
  479. $update_hostname_from_dhcp = get_option($hdb,46) || 0;
  480. my $subnets_dhcp = get_subnets_ref($hdb);
  481. my $enable_ad_dns_update = ($ad_zone and $ad_dns and $update_hostname_from_dhcp);
  482. log_debug("Subnet: $dhcp_record->{network}");
  483. log_debug("DNS update flags - zone: $ad_zone dns: $ad_dns config: $update_hostname_from_dhcp subnet: $subnets_dhcp->{$dhcp_record->{network}}->{dhcp_update_hostname}");
  484. my $maybe_update_dns=(($dhcp_record->{type}=~/add/i or $dhcp_record->{type}=~/old/i) and $dhcp_record->{hostname_utf8} and $dhcp_record->{hostname_utf8} !~/UNDEFINED/i and $enable_ad_dns_update and $subnets_dhcp->{$dhcp_record->{network}}->{dhcp_update_hostname});
  485. if (!$maybe_update_dns) {
  486. db_log_debug($hdb,"FOUND Auth_id: $auth_record->{id}. DNS update don't needed.");
  487. return 0;
  488. }
  489. log_debug("DNS update enabled.");
  490. #update dns block
  491. my $fqdn_static;
  492. if ($auth_record->{dns_name}) {
  493. $fqdn_static=lc($auth_record->{dns_name});
  494. if ($fqdn_static!~/$ad_zone$/i) {
  495. $fqdn_static=~s/\.$//;
  496. $fqdn_static=lc($fqdn_static.'.'.$ad_zone);
  497. }
  498. }
  499. my $fqdn=lc(trim($dhcp_record->{hostname_utf8}));
  500. if ($fqdn!~/$ad_zone$/i) {
  501. $fqdn=~s/\.$//;
  502. $fqdn=lc($fqdn.'.'.$ad_zone);
  503. }
  504. db_log_debug($hdb,"FOUND Auth_id: $auth_record->{id} dns_name: $fqdn_static dhcp_hostname: $fqdn");
  505. #check exists static dns name
  506. my $static_exists = 0;
  507. my $dynamic_exists = 0;
  508. my $static_ok = 0;
  509. my $dynamic_ok = 0;
  510. my $static_ref;
  511. my $dynamic_ref;
  512. if ($fqdn_static ne '') {
  513. my @dns_record=ResolveNames($fqdn_static);
  514. $static_exists = (scalar @dns_record>0);
  515. if ($static_exists) {
  516. $static_ref = join(' ',@dns_record);
  517. foreach my $dns_a (@dns_record) {
  518. if ($dns_a=~/^$dhcp_record->{ip}$/) { $static_ok = $dns_a; }
  519. }
  520. }
  521. } else { $static_ok = 1; }
  522. if ($fqdn ne '') {
  523. my @dns_record=ResolveNames($fqdn);
  524. $dynamic_exists = (scalar @dns_record>0);
  525. if ($dynamic_exists) {
  526. $dynamic_ref = join(' ',@dns_record);
  527. foreach my $dns_a (@dns_record) {
  528. if ($dns_a=~/^$dhcp_record->{ip}$/) { $dynamic_ok = $dns_a; }
  529. }
  530. }
  531. }
  532. if ($fqdn_static ne '') {
  533. if (!$static_ok) {
  534. db_log_info($hdb,"Static record mismatch! Expected $fqdn_static => $dhcp_record->{ip}, recivied: $static_ref");
  535. if (!$static_exists) {
  536. db_log_info($hdb,"Static dns hostname defined but not found. Create it ($fqdn_static => $dhcp_record->{ip})!");
  537. update_ad_hostname($fqdn_static,$dhcp_record->{ip},$ad_zone,$ad_dns,$hdb);
  538. }
  539. } else { db_log_debug($hdb,"Static record for $fqdn_static [$static_ok] correct."); }
  540. }
  541. if ($fqdn ne '' and $dynamic_ok ne '') { db_log_debug($hdb,"Dynamic record for $fqdn [$dynamic_ok] correct. No changes required."); }
  542. if ($fqdn ne '' and !$dynamic_ok) {
  543. #log only to file!!!
  544. log_error($hdb,"Dynamic record mismatch! Expected: $fqdn => $dhcp_record->{ip}, recivied: $dynamic_ref. Checking the status.");
  545. #check exists hostname
  546. my $another_hostname_exists = 0;
  547. my $hostname_filter = ' LOWER(dns_name)="'.lc($dhcp_record->{hostname_utf8}).'"';
  548. if ($fqdn_static ne '' and $fqdn !~/$fqdn_static/) { $hostname_filter = $hostname_filter . ' or LOWER(dns_name)="'.lc($auth_record->{dns_name}).'"'; }
  549. #check exists another records with some static hostname
  550. my $name_record = get_record_sql($hdb,'SELECT * FROM User_auth WHERE id<>'.$auth_record->{id}.' and deleted=0 and ('.$hostname_filter.') ORDER BY last_found DESC');
  551. if ($name_record->{id}) { $another_hostname_exists = 1; }
  552. if (!$another_hostname_exists) {
  553. if ($fqdn_static and $fqdn_static ne '') {
  554. if ($fqdn_static!~/$fqdn/) {
  555. db_log_info($hdb,"Hostname from dhcp request $fqdn differs from static dns hostanme $fqdn_static. Ignore dynamic binding!");
  556. # update_ad_hostname($fqdn,$dhcp_record->{ip},$ad_zone,$ad_dns,$hdb);
  557. }
  558. } else {
  559. db_log_info($hdb,"Static dns hostname not defined. Create dns record by dhcp request. $fqdn => $dhcp_record->{ip}");
  560. update_ad_hostname($fqdn,$dhcp_record->{ip},$ad_zone,$ad_dns,$hdb);
  561. }
  562. } else {
  563. db_log_error($hdb,"Found another record with some hostname id: $name_record->{id} ip: $name_record->{ip} hostname: $name_record->{dns_hostname}. Skip update.");
  564. }
  565. }
  566. #end update dns block
  567. }
  568. #------------------------------------------------------------------------------------------------------------
  569. sub update_ad_hostname {
  570. my $fqdn = shift;
  571. my $ip = shift;
  572. my $zone = shift;
  573. my $server = shift;
  574. my $db = shift;
  575. if (!$db) {
  576. log_info("DNS-UPDATE: Zone $zone Server: $server A: $fqdn IP: $ip");
  577. } else {
  578. db_log_info($db,"DNS-UPDATE: Zone $zone Server: $server A: $fqdn IP: $ip");
  579. }
  580. my @add_dns=();
  581. push(@add_dns,"gsstsig");
  582. push(@add_dns,"server $server");
  583. push(@add_dns,"zone $zone");
  584. push(@add_dns,"update delete $fqdn A");
  585. push(@add_dns,"update add $fqdn 3600 A $ip");
  586. push(@add_dns,"send");
  587. my $nsupdate_file = "/tmp/".$fqdn.".nsupdate";
  588. write_to_file($nsupdate_file,\@add_dns);
  589. do_exec('kinit -k -t /usr/local/scripts/cfg/dns_updater.keytab dns_updater@'.uc($zone).' && nsupdate "'.$nsupdate_file.'"');
  590. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  591. }
  592. #---------------------------------------------------------------------------------------------------------------
  593. sub resurrection_auth {
  594. my $db = shift;
  595. my $ip = shift;
  596. my $mac = shift;
  597. my $action = shift;
  598. my $hostname = shift;
  599. my $ip_aton=StrToIp($ip);
  600. my $timestamp=GetNowTime();
  601. my $record=get_record_sql($db,'SELECT * FROM User_auth WHERE `deleted`=0 AND `ip_int`='.$ip_aton.' AND `mac`="'.$mac.'"');
  602. my $new_record;
  603. $new_record->{last_found}=$timestamp;
  604. if ($record->{user_id}) {
  605. if ($action!~/arp/i) {
  606. $new_record->{dhcp_action}=$action;
  607. $new_record->{dhcp_time}=$timestamp;
  608. update_record($db,'User_auth',$new_record,"id=$record->{id}");
  609. } else {
  610. update_record($db,'User_auth',$new_record,"id=$record->{id}");
  611. }
  612. return $record->{id};
  613. }
  614. #default user
  615. my $new_user_id=get_new_user_id($db,$ip,$mac,$hostname);
  616. #search changed mac
  617. $record=get_record_sql($db,'SELECT * FROM User_auth WHERE `ip_int`='.$ip_aton." and deleted=0");
  618. if ($record->{id}) {
  619. if (!$record->{mac}) {
  620. db_log_verbose($db,"use empty auth record...");
  621. $new_record->{ip_int}=$ip_aton;
  622. $new_record->{ip}=$ip;
  623. $new_record->{mac}=$mac;
  624. $new_record->{user_id}=$new_user_id;
  625. if ($action!~/arp/i) {
  626. $new_record->{dhcp_action}=$action;
  627. $new_record->{dhcp_time}=$timestamp;
  628. update_record($db,'User_auth',$new_record,"id=$record->{id}");
  629. } else {
  630. update_record($db,'User_auth',$new_record,"id=$record->{id}");
  631. }
  632. return $record->{id};
  633. }
  634. if ($record->{mac}) {
  635. db_log_warning($db,"For ip: $ip mac change detected! Old mac: [".$record->{mac}."] New mac: [".$mac."]. Disable old auth_id: $record->{id}");
  636. my $disable_record;
  637. $disable_record->{deleted}="1";
  638. update_record($db,'User_auth',$disable_record,"id=".$record->{id});
  639. }
  640. }
  641. #seek old auth with same ip and mac
  642. my $auth_exists=get_count_records($db,'User_auth',"ip_int=".$ip_aton." and mac='".$mac."'");
  643. $new_record->{ip_int}=$ip_aton;
  644. $new_record->{ip}=$ip;
  645. $new_record->{mac}=$mac;
  646. $new_record->{user_id}=$new_user_id;
  647. $new_record->{save_traf}="$save_detail";
  648. $new_record->{deleted}="0";
  649. $new_record->{dhcp_action}=$action;
  650. $new_record->{dhcp_time}=$timestamp;
  651. if ($auth_exists) {
  652. #found ->Resurrection old record
  653. my $resurrection_id = get_id_record($db,'User_auth',"ip_int=".$ip_aton." and mac='".$mac."'");
  654. if (!is_hotspot($db,$ip)) { db_log_warning($db,"Resurrection auth_id: $resurrection_id with ip: $ip and mac: $mac"); }
  655. else { db_log_info($db,"Resurrection auth_id: $resurrection_id with ip: $ip and mac: $mac"); }
  656. update_record($db,'User_auth',$new_record,"id=$resurrection_id");
  657. } else {
  658. #not found ->create new record
  659. if (!is_hotspot($db,$ip)) { db_log_warning($db,"New ip created! ip: $ip mac: $mac"); } else { db_log_info($db,"New ip created! ip: $ip mac: $mac"); }
  660. insert_record($db,'User_auth',$new_record);
  661. }
  662. #filter and status
  663. my $cur_auth_id=get_id_record($db,'User_auth',"ip='$ip' and mac='$mac' and deleted=0 ORDER BY last_found DESC");
  664. if ($cur_auth_id) {
  665. $record=get_record_sql($db,"SELECT * FROM User_list WHERE id=".$new_user_id);
  666. if ($record) {
  667. $new_record->{filter_group_id}=$record->{filter_group_id};
  668. $new_record->{queue_id}=$record->{queue_id};
  669. $new_record->{enabled}="$record->{enabled}";
  670. update_record($db,'User_auth',$new_record,"id=$cur_auth_id");
  671. }
  672. } else { return; }
  673. return $cur_auth_id;
  674. }
  675. #---------------------------------------------------------------------------------------------------------------
  676. sub new_auth {
  677. my $db = shift;
  678. my $ip = shift;
  679. my $ip_aton=StrToIp($ip);
  680. my $record=get_record_sql($db,'SELECT id FROM User_auth WHERE `deleted`=0 AND `ip_int`='.$ip_aton);
  681. if ($record->{id}) { return $record->{id}; }
  682. #default user
  683. my $new_user_id=get_new_user_id($db,$ip);
  684. my $user_record=get_record_sql($db,"SELECT * FROM User_list WHERE id=".$new_user_id);
  685. my $timestamp=GetNowTime();
  686. my $new_record;
  687. $new_record->{ip_int}=$ip_aton;
  688. $new_record->{ip}=$ip;
  689. $new_record->{user_id}=$new_user_id;
  690. $new_record->{save_traf}="$save_detail";
  691. $new_record->{deleted}="0";
  692. $new_record->{dhcp_action}='netflow';
  693. $new_record->{filter_group_id}=$user_record->{filter_group_id};
  694. $new_record->{queue_id}=$user_record->{queue_id};
  695. $new_record->{enabled}="$user_record->{enabled}";
  696. my $cur_auth_id=insert_record($db,'User_auth',$new_record);
  697. db_log_warning($db,"New ip created by netflow! ip: $ip") if (!$cur_auth_id);
  698. return $cur_auth_id;
  699. }
  700. #---------------------------------------------------------------------------------------------------------------
  701. sub get_option {
  702. my $db=shift;
  703. my $option_id=shift;
  704. return if (!$option_id);
  705. return if (!$db);
  706. my $default_option = get_record_sql($db,'SELECT * FROM config_options WHERE id='.$option_id);
  707. my $config_options = get_record_sql($db,'SELECT * FROM config WHERE option_id='.$option_id);
  708. my $result;
  709. if (!$config_options) {
  710. if ($default_option->{'type'}=~/int/i or $default_option->{'type'}=~/bool/i) {
  711. $result = $default_option->{'default_value'}*1;
  712. } else {
  713. $result = $default_option->{'default_value'};
  714. }
  715. return $result;
  716. }
  717. $result = $config_options->{'value'};
  718. return $result;
  719. }
  720. #---------------------------------------------------------------------------------------------------------------
  721. sub init_option {
  722. my $db=shift;
  723. $last_refresh_config = time();
  724. $config_ref{dbh}=$db;
  725. $config_ref{save_detail}=get_option($db,23);
  726. $config_ref{add_unknown_user}=get_option($db,22);
  727. $config_ref{dns_server}=get_option($db,3);
  728. $config_ref{dhcp_server}=get_option($db,5);
  729. $config_ref{snmp_default_version}=get_option($db,9);
  730. $config_ref{snmp_default_community}=get_option($db,11);
  731. $config_ref{KB}=get_option($db,1);
  732. $config_ref{mac_discovery}=get_option($db,17);
  733. $config_ref{arp_discovery}=get_option($db,19);
  734. $config_ref{default_user_id}=get_option($db,20);
  735. $config_ref{admin_email}=get_option($db,21);
  736. $config_ref{sender_email}=get_option($db,52);
  737. $config_ref{send_email}=get_option($db,51);
  738. $config_ref{history}=get_option($db,26);
  739. $config_ref{history_dhcp}=get_option($db,27);
  740. $config_ref{router_login}=get_option($db,28);
  741. $config_ref{router_password}=get_option($db,29);
  742. $config_ref{router_port}=get_option($db,30);
  743. $config_ref{org_name}=get_option($db,32);
  744. $config_ref{domain_name}=get_option($db,33);
  745. $config_ref{connections_history}=get_option($db,35);
  746. $config_ref{debug}=get_option($db,34);
  747. $config_ref{log_level} = get_option($db,53);
  748. if ($config_ref{debug}) { $config_ref{log_level} = 255; }
  749. $config_ref{urgent_sync}=get_option($db,50);
  750. $config_ref{ignore_hotspot_dhcp_log} = get_option($db,44);
  751. $config_ref{ignore_update_dhcp_event} = get_option($db,45);
  752. $config_ref{update_hostname_from_dhcp} = get_option($db,46);
  753. $config_ref{hotspot_user_id}=get_option($db,43);
  754. $config_ref{history_log_day}=get_option($db,47);
  755. $config_ref{history_syslog_day} = get_option($db,48);
  756. $config_ref{history_trafstat_day} = get_option($db,49);
  757. $config_ref{enable_quotes} = get_option($db,54);
  758. $config_ref{netflow_step} = get_option($db,55);
  759. $config_ref{traffic_ipstat_history} = get_option($db,56);
  760. $config_ref{nagios_url} = get_option($db,57);
  761. $config_ref{cacti_url} = get_option($db,58);
  762. $config_ref{torrus_url} = get_option($db,59);
  763. $config_ref{wiki_url} = get_option($db,60);
  764. $config_ref{stat_url} = get_option($db,62);
  765. $config_ref{wiki_path} = get_option($db,61);
  766. #$save_detail = 1; id=23
  767. $save_detail=get_option($db,23);
  768. #$add_unknown_user = 1; id=22
  769. $add_unknown_user=get_option($db,22);
  770. #$dns_server='192.168.2.12'; id=3
  771. $dns_server=get_option($db,3);
  772. #$dhcp_server='192.168.2.12'; id=5
  773. $dhcp_server=get_option($db,5);
  774. #$snmp_default_version='2'; id=9
  775. $snmp_default_version=get_option($db,9);
  776. #$snmp_default_community='public'; id=11
  777. $snmp_default_community=get_option($db,11);
  778. #$KB=1024; id=1
  779. $KB=get_option($db,1);
  780. #$mac_discovery; id=17
  781. $mac_discovery=get_option($db,17);
  782. #$arp_discovery; id=19
  783. $arp_discovery=get_option($db,19);
  784. #$default_user_id; id=20
  785. $default_user_id=get_option($db,20);
  786. #$admin_email; id=21
  787. $admin_email=get_option($db,21);
  788. #sender email
  789. $sender_email=get_option($db,52);
  790. #send email
  791. $send_email=get_option($db,51);
  792. #$history=15; id=26
  793. $history=get_option($db,26);
  794. #$history_dhcp=7; id=27
  795. $history_dhcp=get_option($db,27);
  796. #$router_login="admin"; id=28
  797. $router_login=get_option($db,28);
  798. #$router_password="admin"; id=29
  799. $router_password=get_option($db,29);
  800. #$router_port=23; id=30
  801. $router_port=get_option($db,30);
  802. #32
  803. $org_name=get_option($db,32);
  804. #33
  805. $domain_name=get_option($db,33);
  806. #35
  807. $connections_history=get_option($db,35);
  808. #debug
  809. $debug=get_option($db,34);
  810. #log level
  811. $log_level = get_option($db,53);
  812. if ($debug) { $log_level = 255; }
  813. #urgent sync access
  814. $urgent_sync=get_option($db,50);
  815. $ignore_hotspot_dhcp_log = get_option($db,44);
  816. $ignore_update_dhcp_event = get_option($db,45);
  817. $update_hostname_from_dhcp = get_option($db,46);
  818. #$hotspot_user_id; id=43
  819. $hotspot_user_id=get_option($db,43);
  820. $history_log_day=get_option($db,47);
  821. $history_syslog_day = get_option($db,48);
  822. $history_trafstat_day = get_option($db,49);
  823. @subnets=get_records_sql($db,'SELECT * FROM subnets ORDER BY ip_int_start');
  824. if (defined $office_networks) { undef $office_networks; }
  825. if (defined $free_networks) { undef $free_networks; }
  826. if (defined $vpn_networks) { undef $vpn_networks; }
  827. if (defined $hotspot_networks) { undef $hotspot_networks; }
  828. if (defined $all_networks) { undef $all_networks; }
  829. $office_networks = new Net::Patricia;
  830. $free_networks = new Net::Patricia;
  831. $vpn_networks = new Net::Patricia;
  832. $hotspot_networks = new Net::Patricia;
  833. $all_networks = new Net::Patricia;
  834. @office_network_list=();
  835. @free_network_list=();
  836. @free_network_list=();
  837. @vpn_network_list=();
  838. @hotspot_network_list=();
  839. @all_network_list=();
  840. foreach my $net (@subnets) {
  841. next if (!$net->{subnet});
  842. $subnets_ref{$net->{subnet}}=$net;
  843. if ($net->{office}) {
  844. push(@office_network_list,$net->{subnet});
  845. $office_networks->add_string($net->{subnet});
  846. }
  847. if ($net->{free}) {
  848. push(@free_network_list,$net->{subnet});
  849. $free_networks->add_string($net->{subnet});
  850. }
  851. if ($net->{vpn}) {
  852. push(@vpn_network_list,$net->{subnet});
  853. $vpn_networks->add_string($net->{subnet});
  854. }
  855. if ($net->{hotspot}) {
  856. push(@hotspot_network_list,$net->{subnet});
  857. push(@all_network_list,$net->{subnet});
  858. $hotspot_networks->add_string($net->{subnet});
  859. }
  860. push(@all_network_list,$net->{subnet});
  861. $all_networks->add_string($net->{subnet});
  862. }
  863. #remove all rules for default user id and hotspot subnet
  864. #delete_record($db,"auth_rules","user_id=".$config_ref{default_user_id});
  865. #delete_record($db,"auth_rules","user_id=".$config_ref{hotspot_user_id});
  866. #foreach my $subnet (@hotspot_network_list) { delete_record($db,"auth_rules","rule='".$subnet."'"); }
  867. }
  868. #---------------------------------------------------------------------------------------------------------------
  869. sub get_subnets_ref {
  870. my $db = shift;
  871. my @list=get_records_sql($db,'SELECT * FROM subnets ORDER BY ip_int_start');
  872. my $list_ref;
  873. foreach my $net (@list) {
  874. next if (!$net->{subnet});
  875. $list_ref->{$net->{subnet}}=$net;
  876. }
  877. return $list_ref;
  878. }
  879. #---------------------------------------------------------------------------------------------------------------
  880. sub get_device_by_ip {
  881. my $db = shift;
  882. my $ip = shift;
  883. my $netdev=get_record_sql($db,'SELECT * FROM devices WHERE ip="'.$ip.'"');
  884. if ($netdev and $netdev->{id}>0) { return $netdev; }
  885. my $auth_rec=get_record_sql($db,'SELECT user_id FROM User_auth WHERE ip="'.$ip.'" and deleted=0');
  886. if ($auth_rec and $auth_rec->{user_id}>0) {
  887. $netdev=get_record_sql($db,'SELECT * FROM devices WHERE user_id='.$auth_rec->{user_id});
  888. return $netdev;
  889. }
  890. return;
  891. }
  892. #---------------------------------------------------------------------------------------------------------------
  893. sub GetUnixTimeByStr {
  894. my $time_str = shift;
  895. $time_str =~s/\//-/g;
  896. $time_str = trim($time_str);
  897. my ($sec,$min,$hour,$day,$mon,$year) = (localtime())[0,1,2,3,4,5];
  898. $year+=1900;
  899. $mon++;
  900. if ($time_str =~/^([0-9]{2,4})\-([0-9]{1,2})-([0-9]{1,2})\s+/) {
  901. $year = $1; $mon = $2; $day = $3;
  902. }
  903. if ($time_str =~/([0-9]{1,2})\:([0-9]{1,2})\:([0-9]{1,2})$/) {
  904. $hour = $1; $min = $2; $sec = $3;
  905. }
  906. my $result = mktime($sec,$min,$hour,$day,$mon-1,$year-1900);
  907. return $result;
  908. }
  909. #---------------------------------------------------------------------------------------------------------------
  910. sub GetTimeStrByUnixTime {
  911. my $time = shift || time();
  912. my ($sec, $min, $hour, $mday, $mon, $year) = (localtime($time))[0,1,2,3,4,5];
  913. my $result = strftime("%Y-%m-%d %H:%M:%S",$sec, $min, $hour, $mday, $mon, $year);
  914. return $result;
  915. }
  916. #---------------------------------------------------------------------------------------------------------------
  917. sub Set_Variable {
  918. my $db = shift;
  919. my $name = shift || $MY_NAME;
  920. my $value = shift || $$;
  921. my $timeshift = shift || 60;
  922. Del_Variable($db,$name);
  923. my $clean_variables = time() + $timeshift;
  924. my ($sec,$min,$hour,$day,$month,$year,$zone) = localtime($clean_variables);
  925. $month++;
  926. $year += 1900;
  927. my $clean_str=sprintf "%04d-%02d-%02d %02d:%02d:%02d",$year,$month,$day,$hour,$min,$sec;
  928. my $clean_variables_date=$db->quote($clean_str);
  929. do_sql($db,"INSERT INTO variables(name,value,clear_time) VALUES('".$name."','".$value."',".$clean_variables_date.");");
  930. }
  931. #---------------------------------------------------------------------------------------------------------------
  932. sub Get_Variable {
  933. my $db = shift;
  934. my $name = shift || $MY_NAME;
  935. my $variable=get_record_sql($db,'SELECT `value` FROM `variables` WHERE name="'.$name.'"');
  936. if (!$variable and $variable->{'value'}) { return $variable->{'value'}; }
  937. return;
  938. }
  939. #---------------------------------------------------------------------------------------------------------------
  940. sub Del_Variable {
  941. my $db = shift;
  942. my $name = shift || $MY_NAME;
  943. do_sql($db,"DELETE FROM `variables` WHERE name='".$name."';");
  944. }
  945. #---------------------------------------------------------------------------------------------------------------
  946. sub recalc_quotes {
  947. my $db = shift;
  948. my $calc_id = shift || $$;
  949. return if (!get_option($db,54));
  950. clean_variables($db);
  951. return if (Get_Variable($db,'RECALC'));
  952. my $timeshift = get_option($db,55);
  953. if ($timeshift >5 ) { $timeshift=$timeshift-1; }
  954. Set_Variable($db,'RECALC',$calc_id,time()+$timeshift*60);
  955. my $now = DateTime->now(time_zone=>'local');
  956. my $day_start = $db->quote($now->ymd("-")." 00:00:00");
  957. my $day_dur = DateTime::Duration->new( days => 1 );
  958. my $tomorrow = $now+$day_dur;
  959. my $day_stop = $db->quote($tomorrow->ymd("-")." 00:00:00");
  960. $now->set(day=>1);
  961. my $month_start=$db->quote($now->ymd("-")." 00:00:00");
  962. my $month_dur = DateTime::Duration->new( months => 1 );
  963. my $next_month = $now + $month_dur;
  964. $next_month->set(day=>1);
  965. my $month_stop = $db->quote($next_month->ymd("-")." 00:00:00");
  966. #get user limits
  967. 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";
  968. my @authlist_ref = get_records_sql($db,$user_auth_list_sql);
  969. my %user_stats;
  970. my %auth_info;
  971. foreach my $row (@authlist_ref) {
  972. $auth_info{$row->{auth_id}}{user_id}=$row->{id};
  973. $auth_info{$row->{auth_id}}{day_limit}=$row->{auth_day};
  974. $auth_info{$row->{auth_id}}{month_limit}=$row->{auth_month};
  975. $auth_info{$row->{auth_id}}{day}=0;
  976. $auth_info{$row->{auth_id}}{month}=0;
  977. $user_stats{$row->{id}}{day_limit}=$row->{day_quota};
  978. $user_stats{$row->{id}}{month_limit}=$row->{month_quota};
  979. $user_stats{$row->{id}}{day}=0;
  980. $user_stats{$row->{id}}{month}=0;
  981. }
  982. #recalc quotes - global
  983. #day
  984. my $day_sql="SELECT User_stats.auth_id, SUM( byte_in + byte_out ) AS traf_all FROM User_stats
  985. WHERE User_stats.`timestamp`>= $day_start AND User_stats.`timestamp`< $day_stop GROUP BY User_stats.auth_id";
  986. my @day_stats = get_records_sql($db,$day_sql);
  987. foreach my $row (@day_stats) {
  988. my $user_id=$auth_info{$row->{auth_id}}{user_id};
  989. $auth_info{$row->{auth_id}}{day}=$row->{traf_all};
  990. $user_stats{$user_id}{day}+=$row->{traf_all};
  991. }
  992. #month
  993. my $month_sql="SELECT User_stats.auth_id, SUM( byte_in + byte_out ) AS traf_all FROM User_stats
  994. WHERE User_stats.`timestamp`>= $month_start AND User_stats.`timestamp`< $month_stop GROUP BY User_stats.auth_id";
  995. my @month_stats = get_records_sql($db,$month_sql);
  996. foreach my $row (@month_stats) {
  997. my $user_id=$auth_info{$row->{auth_id}}{user_id};
  998. $auth_info{$row->{auth_id}}{month}=$row->{traf_all};
  999. $user_stats{$user_id}{month}+=$row->{traf_all};
  1000. }
  1001. foreach my $auth_id (keys %auth_info) {
  1002. next if (!$auth_info{$auth_id}{day_limit});
  1003. next if (!$auth_info{$auth_id}{month_limit});
  1004. my $day_limit=$auth_info{$auth_id}{day_limit}*$KB*$KB;
  1005. my $month_limit=$auth_info{$auth_id}{month_limit}*$KB*$KB;
  1006. my $blocked_d=($auth_info{$auth_id}{day}>$day_limit);
  1007. my $blocked_m=($auth_info{$auth_id}{month}>$month_limit);
  1008. if ($blocked_d or $blocked_m) {
  1009. my $history_msg;
  1010. 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; }
  1011. 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; }
  1012. do_sql($db,"UPDATE User_auth set blocked=1, changed=1 where id=$auth_id");
  1013. db_log_verbose($db,$history_msg);
  1014. }
  1015. }
  1016. foreach my $user_id (keys %user_stats) {
  1017. next if (!$user_stats{$user_id}{day_limit});
  1018. next if (!$user_stats{$user_id}{month_limit});
  1019. my $day_limit=$user_stats{$user_id}{day_limit}*$KB*$KB;
  1020. my $month_limit=$user_stats{$user_id}{month_limit}*$KB*$KB;
  1021. my $blocked_d=($user_stats{$user_id}{day}>$day_limit);
  1022. my $blocked_m=($user_stats{$user_id}{month}>$month_limit);
  1023. if ($blocked_d or $blocked_m) {
  1024. my $history_msg;
  1025. 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; }
  1026. 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; }
  1027. do_sql($db,"UPDATE User_user set blocked=1 where id=$user_id");
  1028. do_sql($db,"UPDATE User_auth set blocked=1, changed=1 where user_id=$user_id");
  1029. db_log_verbose($db,$history_msg);
  1030. }
  1031. }
  1032. Del_Variable($db,'RECALC');
  1033. }
  1034. #---------------------------------------------------------------------------------------------------------------
  1035. sub clean_variables {
  1036. my $db = shift;
  1037. #clean temporary variables
  1038. my $clean_variables = time();
  1039. my ($sec,$min,$hour,$day,$month,$year,$zone) = localtime($clean_variables);
  1040. $month++;
  1041. $year += 1900;
  1042. my $now_str=sprintf "%04d-%02d-%02d %02d:%02d:%02d",$year,$month,$day,$hour,$min,$sec;
  1043. my $clean_variables_date=$db->quote($now_str);
  1044. do_sql($db,"DELETE FROM `variables` WHERE clear_time<=$clean_variables_date");
  1045. }
  1046. #---------------------------------------------------------------------------------------------------------------
  1047. $dbh=init_db();
  1048. init_option($dbh);
  1049. clean_variables($dbh);
  1050. Set_Variable($dbh);
  1051. 1;
  1052. }