mysql.pm 43 KB

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