mysql.pm 39 KB

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