mysql.pm 39 KB

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