mysql.pm 44 KB

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