mysql.pm 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484
  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. my $user_record=get_record_sql($db,"SELECT * FROM User_list WHERE id=".$new_user_id);
  900. if ($user_record) {
  901. $new_record->{ou_id}=$user_record->{ou_id};
  902. $new_record->{comments}=$user_record->{fio};
  903. $new_record->{filter_group_id}=$user_record->{filter_group_id};
  904. $new_record->{queue_id}=$user_record->{queue_id};
  905. $new_record->{enabled}="$user_record->{enabled}";
  906. update_record($db,'User_auth',$new_record,"id=$cur_auth_id");
  907. }
  908. } else { return; }
  909. return $cur_auth_id;
  910. }
  911. #---------------------------------------------------------------------------------------------------------------
  912. sub new_auth {
  913. my $db = shift;
  914. my $ip = shift;
  915. my $ip_aton=StrToIp($ip);
  916. my $record=get_record_sql($db,'SELECT id FROM User_auth WHERE `deleted`=0 AND `ip_int`='.$ip_aton);
  917. if ($record->{id}) { return $record->{id}; }
  918. #default user
  919. my $new_user_info=get_new_user_id($db,$ip,undef,undef);
  920. my $new_user_id;
  921. if ($new_user_info->{user_id}) { $new_user_id = $new_user_info->{user_id}; }
  922. if ($new_user_info->{ou_id}) { $new_user_id = new_user($db,$new_user_info); }
  923. my $user_record=get_record_sql($db,"SELECT * FROM User_list WHERE id=".$new_user_id);
  924. my $timestamp=GetNowTime();
  925. my $new_record;
  926. $new_record->{ip_int}=$ip_aton;
  927. $new_record->{ip}=$ip;
  928. $new_record->{user_id}=$new_user_id;
  929. $new_record->{save_traf}="$save_detail";
  930. $new_record->{deleted}="0";
  931. $new_record->{dhcp_action}='netflow';
  932. $new_record->{ou_id}=$user_record->{ou_id};
  933. $new_record->{filter_group_id}=$user_record->{filter_group_id};
  934. $new_record->{queue_id}=$user_record->{queue_id};
  935. $new_record->{enabled}="$user_record->{enabled}";
  936. $new_record->{comments}=$user_record->{fio};
  937. my $cur_auth_id=insert_record($db,'User_auth',$new_record);
  938. db_log_warning($db,"New ip created by netflow! ip: $ip") if ($cur_auth_id);
  939. return $cur_auth_id;
  940. }
  941. #---------------------------------------------------------------------------------------------------------------
  942. sub get_option {
  943. my $db=shift;
  944. my $option_id=shift;
  945. return if (!$option_id);
  946. return if (!$db);
  947. my $default_option = get_record_sql($db,'SELECT * FROM config_options WHERE id='.$option_id);
  948. my $config_options = get_record_sql($db,'SELECT * FROM config WHERE option_id='.$option_id);
  949. my $result;
  950. if (!$config_options) {
  951. if ($default_option->{'type'}=~/int/i or $default_option->{'type'}=~/bool/i) {
  952. $result = $default_option->{'default_value'}*1;
  953. } else {
  954. $result = $default_option->{'default_value'};
  955. }
  956. return $result;
  957. }
  958. $result = $config_options->{'value'};
  959. return $result;
  960. }
  961. #---------------------------------------------------------------------------------------------------------------
  962. sub init_option {
  963. my $db=shift;
  964. $last_refresh_config = time();
  965. $config_ref{dbh}=$db;
  966. $config_ref{save_detail}=get_option($db,23);
  967. $config_ref{add_unknown_user}=get_option($db,22);
  968. $config_ref{dns_server}=get_option($db,3);
  969. $config_ref{dhcp_server}=get_option($db,5);
  970. $config_ref{snmp_default_version}=get_option($db,9);
  971. $config_ref{snmp_default_community}=get_option($db,11);
  972. $config_ref{KB}=get_option($db,1);
  973. if ($config_ref{KB} ==0) { $config_ref{KB}=1000; }
  974. if ($config_ref{KB} ==1) { $config_ref{KB}=1024; }
  975. $config_ref{admin_email}=get_option($db,21);
  976. $config_ref{sender_email}=get_option($db,52);
  977. $config_ref{send_email}=get_option($db,51);
  978. $config_ref{history}=get_option($db,26);
  979. $config_ref{history_dhcp}=get_option($db,27);
  980. $config_ref{router_login}=get_option($db,28);
  981. $config_ref{router_password}=get_option($db,29);
  982. $config_ref{router_port}=get_option($db,30);
  983. $config_ref{org_name}=get_option($db,32);
  984. $config_ref{domain_name}=get_option($db,33);
  985. $config_ref{connections_history}=get_option($db,35);
  986. $config_ref{debug}=get_option($db,34);
  987. $config_ref{log_level} = get_option($db,53);
  988. if ($config_ref{debug}) { $config_ref{log_level} = 255; }
  989. $config_ref{urgent_sync}=get_option($db,50);
  990. $config_ref{ignore_hotspot_dhcp_log} = get_option($db,44);
  991. $config_ref{ignore_update_dhcp_event} = get_option($db,45);
  992. $config_ref{update_hostname_from_dhcp} = get_option($db,46);
  993. $config_ref{history_log_day}=get_option($db,47);
  994. $config_ref{history_syslog_day} = get_option($db,48);
  995. $config_ref{history_trafstat_day} = get_option($db,49);
  996. $config_ref{enable_quotes} = get_option($db,54);
  997. $config_ref{netflow_step} = get_option($db,55);
  998. $config_ref{traffic_ipstat_history} = get_option($db,56);
  999. $config_ref{nagios_url} = get_option($db,57);
  1000. $config_ref{cacti_url} = get_option($db,58);
  1001. $config_ref{torrus_url} = get_option($db,59);
  1002. $config_ref{wiki_url} = get_option($db,60);
  1003. $config_ref{stat_url} = get_option($db,62);
  1004. $config_ref{wiki_path} = get_option($db,61);
  1005. $config_ref{auto_mac_rule} = get_option($db,64);
  1006. #network configuration mode
  1007. $config_ref{config_mode}=get_option($db,68);
  1008. #auto clean old user record
  1009. $config_ref{clean_empty_user}=get_option($db,69);
  1010. #$save_detail = 1; id=23
  1011. $save_detail=get_option($db,23);
  1012. #$add_unknown_user = 1; id=22
  1013. $add_unknown_user=get_option($db,22);
  1014. #$dns_server='192.168.2.12'; id=3
  1015. $dns_server=get_option($db,3);
  1016. #$dhcp_server='192.168.2.12'; id=5
  1017. $dhcp_server=get_option($db,5);
  1018. #$snmp_default_version='2'; id=9
  1019. $snmp_default_version=get_option($db,9);
  1020. #$snmp_default_community='public'; id=11
  1021. $snmp_default_community=get_option($db,11);
  1022. #$KB=1024; id=1
  1023. $KB=$config_ref{KB};
  1024. #$admin_email; id=21
  1025. $admin_email=get_option($db,21);
  1026. #sender email
  1027. $sender_email=get_option($db,52);
  1028. #send email
  1029. $send_email=get_option($db,51);
  1030. #$history=15; id=26
  1031. $history=get_option($db,26);
  1032. #$history_dhcp=7; id=27
  1033. $history_dhcp=get_option($db,27);
  1034. #$router_login="admin"; id=28
  1035. $router_login=get_option($db,28);
  1036. #$router_password="admin"; id=29
  1037. $router_password=get_option($db,29);
  1038. #$router_port=23; id=30
  1039. $router_port=get_option($db,30);
  1040. #32
  1041. $org_name=get_option($db,32);
  1042. #33
  1043. $domain_name=get_option($db,33);
  1044. #35
  1045. $connections_history=get_option($db,35);
  1046. #debug
  1047. $debug=get_option($db,34);
  1048. #log level
  1049. $log_level = get_option($db,53);
  1050. if ($debug) { $log_level = 255; }
  1051. #urgent sync access
  1052. $urgent_sync=get_option($db,50);
  1053. $ignore_hotspot_dhcp_log = get_option($db,44);
  1054. $ignore_update_dhcp_event = get_option($db,45);
  1055. $update_hostname_from_dhcp = get_option($db,46);
  1056. $history_log_day=get_option($db,47);
  1057. $history_syslog_day = get_option($db,48);
  1058. $history_trafstat_day = get_option($db,49);
  1059. my $ou = get_record_sql($db,"SELECT id FROM OU WHERE default_users = 1");
  1060. if (!$ou) { $default_user_ou_id = 0; } else { $default_user_ou_id = $ou->{'id'}; }
  1061. $ou = get_record_sql($db,"SELECT id FROM OU WHERE default_hotspot = 1");
  1062. if (!$ou) { $default_hotspot_ou_id = $default_user_ou_id; } else { $default_hotspot_ou_id = $ou->{'id'}; }
  1063. @subnets=get_records_sql($db,'SELECT * FROM subnets ORDER BY ip_int_start');
  1064. if (defined $office_networks) { undef $office_networks; }
  1065. if (defined $free_networks) { undef $free_networks; }
  1066. if (defined $vpn_networks) { undef $vpn_networks; }
  1067. if (defined $hotspot_networks) { undef $hotspot_networks; }
  1068. if (defined $all_networks) { undef $all_networks; }
  1069. $office_networks = new Net::Patricia;
  1070. $free_networks = new Net::Patricia;
  1071. $vpn_networks = new Net::Patricia;
  1072. $hotspot_networks = new Net::Patricia;
  1073. $all_networks = new Net::Patricia;
  1074. @office_network_list=();
  1075. @free_network_list=();
  1076. @free_network_list=();
  1077. @vpn_network_list=();
  1078. @hotspot_network_list=();
  1079. @all_network_list=();
  1080. foreach my $net (@subnets) {
  1081. next if (!$net->{subnet});
  1082. $subnets_ref{$net->{subnet}}=$net;
  1083. if ($net->{office}) {
  1084. push(@office_network_list,$net->{subnet});
  1085. $office_networks->add_string($net->{subnet},$net);
  1086. }
  1087. if ($net->{free}) {
  1088. push(@free_network_list,$net->{subnet});
  1089. $free_networks->add_string($net->{subnet},$net);
  1090. }
  1091. if ($net->{vpn}) {
  1092. push(@vpn_network_list,$net->{subnet});
  1093. $vpn_networks->add_string($net->{subnet},$net);
  1094. }
  1095. if ($net->{hotspot}) {
  1096. push(@hotspot_network_list,$net->{subnet});
  1097. push(@all_network_list,$net->{subnet});
  1098. $hotspot_networks->add_string($net->{subnet},$net);
  1099. }
  1100. push(@all_network_list,$net->{subnet});
  1101. $all_networks->add_string($net->{subnet},$net);
  1102. }
  1103. }
  1104. #---------------------------------------------------------------------------------------------------------------
  1105. sub get_subnets_ref {
  1106. my $db = shift;
  1107. my @list=get_records_sql($db,'SELECT * FROM subnets ORDER BY ip_int_start');
  1108. my $list_ref;
  1109. foreach my $net (@list) {
  1110. next if (!$net->{subnet});
  1111. $list_ref->{$net->{subnet}}=$net;
  1112. }
  1113. return $list_ref;
  1114. }
  1115. #---------------------------------------------------------------------------------------------------------------
  1116. sub get_device_by_ip {
  1117. my $db = shift;
  1118. my $ip = shift;
  1119. my $netdev=get_record_sql($db,'SELECT * FROM devices WHERE ip="'.$ip.'"');
  1120. if ($netdev and $netdev->{id}>0) { return $netdev; }
  1121. my $auth_rec=get_record_sql($db,'SELECT user_id FROM User_auth WHERE ip="'.$ip.'" and deleted=0');
  1122. if ($auth_rec and $auth_rec->{user_id}>0) {
  1123. $netdev=get_record_sql($db,'SELECT * FROM devices WHERE user_id='.$auth_rec->{user_id});
  1124. return $netdev;
  1125. }
  1126. return;
  1127. }
  1128. #---------------------------------------------------------------------------------------------------------------
  1129. sub GetUnixTimeByStr {
  1130. my $time_str = shift;
  1131. $time_str =~s/\//-/g;
  1132. $time_str = trim($time_str);
  1133. my ($sec,$min,$hour,$day,$mon,$year) = (localtime())[0,1,2,3,4,5];
  1134. $year+=1900;
  1135. $mon++;
  1136. if ($time_str =~/^([0-9]{2,4})\-([0-9]{1,2})-([0-9]{1,2})\s+/) {
  1137. $year = $1; $mon = $2; $day = $3;
  1138. }
  1139. if ($time_str =~/([0-9]{1,2})\:([0-9]{1,2})\:([0-9]{1,2})$/) {
  1140. $hour = $1; $min = $2; $sec = $3;
  1141. }
  1142. my $result = mktime($sec,$min,$hour,$day,$mon-1,$year-1900);
  1143. return $result;
  1144. }
  1145. #---------------------------------------------------------------------------------------------------------------
  1146. sub GetTimeStrByUnixTime {
  1147. my $time = shift || time();
  1148. my ($sec, $min, $hour, $mday, $mon, $year) = (localtime($time))[0,1,2,3,4,5];
  1149. my $result = strftime("%Y-%m-%d %H:%M:%S",$sec, $min, $hour, $mday, $mon, $year);
  1150. return $result;
  1151. }
  1152. #---------------------------------------------------------------------------------------------------------------
  1153. sub Set_Variable {
  1154. my $db = shift;
  1155. my $name = shift || $MY_NAME;
  1156. my $value = shift || $$;
  1157. my $timeshift = shift || 60;
  1158. Del_Variable($db,$name);
  1159. my $clean_variables = time() + $timeshift;
  1160. my ($sec,$min,$hour,$day,$month,$year,$zone) = localtime($clean_variables);
  1161. $month++;
  1162. $year += 1900;
  1163. my $clean_str=sprintf "%04d-%02d-%02d %02d:%02d:%02d",$year,$month,$day,$hour,$min,$sec;
  1164. my $clean_variables_date=$db->quote($clean_str);
  1165. do_sql($db,"INSERT INTO variables(name,value,clear_time) VALUES('".$name."','".$value."',".$clean_variables_date.");");
  1166. }
  1167. #---------------------------------------------------------------------------------------------------------------
  1168. sub Get_Variable {
  1169. my $db = shift;
  1170. my $name = shift || $MY_NAME;
  1171. my $variable=get_record_sql($db,'SELECT `value` FROM `variables` WHERE name="'.$name.'"');
  1172. if (!$variable and $variable->{'value'}) { return $variable->{'value'}; }
  1173. return;
  1174. }
  1175. #---------------------------------------------------------------------------------------------------------------
  1176. sub Del_Variable {
  1177. my $db = shift;
  1178. my $name = shift || $MY_NAME;
  1179. do_sql($db,"DELETE FROM `variables` WHERE name='".$name."';");
  1180. }
  1181. #---------------------------------------------------------------------------------------------------------------
  1182. sub recalc_quotes {
  1183. my $db = shift;
  1184. my $calc_id = shift || $$;
  1185. return if (!get_option($db,54));
  1186. clean_variables($db);
  1187. return if (Get_Variable($db,'RECALC'));
  1188. my $timeshift = get_option($db,55);
  1189. if ($timeshift >5 ) { $timeshift=$timeshift-1; }
  1190. Set_Variable($db,'RECALC',$calc_id,time()+$timeshift*60);
  1191. my $now = DateTime->now(time_zone=>'local');
  1192. my $day_start = $db->quote($now->ymd("-")." 00:00:00");
  1193. my $day_dur = DateTime::Duration->new( days => 1 );
  1194. my $tomorrow = $now+$day_dur;
  1195. my $day_stop = $db->quote($tomorrow->ymd("-")." 00:00:00");
  1196. $now->set(day=>1);
  1197. my $month_start=$db->quote($now->ymd("-")." 00:00:00");
  1198. my $month_dur = DateTime::Duration->new( months => 1 );
  1199. my $next_month = $now + $month_dur;
  1200. $next_month->set(day=>1);
  1201. my $month_stop = $db->quote($next_month->ymd("-")." 00:00:00");
  1202. #get user limits
  1203. 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";
  1204. my @authlist_ref = get_records_sql($db,$user_auth_list_sql);
  1205. my %user_stats;
  1206. my %auth_info;
  1207. foreach my $row (@authlist_ref) {
  1208. $auth_info{$row->{auth_id}}{user_id}=$row->{id};
  1209. $auth_info{$row->{auth_id}}{day_limit}=$row->{auth_day};
  1210. $auth_info{$row->{auth_id}}{month_limit}=$row->{auth_month};
  1211. $auth_info{$row->{auth_id}}{day}=0;
  1212. $auth_info{$row->{auth_id}}{month}=0;
  1213. $user_stats{$row->{id}}{day_limit}=$row->{day_quota};
  1214. $user_stats{$row->{id}}{month_limit}=$row->{month_quota};
  1215. $user_stats{$row->{id}}{day}=0;
  1216. $user_stats{$row->{id}}{month}=0;
  1217. }
  1218. #recalc quotes - global
  1219. #day
  1220. my $day_sql="SELECT User_stats.auth_id, SUM( byte_in + byte_out ) AS traf_all FROM User_stats
  1221. WHERE User_stats.`timestamp`>= $day_start AND User_stats.`timestamp`< $day_stop GROUP BY User_stats.auth_id";
  1222. my @day_stats = get_records_sql($db,$day_sql);
  1223. foreach my $row (@day_stats) {
  1224. my $user_id=$auth_info{$row->{auth_id}}{user_id};
  1225. $auth_info{$row->{auth_id}}{day}=$row->{traf_all};
  1226. $user_stats{$user_id}{day}+=$row->{traf_all};
  1227. }
  1228. #month
  1229. my $month_sql="SELECT User_stats.auth_id, SUM( byte_in + byte_out ) AS traf_all FROM User_stats
  1230. WHERE User_stats.`timestamp`>= $month_start AND User_stats.`timestamp`< $month_stop GROUP BY User_stats.auth_id";
  1231. my @month_stats = get_records_sql($db,$month_sql);
  1232. foreach my $row (@month_stats) {
  1233. my $user_id=$auth_info{$row->{auth_id}}{user_id};
  1234. $auth_info{$row->{auth_id}}{month}=$row->{traf_all};
  1235. $user_stats{$user_id}{month}+=$row->{traf_all};
  1236. }
  1237. foreach my $auth_id (keys %auth_info) {
  1238. next if (!$auth_info{$auth_id}{day_limit});
  1239. next if (!$auth_info{$auth_id}{month_limit});
  1240. my $day_limit=$auth_info{$auth_id}{day_limit}*$KB*$KB;
  1241. my $month_limit=$auth_info{$auth_id}{month_limit}*$KB*$KB;
  1242. my $blocked_d=($auth_info{$auth_id}{day}>$day_limit);
  1243. my $blocked_m=($auth_info{$auth_id}{month}>$month_limit);
  1244. if ($blocked_d or $blocked_m) {
  1245. my $history_msg;
  1246. 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; }
  1247. 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; }
  1248. do_sql($db,"UPDATE User_auth set blocked=1, changed=1 where id=$auth_id");
  1249. db_log_verbose($db,$history_msg);
  1250. }
  1251. }
  1252. foreach my $user_id (keys %user_stats) {
  1253. next if (!$user_stats{$user_id}{day_limit});
  1254. next if (!$user_stats{$user_id}{month_limit});
  1255. my $day_limit=$user_stats{$user_id}{day_limit}*$KB*$KB;
  1256. my $month_limit=$user_stats{$user_id}{month_limit}*$KB*$KB;
  1257. my $blocked_d=($user_stats{$user_id}{day}>$day_limit);
  1258. my $blocked_m=($user_stats{$user_id}{month}>$month_limit);
  1259. if ($blocked_d or $blocked_m) {
  1260. my $history_msg;
  1261. 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; }
  1262. 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; }
  1263. do_sql($db,"UPDATE User_user set blocked=1 where id=$user_id");
  1264. do_sql($db,"UPDATE User_auth set blocked=1, changed=1 where user_id=$user_id");
  1265. db_log_verbose($db,$history_msg);
  1266. }
  1267. }
  1268. Del_Variable($db,'RECALC');
  1269. }
  1270. #---------------------------------------------------------------------------------------------------------------
  1271. sub clean_variables {
  1272. my $db = shift;
  1273. #clean temporary variables
  1274. my $clean_variables = time();
  1275. my ($sec,$min,$hour,$day,$month,$year,$zone) = localtime($clean_variables);
  1276. $month++;
  1277. $year += 1900;
  1278. my $now_str=sprintf "%04d-%02d-%02d %02d:%02d:%02d",$year,$month,$day,$hour,$min,$sec;
  1279. my $clean_variables_date=$db->quote($now_str);
  1280. do_sql($db,"DELETE FROM `variables` WHERE clear_time<=$clean_variables_date");
  1281. }
  1282. #---------------------------------------------------------------------------------------------------------------
  1283. $dbh=init_db();
  1284. init_option($dbh);
  1285. clean_variables($dbh);
  1286. Set_Variable($dbh);
  1287. 1;
  1288. }