mysql.pm 38 KB

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