mysql.pm 47 KB

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