mysql.pm 39 KB

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