mysql.pm 42 KB

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