mysql.pm 42 KB

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