mysql.pm 45 KB

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