1
0

mysql.pm 38 KB

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