mysql.pm 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362
  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("Dhcp record: ".Dumper($dhcp_record));
  521. log_debug("Subnets: ".Dumper($subnets_dhcp->{$dhcp_record->{network}->{subnet}}));
  522. log_debug("enable_ad_dns_update: ".$enable_ad_dns_update);
  523. log_debug("DNS update flags - zone: ".$ad_zone.",dns: ".$ad_dns.", update_hostname_from_dhcp: ".$update_hostname_from_dhcp.", enable_ad_dns_update: ".$enable_ad_dns_update);
  524. 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}->{subnet}}->{dhcp_update_hostname});
  525. if (!$maybe_update_dns) {
  526. db_log_debug($hdb,"FOUND Auth_id: $auth_record->{id}. DNS update don't needed.");
  527. return 0;
  528. }
  529. log_debug("DNS update enabled.");
  530. #update dns block
  531. my $fqdn_static;
  532. if ($auth_record->{dns_name}) {
  533. $fqdn_static=lc($auth_record->{dns_name});
  534. if ($fqdn_static!~/\.$ad_zone$/i) {
  535. $fqdn_static=~s/\.$//;
  536. $fqdn_static=lc($fqdn_static.'.'.$ad_zone);
  537. }
  538. }
  539. my $fqdn=lc(trim($dhcp_record->{hostname_utf8}));
  540. if ($fqdn!~/\.$ad_zone$/i) {
  541. $fqdn=~s/\.$//;
  542. $fqdn=lc($fqdn.'.'.$ad_zone);
  543. }
  544. db_log_debug($hdb,"FOUND Auth_id: $auth_record->{id} dns_name: $fqdn_static dhcp_hostname: $fqdn");
  545. #check exists static dns name
  546. my $static_exists = 0;
  547. my $dynamic_exists = 0;
  548. my $static_ok = 0;
  549. my $dynamic_ok = 0;
  550. my $static_ref;
  551. my $dynamic_ref;
  552. if ($fqdn_static ne '') {
  553. my @dns_record=ResolveNames($fqdn_static);
  554. $static_exists = (scalar @dns_record>0);
  555. if ($static_exists) {
  556. $static_ref = join(' ',@dns_record);
  557. foreach my $dns_a (@dns_record) {
  558. if ($dns_a=~/^$dhcp_record->{ip}$/) { $static_ok = $dns_a; }
  559. }
  560. }
  561. } else { $static_ok = 1; }
  562. if ($fqdn ne '') {
  563. my @dns_record=ResolveNames($fqdn);
  564. $dynamic_exists = (scalar @dns_record>0);
  565. if ($dynamic_exists) {
  566. $dynamic_ref = join(' ',@dns_record);
  567. foreach my $dns_a (@dns_record) {
  568. if ($dns_a=~/^$dhcp_record->{ip}$/) { $dynamic_ok = $dns_a; }
  569. }
  570. }
  571. }
  572. db_log_debug($hdb,"Dns record for static record $fqdn_static: $static_ok");
  573. db_log_debug($hdb,"Dns record for dhcp-hostname $fqdn: $dynamic_ok");
  574. if ($fqdn_static ne '') {
  575. if (!$static_ok) {
  576. db_log_info($hdb,"Static record mismatch! Expected $fqdn_static => $dhcp_record->{ip}, recivied: $static_ref");
  577. if (!$static_exists) {
  578. db_log_info($hdb,"Static dns hostname defined but not found. Create it ($fqdn_static => $dhcp_record->{ip})!");
  579. update_ad_hostname($fqdn_static,$dhcp_record->{ip},$ad_zone,$ad_dns,$hdb);
  580. }
  581. } else {
  582. db_log_debug($hdb,"Static record for $fqdn_static [$static_ok] correct.");
  583. }
  584. }
  585. if ($fqdn ne '' and $dynamic_ok ne '') { db_log_debug($hdb,"Dynamic record for $fqdn [$dynamic_ok] correct. No changes required."); }
  586. if ($fqdn ne '' and !$dynamic_ok) {
  587. #log event without email alert
  588. log_error("Dynamic record mismatch! Expected: $fqdn => $dhcp_record->{ip}, recivied: $dynamic_ref. Checking the status.");
  589. #check exists hostname
  590. my $another_hostname_exists = 0;
  591. my $hostname_filter = ' LOWER(dns_name) REGEXP("^'.lc($dhcp_record->{hostname_utf8}).'\.*$")';
  592. if ($fqdn_static ne '' and $fqdn !~/$fqdn_static/) {
  593. $hostname_filter = $hostname_filter . ' or LOWER(dns_name) REGEXP("^'.lc($auth_record->{dns_name}).'\.*$")';
  594. }
  595. #check exists another records with some static hostname
  596. my $filter_sql = 'SELECT * FROM User_auth WHERE id<>'.$auth_record->{id}.' and deleted=0 and ('.$hostname_filter.') ORDER BY last_found DESC';
  597. db_log_debug($hdb,"Search dhcp hostname by: ".$filter_sql);
  598. my $name_record = get_record_sql($hdb,$filter_sql);
  599. if ($name_record->{dns_name} =~/^$fqdn$/i or $name_record->{dns_name} =~/^$dhcp_record->{hostname_utf8}$/i) {
  600. $another_hostname_exists = 1;
  601. }
  602. if (!$another_hostname_exists) {
  603. if ($fqdn_static and $fqdn_static ne '') {
  604. if ($fqdn_static!~/$fqdn/) {
  605. db_log_info($hdb,"Hostname from dhcp request $fqdn differs from static dns hostanme $fqdn_static. Ignore dynamic binding!");
  606. # update_ad_hostname($fqdn,$dhcp_record->{ip},$ad_zone,$ad_dns,$hdb);
  607. }
  608. } else {
  609. db_log_info($hdb,"Static dns hostname not defined. Create dns record by dhcp request. $fqdn => $dhcp_record->{ip}");
  610. update_ad_hostname($fqdn,$dhcp_record->{ip},$ad_zone,$ad_dns,$hdb);
  611. }
  612. } else {
  613. db_log_error($hdb,"Found another record with some hostname id: $name_record->{id} ip: $name_record->{ip} hostname: $name_record->{dns_name}. Skip update.");
  614. }
  615. }
  616. #end update dns block
  617. }
  618. #------------------------------------------------------------------------------------------------------------
  619. sub update_ad_hostname {
  620. my $fqdn = shift;
  621. my $ip = shift;
  622. my $zone = shift;
  623. my $server = shift;
  624. my $db = shift;
  625. if (!$db) {
  626. log_info("DNS-UPDATE: Zone $zone Server: $server A: $fqdn IP: $ip");
  627. } else {
  628. db_log_info($db,"DNS-UPDATE: Zone $zone Server: $server A: $fqdn IP: $ip");
  629. }
  630. my $ad_zone = get_option($db,33);
  631. my @add_dns=();
  632. push(@add_dns,"gsstsig");
  633. push(@add_dns,"server $server");
  634. push(@add_dns,"zone $zone");
  635. push(@add_dns,"update delete $fqdn A");
  636. push(@add_dns,"update add $fqdn 3600 A $ip");
  637. push(@add_dns,"send");
  638. my $nsupdate_file = "/tmp/".$fqdn.".nsupdate";
  639. write_to_file($nsupdate_file,\@add_dns);
  640. do_exec('/usr/bin/kinit -k -t /usr/local/scripts/cfg/dns_updater.keytab dns_updater@'.uc($ad_zone).' && /usr/bin/nsupdate "'.$nsupdate_file.'"');
  641. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  642. }
  643. #---------------------------------------------------------------------------------------------------------------
  644. sub update_ad_ptr {
  645. my $fqdn = shift;
  646. my $ip = shift;
  647. my $server = shift;
  648. my $db = shift;
  649. my $radr;
  650. my $zone;
  651. if ($ip =~ /([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})(\/[0-9]{1,2}){0,1}/) {
  652. return 0 if($1 > 255 || $2 > 255 || $3 > 255 || $4 > 255);
  653. $radr = "$4.$3.$2.$1.in-addr.arpa";
  654. $zone = "$3.$2.$1.in-addr.arpa";
  655. }
  656. if (!$radr or !$zone) { return 0; }
  657. if (!$db) {
  658. log_info("DNS-UPDATE: Zone $zone Server: $server A: $fqdn PTR: $ip");
  659. } else {
  660. db_log_info($db,"DNS-UPDATE: Zone $zone Server: $server A: $fqdn PTR: $ip");
  661. }
  662. my $ad_zone = get_option($db,33);
  663. my @add_dns=();
  664. push(@add_dns,"gsstsig");
  665. push(@add_dns,"server $server");
  666. push(@add_dns,"zone $zone");
  667. push(@add_dns,"update delete $radr PTR");
  668. push(@add_dns,"update add $radr 3600 PTR $fqdn.");
  669. push(@add_dns,"send");
  670. my $nsupdate_file = "/tmp/".$radr.".nsupdate";
  671. write_to_file($nsupdate_file,\@add_dns);
  672. my $run_cmd = '/usr/bin/kinit -k -t /usr/local/scripts/cfg/dns_updater.keytab dns_updater@'.uc($ad_zone).' && /usr/bin/nsupdate "'.$nsupdate_file.'"';
  673. do_exec($run_cmd);
  674. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  675. }
  676. #---------------------------------------------------------------------------------------------------------------
  677. sub new_user {
  678. my $db = shift;
  679. my $user_info = shift;
  680. my $user;
  681. if ($user_info->{mac}) {
  682. $user->{login}=mac_splitted($user_info->{mac});
  683. } else {
  684. $user->{login}=$user_info->{ip};
  685. }
  686. if ($user_info->{dhcp_hostname}) {
  687. $user->{fio}=$user_info->{ip}. '['.$user_info->{dhcp_hostname} .']';
  688. } else {
  689. $user->{fio}=$user_info->{ip};
  690. }
  691. my $login_count = get_count_records($db,"User_list","(login LIKE '".$user->{login}."(%)') OR (login='".$user->{login}."')");
  692. if ($login_count) { $login_count++; $user->{login} .="(".$login_count.")"; }
  693. $user->{ou_id} = $user_info->{ou_id};
  694. my $ou_info = get_record_sql($db,"SELECT * FROM OU WHERE id=".$user_info->{'ou_id'});
  695. if ($ou_info) {
  696. $user->{'enabled'} = $ou_info->{'enabled'};
  697. $user->{'queue_id'} = $ou_info->{'queue_id'};
  698. $user->{'filter_group_id'} = $ou_info->{'filter_group_id'};
  699. }
  700. my $result = insert_record($db,"User_list",$user);
  701. if ($result and $config_ref{auto_mac_rule} and $user_info->{mac}) {
  702. my $auth_rule;
  703. $auth_rule->{user_id} = $result;
  704. $auth_rule->{type} = 2;
  705. $auth_rule->{rule} = mac_splitted($user_info->{mac});
  706. insert_record($db,"auth_rules",$auth_rule);
  707. }
  708. return $result;
  709. }
  710. #---------------------------------------------------------------------------------------------------------------
  711. sub resurrection_auth {
  712. my $db = shift;
  713. my $ip = shift;
  714. my $mac = shift;
  715. my $action = shift;
  716. my $hostname = shift;
  717. my $ip_aton=StrToIp($ip);
  718. my $timestamp=GetNowTime();
  719. my $record=get_record_sql($db,'SELECT * FROM User_auth WHERE `deleted`=0 AND `ip_int`='.$ip_aton.' AND `mac`="'.$mac.'"');
  720. my $new_record;
  721. $new_record->{last_found}=$timestamp;
  722. #auth found?
  723. if ($record->{user_id}) {
  724. #update timestamp and return
  725. if ($action!~/arp/i) {
  726. $new_record->{dhcp_action}=$action;
  727. $new_record->{dhcp_time}=$timestamp;
  728. if ($hostname) { $new_record->{dhcp_hostname} = $hostname; }
  729. update_record($db,'User_auth',$new_record,"id=$record->{id}");
  730. } else {
  731. update_record($db,'User_auth',$new_record,"id=$record->{id}");
  732. }
  733. return $record->{id};
  734. }
  735. my $user_subnet=$office_networks->match_string($ip);
  736. if ($user_subnet->{static}) {
  737. db_log_warning($db,"Unknown ip+mac found in static subnet! Stop work for ip: $ip mac: [".$mac."]");
  738. return 0;
  739. }
  740. #search changed mac
  741. $record=get_record_sql($db,'SELECT * FROM User_auth WHERE `ip_int`='.$ip_aton." and deleted=0");
  742. if ($record->{id}) {
  743. #if found record with same ip but another mac
  744. if (!$record->{mac}) {
  745. db_log_verbose($db,"use empty auth record...");
  746. $new_record->{mac}=$mac;
  747. if ($action!~/arp/i) {
  748. $new_record->{dhcp_action}=$action;
  749. $new_record->{dhcp_time}=$timestamp;
  750. if ($hostname) { $new_record->{dhcp_hostname} = $hostname; }
  751. update_record($db,'User_auth',$new_record,"id=$record->{id}");
  752. } else {
  753. update_record($db,'User_auth',$new_record,"id=$record->{id}");
  754. }
  755. return $record->{id};
  756. }
  757. if ($record->{mac}) {
  758. db_log_warning($db,"For ip: $ip mac change detected! Old mac: [".$record->{mac}."] New mac: [".$mac."]. Disable old auth_id: $record->{id}");
  759. my $disable_record;
  760. $disable_record->{deleted}="1";
  761. update_record($db,'User_auth',$disable_record,"id=".$record->{id});
  762. }
  763. }
  764. #default user
  765. my $new_user_info=get_new_user_id($db,$ip,$mac,$hostname);
  766. my $new_user_id;
  767. if ($new_user_info->{user_id}) { $new_user_id = $new_user_info->{user_id}; }
  768. if (!$new_user_id) { $new_user_id = new_user($db,$new_user_info); }
  769. #seek old auth with same ip and mac
  770. my $auth_exists=get_count_records($db,'User_auth',"ip_int=".$ip_aton." and mac='".$mac."'");
  771. $new_record->{ip_int}=$ip_aton;
  772. $new_record->{ip}=$ip;
  773. $new_record->{mac}=$mac;
  774. $new_record->{user_id}=$new_user_id;
  775. $new_record->{save_traf}="$save_detail";
  776. $new_record->{deleted}="0";
  777. $new_record->{dhcp_action}=$action;
  778. $new_record->{dhcp_time}=$timestamp;
  779. if ($auth_exists) {
  780. #found ->Resurrection old record
  781. my $resurrection_id = get_id_record($db,'User_auth',"ip_int=".$ip_aton." and mac='".$mac."'");
  782. if (!is_hotspot($db,$ip)) { db_log_warning($db,"Resurrection auth_id: $resurrection_id with ip: $ip and mac: $mac"); }
  783. else { db_log_info($db,"Resurrection auth_id: $resurrection_id with ip: $ip and mac: $mac"); }
  784. update_record($db,'User_auth',$new_record,"id=$resurrection_id");
  785. } else {
  786. #not found ->create new record
  787. 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"); }
  788. insert_record($db,'User_auth',$new_record);
  789. }
  790. #filter and status
  791. my $cur_auth_id=get_id_record($db,'User_auth',"ip='$ip' and mac='$mac' and deleted=0 ORDER BY last_found DESC");
  792. if ($cur_auth_id) {
  793. $record=get_record_sql($db,"SELECT * FROM User_list WHERE id=".$new_user_id);
  794. if ($record) {
  795. $new_record->{ou_id}=$record->{ou_id};
  796. $new_record->{filter_group_id}=$record->{filter_group_id};
  797. $new_record->{queue_id}=$record->{queue_id};
  798. $new_record->{enabled}="$record->{enabled}";
  799. update_record($db,'User_auth',$new_record,"id=$cur_auth_id");
  800. }
  801. } else { return; }
  802. return $cur_auth_id;
  803. }
  804. #---------------------------------------------------------------------------------------------------------------
  805. sub new_auth {
  806. my $db = shift;
  807. my $ip = shift;
  808. my $ip_aton=StrToIp($ip);
  809. my $record=get_record_sql($db,'SELECT id FROM User_auth WHERE `deleted`=0 AND `ip_int`='.$ip_aton);
  810. if ($record->{id}) { return $record->{id}; }
  811. #default user
  812. my $new_user_info=get_new_user_id($db,$ip,undef,undef);
  813. my $new_user_id;
  814. if ($new_user_info->{user_id}) { $new_user_id = $new_user_info->{user_id}; }
  815. if ($new_user_info->{ou_id}) { $new_user_id = new_user($db,$new_user_info); }
  816. my $user_record=get_record_sql($db,"SELECT * FROM User_list WHERE id=".$new_user_id);
  817. my $timestamp=GetNowTime();
  818. my $new_record;
  819. $new_record->{ip_int}=$ip_aton;
  820. $new_record->{ip}=$ip;
  821. $new_record->{user_id}=$new_user_id;
  822. $new_record->{save_traf}="$save_detail";
  823. $new_record->{deleted}="0";
  824. $new_record->{dhcp_action}='netflow';
  825. $new_record->{ou_id}=$user_record->{ou_id};
  826. $new_record->{filter_group_id}=$user_record->{filter_group_id};
  827. $new_record->{queue_id}=$user_record->{queue_id};
  828. $new_record->{enabled}="$user_record->{enabled}";
  829. my $cur_auth_id=insert_record($db,'User_auth',$new_record);
  830. db_log_warning($db,"New ip created by netflow! ip: $ip") if ($cur_auth_id);
  831. return $cur_auth_id;
  832. }
  833. #---------------------------------------------------------------------------------------------------------------
  834. sub get_option {
  835. my $db=shift;
  836. my $option_id=shift;
  837. return if (!$option_id);
  838. return if (!$db);
  839. my $default_option = get_record_sql($db,'SELECT * FROM config_options WHERE id='.$option_id);
  840. my $config_options = get_record_sql($db,'SELECT * FROM config WHERE option_id='.$option_id);
  841. my $result;
  842. if (!$config_options) {
  843. if ($default_option->{'type'}=~/int/i or $default_option->{'type'}=~/bool/i) {
  844. $result = $default_option->{'default_value'}*1;
  845. } else {
  846. $result = $default_option->{'default_value'};
  847. }
  848. return $result;
  849. }
  850. $result = $config_options->{'value'};
  851. return $result;
  852. }
  853. #---------------------------------------------------------------------------------------------------------------
  854. sub init_option {
  855. my $db=shift;
  856. $last_refresh_config = time();
  857. $config_ref{dbh}=$db;
  858. $config_ref{save_detail}=get_option($db,23);
  859. $config_ref{add_unknown_user}=get_option($db,22);
  860. $config_ref{dns_server}=get_option($db,3);
  861. $config_ref{dhcp_server}=get_option($db,5);
  862. $config_ref{snmp_default_version}=get_option($db,9);
  863. $config_ref{snmp_default_community}=get_option($db,11);
  864. $config_ref{KB}=get_option($db,1);
  865. if ($config_ref{KB} ==0) { $config_ref{KB}=1000; }
  866. if ($config_ref{KB} ==1) { $config_ref{KB}=1024; }
  867. $config_ref{mac_discovery}=get_option($db,17);
  868. $config_ref{arp_discovery}=get_option($db,19);
  869. $config_ref{admin_email}=get_option($db,21);
  870. $config_ref{sender_email}=get_option($db,52);
  871. $config_ref{send_email}=get_option($db,51);
  872. $config_ref{history}=get_option($db,26);
  873. $config_ref{history_dhcp}=get_option($db,27);
  874. $config_ref{router_login}=get_option($db,28);
  875. $config_ref{router_password}=get_option($db,29);
  876. $config_ref{router_port}=get_option($db,30);
  877. $config_ref{org_name}=get_option($db,32);
  878. $config_ref{domain_name}=get_option($db,33);
  879. $config_ref{connections_history}=get_option($db,35);
  880. $config_ref{debug}=get_option($db,34);
  881. $config_ref{log_level} = get_option($db,53);
  882. if ($config_ref{debug}) { $config_ref{log_level} = 255; }
  883. $config_ref{urgent_sync}=get_option($db,50);
  884. $config_ref{ignore_hotspot_dhcp_log} = get_option($db,44);
  885. $config_ref{ignore_update_dhcp_event} = get_option($db,45);
  886. $config_ref{update_hostname_from_dhcp} = get_option($db,46);
  887. $config_ref{history_log_day}=get_option($db,47);
  888. $config_ref{history_syslog_day} = get_option($db,48);
  889. $config_ref{history_trafstat_day} = get_option($db,49);
  890. $config_ref{enable_quotes} = get_option($db,54);
  891. $config_ref{netflow_step} = get_option($db,55);
  892. $config_ref{traffic_ipstat_history} = get_option($db,56);
  893. $config_ref{nagios_url} = get_option($db,57);
  894. $config_ref{cacti_url} = get_option($db,58);
  895. $config_ref{torrus_url} = get_option($db,59);
  896. $config_ref{wiki_url} = get_option($db,60);
  897. $config_ref{stat_url} = get_option($db,62);
  898. $config_ref{wiki_path} = get_option($db,61);
  899. $config_ref{auto_mac_rule} = get_option($db,64);
  900. #$save_detail = 1; id=23
  901. $save_detail=get_option($db,23);
  902. #$add_unknown_user = 1; id=22
  903. $add_unknown_user=get_option($db,22);
  904. #$dns_server='192.168.2.12'; id=3
  905. $dns_server=get_option($db,3);
  906. #$dhcp_server='192.168.2.12'; id=5
  907. $dhcp_server=get_option($db,5);
  908. #$snmp_default_version='2'; id=9
  909. $snmp_default_version=get_option($db,9);
  910. #$snmp_default_community='public'; id=11
  911. $snmp_default_community=get_option($db,11);
  912. #$KB=1024; id=1
  913. $KB=$config_ref{KB};
  914. #$mac_discovery; id=17
  915. $mac_discovery=get_option($db,17);
  916. #$arp_discovery; id=19
  917. $arp_discovery=get_option($db,19);
  918. #$admin_email; id=21
  919. $admin_email=get_option($db,21);
  920. #sender email
  921. $sender_email=get_option($db,52);
  922. #send email
  923. $send_email=get_option($db,51);
  924. #$history=15; id=26
  925. $history=get_option($db,26);
  926. #$history_dhcp=7; id=27
  927. $history_dhcp=get_option($db,27);
  928. #$router_login="admin"; id=28
  929. $router_login=get_option($db,28);
  930. #$router_password="admin"; id=29
  931. $router_password=get_option($db,29);
  932. #$router_port=23; id=30
  933. $router_port=get_option($db,30);
  934. #32
  935. $org_name=get_option($db,32);
  936. #33
  937. $domain_name=get_option($db,33);
  938. #35
  939. $connections_history=get_option($db,35);
  940. #debug
  941. $debug=get_option($db,34);
  942. #log level
  943. $log_level = get_option($db,53);
  944. if ($debug) { $log_level = 255; }
  945. #urgent sync access
  946. $urgent_sync=get_option($db,50);
  947. $ignore_hotspot_dhcp_log = get_option($db,44);
  948. $ignore_update_dhcp_event = get_option($db,45);
  949. $update_hostname_from_dhcp = get_option($db,46);
  950. $history_log_day=get_option($db,47);
  951. $history_syslog_day = get_option($db,48);
  952. $history_trafstat_day = get_option($db,49);
  953. my $ou = get_record_sql($db,"SELECT id FROM OU WHERE default_users = 1");
  954. if (!$ou) { $default_user_ou_id = 0; } else { $default_user_ou_id = $ou->{'id'}; }
  955. $ou = get_record_sql($db,"SELECT id FROM OU WHERE default_hotspot = 1");
  956. if (!$ou) { $default_hotspot_ou_id = $default_user_ou_id; } else { $default_hotspot_ou_id = $ou->{'id'}; }
  957. @subnets=get_records_sql($db,'SELECT * FROM subnets ORDER BY ip_int_start');
  958. if (defined $office_networks) { undef $office_networks; }
  959. if (defined $free_networks) { undef $free_networks; }
  960. if (defined $vpn_networks) { undef $vpn_networks; }
  961. if (defined $hotspot_networks) { undef $hotspot_networks; }
  962. if (defined $all_networks) { undef $all_networks; }
  963. $office_networks = new Net::Patricia;
  964. $free_networks = new Net::Patricia;
  965. $vpn_networks = new Net::Patricia;
  966. $hotspot_networks = new Net::Patricia;
  967. $all_networks = new Net::Patricia;
  968. @office_network_list=();
  969. @free_network_list=();
  970. @free_network_list=();
  971. @vpn_network_list=();
  972. @hotspot_network_list=();
  973. @all_network_list=();
  974. foreach my $net (@subnets) {
  975. next if (!$net->{subnet});
  976. $subnets_ref{$net->{subnet}}=$net;
  977. if ($net->{office}) {
  978. push(@office_network_list,$net->{subnet});
  979. $office_networks->add_string($net->{subnet},$net);
  980. }
  981. if ($net->{free}) {
  982. push(@free_network_list,$net->{subnet});
  983. $free_networks->add_string($net->{subnet},$net);
  984. }
  985. if ($net->{vpn}) {
  986. push(@vpn_network_list,$net->{subnet});
  987. $vpn_networks->add_string($net->{subnet},$net);
  988. }
  989. if ($net->{hotspot}) {
  990. push(@hotspot_network_list,$net->{subnet});
  991. push(@all_network_list,$net->{subnet});
  992. $hotspot_networks->add_string($net->{subnet},$net);
  993. }
  994. push(@all_network_list,$net->{subnet});
  995. $all_networks->add_string($net->{subnet},$net);
  996. }
  997. }
  998. #---------------------------------------------------------------------------------------------------------------
  999. sub get_subnets_ref {
  1000. my $db = shift;
  1001. my @list=get_records_sql($db,'SELECT * FROM subnets ORDER BY ip_int_start');
  1002. my $list_ref;
  1003. foreach my $net (@list) {
  1004. next if (!$net->{subnet});
  1005. $list_ref->{$net->{subnet}}=$net;
  1006. }
  1007. return $list_ref;
  1008. }
  1009. #---------------------------------------------------------------------------------------------------------------
  1010. sub get_device_by_ip {
  1011. my $db = shift;
  1012. my $ip = shift;
  1013. my $netdev=get_record_sql($db,'SELECT * FROM devices WHERE ip="'.$ip.'"');
  1014. if ($netdev and $netdev->{id}>0) { return $netdev; }
  1015. my $auth_rec=get_record_sql($db,'SELECT user_id FROM User_auth WHERE ip="'.$ip.'" and deleted=0');
  1016. if ($auth_rec and $auth_rec->{user_id}>0) {
  1017. $netdev=get_record_sql($db,'SELECT * FROM devices WHERE user_id='.$auth_rec->{user_id});
  1018. return $netdev;
  1019. }
  1020. return;
  1021. }
  1022. #---------------------------------------------------------------------------------------------------------------
  1023. sub GetUnixTimeByStr {
  1024. my $time_str = shift;
  1025. $time_str =~s/\//-/g;
  1026. $time_str = trim($time_str);
  1027. my ($sec,$min,$hour,$day,$mon,$year) = (localtime())[0,1,2,3,4,5];
  1028. $year+=1900;
  1029. $mon++;
  1030. if ($time_str =~/^([0-9]{2,4})\-([0-9]{1,2})-([0-9]{1,2})\s+/) {
  1031. $year = $1; $mon = $2; $day = $3;
  1032. }
  1033. if ($time_str =~/([0-9]{1,2})\:([0-9]{1,2})\:([0-9]{1,2})$/) {
  1034. $hour = $1; $min = $2; $sec = $3;
  1035. }
  1036. my $result = mktime($sec,$min,$hour,$day,$mon-1,$year-1900);
  1037. return $result;
  1038. }
  1039. #---------------------------------------------------------------------------------------------------------------
  1040. sub GetTimeStrByUnixTime {
  1041. my $time = shift || time();
  1042. my ($sec, $min, $hour, $mday, $mon, $year) = (localtime($time))[0,1,2,3,4,5];
  1043. my $result = strftime("%Y-%m-%d %H:%M:%S",$sec, $min, $hour, $mday, $mon, $year);
  1044. return $result;
  1045. }
  1046. #---------------------------------------------------------------------------------------------------------------
  1047. sub Set_Variable {
  1048. my $db = shift;
  1049. my $name = shift || $MY_NAME;
  1050. my $value = shift || $$;
  1051. my $timeshift = shift || 60;
  1052. Del_Variable($db,$name);
  1053. my $clean_variables = time() + $timeshift;
  1054. my ($sec,$min,$hour,$day,$month,$year,$zone) = localtime($clean_variables);
  1055. $month++;
  1056. $year += 1900;
  1057. my $clean_str=sprintf "%04d-%02d-%02d %02d:%02d:%02d",$year,$month,$day,$hour,$min,$sec;
  1058. my $clean_variables_date=$db->quote($clean_str);
  1059. do_sql($db,"INSERT INTO variables(name,value,clear_time) VALUES('".$name."','".$value."',".$clean_variables_date.");");
  1060. }
  1061. #---------------------------------------------------------------------------------------------------------------
  1062. sub Get_Variable {
  1063. my $db = shift;
  1064. my $name = shift || $MY_NAME;
  1065. my $variable=get_record_sql($db,'SELECT `value` FROM `variables` WHERE name="'.$name.'"');
  1066. if (!$variable and $variable->{'value'}) { return $variable->{'value'}; }
  1067. return;
  1068. }
  1069. #---------------------------------------------------------------------------------------------------------------
  1070. sub Del_Variable {
  1071. my $db = shift;
  1072. my $name = shift || $MY_NAME;
  1073. do_sql($db,"DELETE FROM `variables` WHERE name='".$name."';");
  1074. }
  1075. #---------------------------------------------------------------------------------------------------------------
  1076. sub recalc_quotes {
  1077. my $db = shift;
  1078. my $calc_id = shift || $$;
  1079. return if (!get_option($db,54));
  1080. clean_variables($db);
  1081. return if (Get_Variable($db,'RECALC'));
  1082. my $timeshift = get_option($db,55);
  1083. if ($timeshift >5 ) { $timeshift=$timeshift-1; }
  1084. Set_Variable($db,'RECALC',$calc_id,time()+$timeshift*60);
  1085. my $now = DateTime->now(time_zone=>'local');
  1086. my $day_start = $db->quote($now->ymd("-")." 00:00:00");
  1087. my $day_dur = DateTime::Duration->new( days => 1 );
  1088. my $tomorrow = $now+$day_dur;
  1089. my $day_stop = $db->quote($tomorrow->ymd("-")." 00:00:00");
  1090. $now->set(day=>1);
  1091. my $month_start=$db->quote($now->ymd("-")." 00:00:00");
  1092. my $month_dur = DateTime::Duration->new( months => 1 );
  1093. my $next_month = $now + $month_dur;
  1094. $next_month->set(day=>1);
  1095. my $month_stop = $db->quote($next_month->ymd("-")." 00:00:00");
  1096. #get user limits
  1097. 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";
  1098. my @authlist_ref = get_records_sql($db,$user_auth_list_sql);
  1099. my %user_stats;
  1100. my %auth_info;
  1101. foreach my $row (@authlist_ref) {
  1102. $auth_info{$row->{auth_id}}{user_id}=$row->{id};
  1103. $auth_info{$row->{auth_id}}{day_limit}=$row->{auth_day};
  1104. $auth_info{$row->{auth_id}}{month_limit}=$row->{auth_month};
  1105. $auth_info{$row->{auth_id}}{day}=0;
  1106. $auth_info{$row->{auth_id}}{month}=0;
  1107. $user_stats{$row->{id}}{day_limit}=$row->{day_quota};
  1108. $user_stats{$row->{id}}{month_limit}=$row->{month_quota};
  1109. $user_stats{$row->{id}}{day}=0;
  1110. $user_stats{$row->{id}}{month}=0;
  1111. }
  1112. #recalc quotes - global
  1113. #day
  1114. my $day_sql="SELECT User_stats.auth_id, SUM( byte_in + byte_out ) AS traf_all FROM User_stats
  1115. WHERE User_stats.`timestamp`>= $day_start AND User_stats.`timestamp`< $day_stop GROUP BY User_stats.auth_id";
  1116. my @day_stats = get_records_sql($db,$day_sql);
  1117. foreach my $row (@day_stats) {
  1118. my $user_id=$auth_info{$row->{auth_id}}{user_id};
  1119. $auth_info{$row->{auth_id}}{day}=$row->{traf_all};
  1120. $user_stats{$user_id}{day}+=$row->{traf_all};
  1121. }
  1122. #month
  1123. my $month_sql="SELECT User_stats.auth_id, SUM( byte_in + byte_out ) AS traf_all FROM User_stats
  1124. WHERE User_stats.`timestamp`>= $month_start AND User_stats.`timestamp`< $month_stop GROUP BY User_stats.auth_id";
  1125. my @month_stats = get_records_sql($db,$month_sql);
  1126. foreach my $row (@month_stats) {
  1127. my $user_id=$auth_info{$row->{auth_id}}{user_id};
  1128. $auth_info{$row->{auth_id}}{month}=$row->{traf_all};
  1129. $user_stats{$user_id}{month}+=$row->{traf_all};
  1130. }
  1131. foreach my $auth_id (keys %auth_info) {
  1132. next if (!$auth_info{$auth_id}{day_limit});
  1133. next if (!$auth_info{$auth_id}{month_limit});
  1134. my $day_limit=$auth_info{$auth_id}{day_limit}*$KB*$KB;
  1135. my $month_limit=$auth_info{$auth_id}{month_limit}*$KB*$KB;
  1136. my $blocked_d=($auth_info{$auth_id}{day}>$day_limit);
  1137. my $blocked_m=($auth_info{$auth_id}{month}>$month_limit);
  1138. if ($blocked_d or $blocked_m) {
  1139. my $history_msg;
  1140. 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; }
  1141. 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; }
  1142. do_sql($db,"UPDATE User_auth set blocked=1, changed=1 where id=$auth_id");
  1143. db_log_verbose($db,$history_msg);
  1144. }
  1145. }
  1146. foreach my $user_id (keys %user_stats) {
  1147. next if (!$user_stats{$user_id}{day_limit});
  1148. next if (!$user_stats{$user_id}{month_limit});
  1149. my $day_limit=$user_stats{$user_id}{day_limit}*$KB*$KB;
  1150. my $month_limit=$user_stats{$user_id}{month_limit}*$KB*$KB;
  1151. my $blocked_d=($user_stats{$user_id}{day}>$day_limit);
  1152. my $blocked_m=($user_stats{$user_id}{month}>$month_limit);
  1153. if ($blocked_d or $blocked_m) {
  1154. my $history_msg;
  1155. 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; }
  1156. 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; }
  1157. do_sql($db,"UPDATE User_user set blocked=1 where id=$user_id");
  1158. do_sql($db,"UPDATE User_auth set blocked=1, changed=1 where user_id=$user_id");
  1159. db_log_verbose($db,$history_msg);
  1160. }
  1161. }
  1162. Del_Variable($db,'RECALC');
  1163. }
  1164. #---------------------------------------------------------------------------------------------------------------
  1165. sub clean_variables {
  1166. my $db = shift;
  1167. #clean temporary variables
  1168. my $clean_variables = time();
  1169. my ($sec,$min,$hour,$day,$month,$year,$zone) = localtime($clean_variables);
  1170. $month++;
  1171. $year += 1900;
  1172. my $now_str=sprintf "%04d-%02d-%02d %02d:%02d:%02d",$year,$month,$day,$hour,$min,$sec;
  1173. my $clean_variables_date=$db->quote($now_str);
  1174. do_sql($db,"DELETE FROM `variables` WHERE clear_time<=$clean_variables_date");
  1175. }
  1176. #---------------------------------------------------------------------------------------------------------------
  1177. $dbh=init_db();
  1178. init_option($dbh);
  1179. clean_variables($dbh);
  1180. Set_Variable($dbh);
  1181. 1;
  1182. }