1
0

mysql.pm 49 KB

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