mysql.pm 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973
  1. package eyelib::mysql;
  2. #
  3. # Copyright (C) Roman Dmitiriev, rnd@rajven.ru
  4. #
  5. use utf8;
  6. use open ":encoding(utf8)";
  7. use strict;
  8. use English;
  9. use FindBin '$Bin';
  10. use lib "/opt/Eye/scripts";
  11. use base 'Exporter';
  12. use vars qw(@EXPORT @ISA);
  13. use eyelib::config;
  14. use eyelib::main;
  15. use Net::Patricia;
  16. use eyelib::net_utils;
  17. use Data::Dumper;
  18. use DateTime;
  19. use POSIX;
  20. use DBI;
  21. our @ISA = qw(Exporter);
  22. our @EXPORT = qw(
  23. batch_db_sql
  24. batch_db_sql_cached
  25. db_log_warning
  26. db_log_debug
  27. db_log_error
  28. db_log_info
  29. db_log_verbose
  30. delete_record
  31. do_sql
  32. Get_Variable
  33. Set_Variable
  34. Del_Variable
  35. get_count_records
  36. get_record_sql
  37. get_records_sql
  38. get_device_by_ip
  39. get_diff_rec
  40. get_id_record
  41. get_new_user_id
  42. is_hotspot
  43. GetNowTime
  44. GetUnixTimeByStr
  45. GetTimeStrByUnixTime
  46. get_option
  47. get_subnets_ref
  48. init_db
  49. init_option
  50. insert_record
  51. apply_device_lock
  52. set_lock_discovery
  53. unset_lock_discovery
  54. IpToStr
  55. unbind_ports
  56. resurrection_auth
  57. new_auth
  58. StrToIp
  59. get_first_line
  60. update_dns_record
  61. update_dns_record_by_dhcp
  62. create_dns_cname
  63. delete_dns_cname
  64. create_dns_hostname
  65. delete_dns_hostname
  66. create_dns_ptr
  67. delete_dns_ptr
  68. update_record
  69. write_db_log
  70. set_changed
  71. recalc_quotes
  72. clean_variables
  73. $add_rules
  74. $L_WARNING
  75. $L_INFO
  76. $L_DEBUG
  77. $L_ERROR
  78. $L_VERBOSE
  79. );
  80. BEGIN
  81. {
  82. #---------------------------------------------------------------------------------------------------------------
  83. our $add_rules;
  84. our $L_ERROR = 0;
  85. our $L_WARNING = 1;
  86. our $L_INFO = 2;
  87. our $L_VERBOSE = 3;
  88. our $L_DEBUG = 255;
  89. our %acl_fields = (
  90. 'ip' => '1',
  91. 'ip_int' => '1',
  92. 'enabled'=>'1',
  93. 'dhcp'=>'1',
  94. 'filter_group_id'=>'1',
  95. 'deleted'=>'1',
  96. 'dhcp_acl'=>'1',
  97. 'queue_id'=>'1',
  98. 'mac'=>'1',
  99. 'blocked'=>'1'
  100. );
  101. our %dhcp_fields = (
  102. 'ip' => '1',
  103. 'dhcp'=>'1',
  104. 'deleted'=>'1',
  105. 'mac'=>'1',
  106. );
  107. our %dns_fields = (
  108. 'ip' => '1',
  109. 'dns_name'=>'1',
  110. 'alias'=>'1',
  111. );
  112. #---------------------------------------------------------------------------------------------------------------
  113. sub StrToIp{
  114. return unpack('N',pack('C4',split(/\./,$_[0])));
  115. }
  116. #---------------------------------------------------------------------------------------------------------------
  117. sub IpToStr{
  118. my $nIP = shift;
  119. my $res = (($nIP>>24) & 255) .".". (($nIP>>16) & 255) .".". (($nIP>>8) & 255) .".". ($nIP & 255);
  120. return $res;
  121. }
  122. #---------------------------------------------------------------------------------------------------------------
  123. sub batch_db_sql {
  124. my $db=shift;
  125. my $batch_sql=shift;
  126. return if (!$db);
  127. $db->{AutoCommit} = 0;
  128. my $apply = 0;
  129. my $sth;
  130. my @msg = ();
  131. if (ref($batch_sql) eq 'ARRAY') { @msg = @$batch_sql; } else { @msg = split("\n",$batch_sql); }
  132. foreach my $sSQL (@msg) {
  133. next if (!$sSQL);
  134. $sth = $db->prepare($sSQL) or die "Unable to prepare $sSQL" . $db->errstr;
  135. $sth->execute() or die "Unable to prepare $sSQL" . $db->errstr;
  136. $apply = 1;
  137. }
  138. if ($apply) { $sth->finish(); }
  139. $db->{AutoCommit} = 1;
  140. }
  141. #---------------------------------------------------------------------------------------------------------------
  142. sub batch_db_sql_cached {
  143. my $db = DBI->connect("dbi:mysql:database=$DBNAME;host=$DBHOST","$DBUSER","$DBPASS", { RaiseError => 0, AutoCommit => 0 });
  144. if ( !defined $db ) { die "Cannot connect to mySQL server: $DBI::errstr\n"; }
  145. $db->do('SET NAMES utf8mb4');
  146. $db->{'mysql_enable_utf8'} = 1;
  147. $db->{'mysql_auto_reconnect'} = 1;
  148. my $table= shift;
  149. my $batch_sql=shift;
  150. return if (!$db);
  151. my @msg = ();
  152. if (ref($batch_sql) eq 'ARRAY') { @msg = @$batch_sql; } else { @msg = split("\n",$batch_sql); }
  153. my $sth = $db->prepare_cached($table) or die "Unable to prepare:" . $db->errstr;
  154. foreach my $sSQL (@msg) {
  155. next if (!$sSQL);
  156. $sth->execute(@$sSQL) or die "Unable to execute:" . $db->errstr;
  157. }
  158. $db->commit();
  159. $db->disconnect();
  160. }
  161. #---------------------------------------------------------------------------------------------------------------
  162. sub do_sql {
  163. my $db=shift;
  164. my $sql=shift;
  165. return if (!$db);
  166. return if (!$sql);
  167. if ($sql!~/^select /i) { log_debug($sql); }
  168. my $sql_prep = $db->prepare($sql) or die "Unable to prepare $sql: " . $db->errstr;
  169. my $sql_ref;
  170. my $rv = $sql_prep->execute() or die "Unable to execute $sql: " . $db->errstr;
  171. if ($sql=~/^insert/i) { $sql_ref = $sql_prep->{mysql_insertid}; }
  172. if ($sql=~/^select /i) { $sql_ref = $sql_prep->fetchall_arrayref() or die "Unable to select $sql: " . $db->errstr; };
  173. $sql_prep->finish();
  174. return $sql_ref;
  175. }
  176. #---------------------------------------------------------------------------------------------------------------
  177. sub get_first_line {
  178. my $msg = shift;
  179. if (!$msg) { return; }
  180. if ($msg=~ /(.*)(\n|\<br\>)/) {
  181. $msg = $1 if ($1);
  182. chomp($msg);
  183. }
  184. return $msg;
  185. }
  186. #---------------------------------------------------------------------------------------------------------------
  187. sub write_db_log {
  188. my $db=shift;
  189. my $msg=shift;
  190. my $level = shift || $L_VERBOSE;
  191. my $auth_id = shift || 0;
  192. return if (!$db);
  193. return if (!$msg);
  194. $msg=~s/[\'\"]//g;
  195. my $db_log = 0;
  196. if (!$db) { $db_log = 0; }
  197. if ($level eq $L_ERROR and $log_level >= $L_ERROR) { log_error($msg); $db_log = 1; }
  198. if ($level eq $L_WARNING and $log_level >= $L_WARNING) { log_warning($msg); $db_log = 1; }
  199. if ($level eq $L_INFO and $log_level >= $L_INFO) { log_info($msg); $db_log = 1; }
  200. if ($level eq $L_DEBUG and $log_level >= $L_DEBUG) { log_debug($msg); $db_log = 1; }
  201. if ($db_log) {
  202. my $history_sql="INSERT INTO worklog(customer,message,level,auth_id) VALUES(".$db->quote($MY_NAME).",".$db->quote($msg).",$level,$auth_id)";
  203. my $history_rf=$db->prepare($history_sql) or die "Unable to prepare $history_sql:" . $db->errstr;
  204. $history_rf->execute() or die "Unable to execute $history_sql: " . $db->errstr;
  205. }
  206. }
  207. #---------------------------------------------------------------------------------------------------------------
  208. sub db_log_debug {
  209. my $db = shift;
  210. my $msg = shift;
  211. my $id = shift;
  212. if ($debug) { write_db_log($db,$msg,$L_DEBUG,$id); }
  213. }
  214. #---------------------------------------------------------------------------------------------------------------
  215. sub db_log_error {
  216. my $db = shift;
  217. my $msg = shift;
  218. if ($log_level >= $L_ERROR) {
  219. sendEmail("ERROR! ".get_first_line($msg),$msg,1);
  220. write_db_log($db,$msg,$L_ERROR);
  221. }
  222. }
  223. #---------------------------------------------------------------------------------------------------------------
  224. sub db_log_info {
  225. my $db = shift;
  226. my $msg = shift;
  227. my $id = shift;
  228. if ($log_level >= $L_INFO) { write_db_log($db,$msg,$L_INFO,$id); }
  229. }
  230. #---------------------------------------------------------------------------------------------------------------
  231. sub db_log_verbose {
  232. my $db = shift;
  233. my $msg = shift;
  234. my $id = shift;
  235. if ($log_level >= $L_VERBOSE) { write_db_log($db,$msg,$L_VERBOSE,$id); }
  236. }
  237. #---------------------------------------------------------------------------------------------------------------
  238. sub db_log_warning {
  239. my $db = shift;
  240. my $msg = shift;
  241. my $id = shift;
  242. if ($log_level >= $L_WARNING) {
  243. sendEmail("WARN! ".get_first_line($msg),$msg,1);
  244. write_db_log($db,$msg,$L_WARNING,$id);
  245. }
  246. }
  247. #---------------------------------------------------------------------------------------------------------------
  248. sub init_db {
  249. # Create new database handle. If we can't connect, die()
  250. my $db = DBI->connect("dbi:mysql:database=$DBNAME;host=$DBHOST","$DBUSER","$DBPASS", { RaiseError => 0, AutoCommit => 1 });
  251. if ( !defined $db ) { die "Cannot connect to mySQL server: $DBI::errstr\n"; }
  252. $db->do('SET NAMES utf8mb4');
  253. $db->{'mysql_enable_utf8'} = 1;
  254. $db->{'mysql_auto_reconnect'} = 1;
  255. return $db;
  256. }
  257. #---------------------------------------------------------------------------------------------------------------
  258. sub get_count_records {
  259. my $db = shift;
  260. my $table = shift;
  261. my $filter = shift;
  262. my $result = 0;
  263. return $result if (!$db);
  264. return $result if (!$table);
  265. my $sSQL='SELECT COUNT(*) as rec_cnt FROM '.$table;
  266. if ($filter) { $sSQL=$sSQL." WHERE ".$filter; }
  267. my $record = get_record_sql($db,$sSQL);
  268. if ($record->{rec_cnt}) { $result = $record->{rec_cnt}; }
  269. return $result;
  270. }
  271. #---------------------------------------------------------------------------------------------------------------
  272. sub get_id_record {
  273. my $db = shift;
  274. my $table = shift;
  275. my $filter = shift;
  276. my $result = 0;
  277. return $result if (!$db);
  278. return $result if (!$table);
  279. my $record = get_record_sql($db,"SELECT id FROM $table WHERE $filter");
  280. if ($record->{id}) { $result = $record->{id}; }
  281. return $result;
  282. }
  283. #---------------------------------------------------------------------------------------------------------------
  284. sub get_records_sql {
  285. my $db = shift;
  286. my $table = shift;
  287. my @result;
  288. return @result if (!$db);
  289. return @result if (!$table);
  290. my $list = $db->prepare( $table ) or die "Unable to prepare $table:" . $db->errstr;
  291. $list->execute() or die "Unable to execute $table: " . $db->errstr;
  292. while(my $row_ref = $list->fetchrow_hashref()) { push(@result,$row_ref); }
  293. $list->finish();
  294. return @result;
  295. }
  296. #---------------------------------------------------------------------------------------------------------------
  297. sub get_record_sql {
  298. my $db = shift;
  299. my $tsql = shift;
  300. my @result;
  301. return @result if (!$db);
  302. return @result if (!$tsql);
  303. $tsql.=' LIMIT 1';
  304. my $row_ref;
  305. eval {
  306. my $list = $db->prepare($tsql) or die "Unable to prepare $tsql: " . $db->errstr;
  307. $list->execute() or die "Unable to execute $tsql: " . $db->errstr;
  308. $row_ref = $list->fetchrow_hashref();
  309. $list->finish();
  310. };
  311. if ($@) {
  312. log_error("Error apply sql: $tsql err:".$@);
  313. die "Error apply sql: $tsql";
  314. }
  315. return $row_ref;
  316. }
  317. #---------------------------------------------------------------------------------------------------------------
  318. sub unbind_ports {
  319. my $db = shift;
  320. my $device_id = shift;
  321. return if (!$db);
  322. return if (!$device_id);
  323. my @target = get_records_sql($db, "SELECT U.target_port_id,U.id FROM device_ports U WHERE U.device_id=".$device_id);
  324. foreach my $row (@target) {
  325. do_sql($db, "UPDATE device_ports SET target_port_id=0 WHERE target_port_id=".$row->{id});
  326. do_sql($db, "UPDATE device_ports SET target_port_id=0 WHERE id=".$row->{id});
  327. }
  328. }
  329. #---------------------------------------------------------------------------------------------------------------
  330. sub get_diff_rec {
  331. my $db = shift;
  332. my $table = shift;
  333. my $value = shift;
  334. my $filter = shift;
  335. return if (!$db);
  336. return if (!$table);
  337. return if (!$filter);
  338. my $old_value = get_record_sql($db,"SELECT * FROM $table WHERE $filter");
  339. my $result='';
  340. foreach my $field (keys %$value) {
  341. if (!$value->{$field}) { $value->{$field}=''; }
  342. if (!$old_value->{$field}) { $old_value->{$field}=''; }
  343. if ($value->{$field}!~/^$old_value->{$field}$/) { $result = $result." $field => $value->{$field} (old: $old_value->{$field}),"; }
  344. }
  345. $result=~s/,$//;
  346. return $result;
  347. }
  348. #---------------------------------------------------------------------------------------------------------------
  349. sub get_dns_name {
  350. my $db = shift;
  351. my $id = shift;
  352. my $auth_record = get_record_sql($db,"SELECT dns_name FROM User_auth WHERE deleted=0 AND id=".$id);
  353. if ($auth_record and $auth_record->{'dns_name'}) { return $auth_record->{'dns_name'}; }
  354. return;
  355. }
  356. #---------------------------------------------------------------------------------------------------------------
  357. sub update_record {
  358. my $db = shift;
  359. my $table = shift;
  360. my $record = shift;
  361. my $filter = shift;
  362. return if (!$db);
  363. return if (!$table);
  364. return if (!$filter);
  365. my $old_record = get_record_sql($db,"SELECT * FROM $table WHERE $filter");
  366. my $diff='';
  367. my $change_str='';
  368. my $found_changed=0;
  369. my $rec_id = 0;
  370. my $dns_changed = 0;
  371. $rec_id = $old_record->{'id'} if ($old_record->{'id'});
  372. if ($table eq "User_auth") {
  373. foreach my $field (keys %$record) {
  374. if (exists $acl_fields{$field}) { $record->{changed}="1"; }
  375. if (exists $dhcp_fields{$field}) { $record->{dhcp_changed}="1"; }
  376. if (exists $dns_fields{$field}) { $dns_changed=1; }
  377. }
  378. }
  379. foreach my $field (keys %$record) {
  380. if (!defined $record->{$field}) { $record->{$field}=''; }
  381. if (!defined $old_record->{$field}) { $old_record->{$field}=''; }
  382. my $old_value = quotemeta($old_record->{$field});
  383. my $new_value = $record->{$field};
  384. $new_value=~s/\'//g;
  385. $new_value=~s/\"//g;
  386. if ($new_value!~/^$old_value$/) {
  387. $diff = $diff." $field => $record->{$field} (old: $old_record->{$field}),";
  388. $change_str = $change_str." `$field`=".$db->quote($record->{$field}).",";
  389. $found_changed++;
  390. }
  391. }
  392. if ($found_changed) {
  393. $change_str=~s/\,$//;
  394. $diff=~s/\,$//;
  395. if ($table eq 'User_auth') {
  396. $change_str .= ", `changed_time`='".GetNowTime()."'";
  397. if ($dns_changed) {
  398. my $del_dns;
  399. if ($old_record->{'dns_name'} and $old_record->{'ip'}) {
  400. $del_dns->{'name_type'}='A';
  401. $del_dns->{'name'}=$old_record->{'dns_name'};
  402. $del_dns->{'value'}=$old_record->{'ip'};
  403. $del_dns->{'type'}='del';
  404. if ($rec_id) { $del_dns->{'auth_id'}=$rec_id; }
  405. insert_record($db,'dns_queue',$del_dns);
  406. }
  407. my $new_dns;
  408. my $dns_rec_ip = $old_record->{ip};
  409. my $dns_rec_name = $old_record->{dns_name};
  410. if ($record->{'dns_name'}) { $dns_rec_name = $record->{'dns_name'}; }
  411. if ($record->{'ip'}) { $dns_rec_ip = $record->{'ip'}; }
  412. if ($dns_rec_name and $dns_rec_ip) {
  413. $new_dns->{'name_type'}='A';
  414. $new_dns->{'name'}=$dns_rec_name;
  415. $new_dns->{'value'}=$dns_rec_ip;
  416. $new_dns->{'type'}='add';
  417. if ($rec_id) { $new_dns->{'auth_id'}=$rec_id; }
  418. insert_record($db,'dns_queue',$new_dns);
  419. }
  420. }
  421. }
  422. if ($table eq 'User_auth_alias') {
  423. if ($dns_changed) {
  424. my $del_dns;
  425. if ($old_record->{'alias'}) {
  426. $del_dns->{'name_type'}='CNAME';
  427. $del_dns->{'name'}=$old_record->{'alias'};
  428. $del_dns->{'type'}='del';
  429. $del_dns->{'value'}=get_dns_name($db,$old_record->{auth_id});
  430. $del_dns->{'auth_id'}=$old_record->{auth_id};
  431. insert_record($db,'dns_queue',$del_dns);
  432. }
  433. my $new_dns;
  434. my $dns_rec_name = $old_record->{alias};
  435. if ($record->{'alias'}) { $dns_rec_name = $record->{'alias'}; }
  436. if ($dns_rec_name) {
  437. $new_dns->{'name_type'}='CNAME';
  438. $new_dns->{'name'}=$dns_rec_name;
  439. $new_dns->{'type'}='add';
  440. $new_dns->{'value'}=get_dns_name($db,$old_record->{auth_id});
  441. $new_dns->{'auth_id'}=$rec_id;
  442. insert_record($db,'dns_queue',$new_dns);
  443. }
  444. }
  445. }
  446. my $sSQL = "UPDATE $table SET $change_str WHERE $filter";
  447. db_log_debug($db,'Change table '.$table.' for '.$filter.' set: '.$diff, $rec_id);
  448. do_sql($db,$sSQL);
  449. } else {
  450. db_log_debug($db,'Nothing change. Skip update.');
  451. }
  452. return 1;
  453. }
  454. #---------------------------------------------------------------------------------------------------------------
  455. sub insert_record {
  456. my $db = shift;
  457. my $table = shift;
  458. my $record = shift;
  459. return if (!$db);
  460. return if (!$table);
  461. my $change_str='';
  462. my $fields='';
  463. my $values='';
  464. my $new_str='';
  465. my $dns_changed = 0;
  466. if ($table eq "User_auth") {
  467. foreach my $field (keys %$record) {
  468. if (exists $acl_fields{$field}) { $record->{changed}="1"; }
  469. if (exists $dhcp_fields{$field}) { $record->{dhcp_changed}="1"; }
  470. if (exists $dns_fields{$field}) { $dns_changed=1; }
  471. }
  472. }
  473. foreach my $field (keys %$record) {
  474. if (!defined $record->{$field}) { $record->{$field}=''; }
  475. my $new_value = $record->{$field};
  476. $new_value=~s/\'//g;
  477. $new_value=~s/\"//g;
  478. $record->{$field} = $new_value;
  479. $fields = $fields."`$field`,";
  480. $values = $values." ".$db->quote($record->{$field}).",";
  481. $new_str = $new_str." $field => $record->{$field},";
  482. }
  483. $fields=~s/,$//;
  484. $values=~s/,$//;
  485. $new_str=~s/,$//;
  486. my $sSQL = "INSERT INTO $table($fields) VALUES($values)";
  487. my $result = do_sql($db,$sSQL);
  488. if ($result) {
  489. $new_str='id: '.$result.' '.$new_str;
  490. if ($table eq 'User_auth_alias' and $dns_changed) {
  491. if ($record->{'alias'}) {
  492. my $add_dns;
  493. $add_dns->{'name_type'}='CNAME';
  494. $add_dns->{'name'}=$record->{'alias'};
  495. $add_dns->{'value'}=get_dns_name($db,$record->{'auth_id'});
  496. $add_dns->{'type'}='add';
  497. $add_dns->{'auth_id'}=$record->{'auth_id'};
  498. insert_record($db,'dns_queue',$add_dns);
  499. }
  500. }
  501. if ($table eq 'User_auth' and $dns_changed) {
  502. if ($record->{'dns_name'} and $record->{'ip'} and $dns_changed) {
  503. my $add_dns;
  504. $add_dns->{'name_type'}='A';
  505. $add_dns->{'name'}=$record->{'dns_name'};
  506. $add_dns->{'value'}=$record->{'ip'};
  507. $add_dns->{'type'}='add';
  508. $add_dns->{'auth_id'}=$result;
  509. insert_record($db,'dns_queue',$add_dns);
  510. }
  511. }
  512. }
  513. db_log_debug($db,'Add record to table '.$table.' '.$new_str);
  514. return $result;
  515. }
  516. #---------------------------------------------------------------------------------------------------------------
  517. sub delete_record {
  518. my $db = shift;
  519. my $table = shift;
  520. my $filter = shift;
  521. return if (!$db);
  522. return if (!$table);
  523. return if (!$filter);
  524. my $old_record = get_record_sql($db,"SELECT * FROM $table WHERE $filter");
  525. my $diff='';
  526. foreach my $field (keys %$old_record) {
  527. if (!$old_record->{$field}) { $old_record->{$field}=''; }
  528. $diff = $diff." $field => $old_record->{$field},";
  529. }
  530. $diff=~s/,$//;
  531. db_log_debug($db,'Delete record from table '.$table.' value: '.$diff);
  532. #never delete user ip record!
  533. if ($table eq 'User_auth') {
  534. my $sSQL = "UPDATE User_auth SET changed=1, deleted=1, changed_time='".GetNowTime()."' WHERE ".$filter;
  535. do_sql($db,$sSQL);
  536. if ($old_record->{'dns_name'} and $old_record->{'ip'}) {
  537. my $del_dns;
  538. $del_dns->{'name_type'}='A';
  539. $del_dns->{'name'}=$old_record->{'dns_name'};
  540. $del_dns->{'value'}=$old_record->{'ip'};
  541. $del_dns->{'type'}='del';
  542. $del_dns->{'auth_id'}=$old_record->{'id'};
  543. insert_record($db,'dns_queue',$del_dns);
  544. }
  545. }
  546. if ($table eq 'User_auth_alias') {
  547. if ($old_record->{'alias'} and $old_record->{'auth_id'}) {
  548. my $del_dns;
  549. $del_dns->{'name_type'}='CNAME';
  550. $del_dns->{'name'}=$old_record->{'alias'};
  551. $del_dns->{'value'}=get_dns_name($db,$old_record->{'auth_id'});
  552. $del_dns->{'type'}='del';
  553. $del_dns->{'auth_id'}=$old_record->{'auth_id'};
  554. insert_record($db,'dns_queue',$del_dns);
  555. }
  556. }
  557. my $sSQL = "DELETE FROM ".$table." WHERE ".$filter;
  558. return do_sql($db,$sSQL);
  559. }
  560. #---------------------------------------------------------------------------------------------------------------
  561. sub GetNowTime {
  562. my ($sec,$min,$hour,$day,$month,$year,$zone) = localtime(time());
  563. $month += 1;
  564. $year += 1900;
  565. my $now_str=sprintf "%04d-%02d-%02d %02d:%02d:%02d",$year,$month,$day,$hour,$min,$sec;
  566. return $now_str;
  567. }
  568. #---------------------------------------------------------------------------------------------------------------
  569. sub is_hotspot {
  570. my $db = shift;
  571. my $ip = shift;
  572. my $users = new Net::Patricia;
  573. #check hotspot
  574. my @ip_rules = get_records_sql($db,'SELECT * FROM subnets WHERE hotspot=1 AND LENGTH(subnet)>0');
  575. foreach my $row (@ip_rules) { $users->add_string($row->{subnet}); }
  576. if ($users->match_string($ip)) { return 1; }
  577. return 0;
  578. }
  579. #---------------------------------------------------------------------------------------------------------------
  580. sub get_new_user_id {
  581. my $db = shift;
  582. my $ip = shift;
  583. my $mac = shift;
  584. my $hostname = shift;
  585. my $result;
  586. #check user rules
  587. $mac = mac_simplify($mac);
  588. $result->{ip} = $ip;
  589. $result->{mac} = mac_splitted($mac);
  590. $result->{dhcp_hostname} = $hostname;
  591. $result->{ou_id}=undef;
  592. $result->{user_id}=undef;
  593. #check ip
  594. if (defined $ip and $ip) {
  595. my $users = new Net::Patricia;
  596. #check ip rules
  597. my @ip_rules = get_records_sql($db,'SELECT * FROM auth_rules WHERE type=1 and LENGTH(rule)>0 AND user_id IS NOT NULL');
  598. foreach my $row (@ip_rules) { eval { $users->add_string($row->{rule},$row->{user_id}); }; }
  599. if ($users->match_string($ip)) { $result->{user_id}=$users->match_string($ip); }
  600. }
  601. #check mac
  602. if (defined $mac and $mac) {
  603. my @user_rules=get_records_sql($db,'SELECT * FROM auth_rules WHERE type=2 AND LENGTH(rule)>0 AND user_id IS NOT NULL');
  604. foreach my $user (@user_rules) {
  605. my $rule = mac_simplify($user->{rule});
  606. if ($mac=~/$rule/i) { $result->{user_id}=$user->{user_id}; }
  607. }
  608. }
  609. #check hostname
  610. if (defined $hostname and $hostname) {
  611. my @user_rules=get_records_sql($db,'SELECT * FROM auth_rules WHERE type=3 AND LENGTH(rule)>0 AND user_id IS NOT NULL');
  612. foreach my $user (@user_rules) {
  613. if ($hostname=~/$user->{rule}/i) { $result->{user_id}=$user->{user_id}; }
  614. }
  615. }
  616. #
  617. if ($result->{user_id}) { return $result; }
  618. #check ou rules
  619. #check ip
  620. if (defined $ip and $ip) {
  621. my $users = new Net::Patricia;
  622. #check hotspot
  623. my @ip_rules = get_records_sql($db,'SELECT * FROM subnets WHERE hotspot=1 AND LENGTH(subnet)>0');
  624. foreach my $row (@ip_rules) { $users->add_string($row->{subnet},$default_hotspot_ou_id); }
  625. if ($users->match_string($ip)) { $result->{ou_id}=$users->match_string($ip); }
  626. #check ip rules
  627. @ip_rules = get_records_sql($db,'SELECT * FROM auth_rules WHERE type=1 and LENGTH(rule)>0 AND ou_id IS NOT NULL');
  628. foreach my $row (@ip_rules) { eval { $users->add_string($row->{rule},$row->{ou_id}); }; }
  629. if ($users->match_string($ip)) { $result->{ou_id}=$users->match_string($ip); }
  630. }
  631. #check mac
  632. if (defined $mac and $mac) {
  633. my @user_rules=get_records_sql($db,'SELECT * FROM auth_rules WHERE type=2 AND LENGTH(rule)>0 AND ou_id IS NOT NULL');
  634. foreach my $user (@user_rules) {
  635. my $rule = mac_simplify($user->{rule});
  636. if ($mac=~/$rule/i) { $result->{ou_id}=$user->{ou_id}; }
  637. }
  638. }
  639. #check hostname
  640. if (defined $hostname and $hostname) {
  641. my @user_rules=get_records_sql($db,'SELECT * FROM auth_rules WHERE type=3 AND LENGTH(rule)>0 AND ou_id IS NOT NULL');
  642. foreach my $user (@user_rules) {
  643. if ($hostname=~/$user->{rule}/i) { $result->{ou_id}=$user->{ou_id}; }
  644. }
  645. }
  646. if (!$result->{ou_id}) { $result->{ou_id}=$default_user_ou_id; }
  647. return $result;
  648. }
  649. #---------------------------------------------------------------------------------------------------------------
  650. sub set_changed {
  651. my $db = shift;
  652. my $id = shift;
  653. return if (!$db or !$id);
  654. my $update_record;
  655. $update_record->{changed}=1;
  656. update_record($db,'User_auth',$update_record,"id=$id");
  657. }
  658. #---------------------------------------------------------------------------------------------------------------
  659. sub update_dns_record {
  660. my $hdb = shift;
  661. my $auth_id = shift;
  662. return if (!$config_ref{enable_dns_updates});
  663. #get domain
  664. my $ad_zone = get_option($hdb,33);
  665. #get dns server
  666. my $ad_dns = get_option($hdb,3);
  667. my $enable_ad_dns_update = ($ad_zone and $ad_dns and $config_ref{enable_dns_updates});
  668. log_debug("Auth id: ".$auth_id);
  669. log_debug("enable_ad_dns_update: ".$enable_ad_dns_update);
  670. log_debug("DNS update flags - zone: ".$ad_zone.", dns: ".$ad_dns.", enable_ad_dns_update: ".$enable_ad_dns_update);
  671. my @dns_queue = get_records_sql($hdb,"SELECT * FROM dns_queue WHERE auth_id=".$auth_id." ORDER BY id ASC");
  672. if (!@dns_queue or !scalar @dns_queue) { return; }
  673. foreach my $dns_cmd (@dns_queue) {
  674. my $fqdn = '';
  675. my $fqdn_ip = '';
  676. my $fqdn_parent = '';
  677. my $static_exists = 0;
  678. my $static_ref = '';
  679. my $static_ok = 0;
  680. eval {
  681. if ($dns_cmd->{name_type}=~/^cname$/i) {
  682. $fqdn=lc($dns_cmd->{name});
  683. $fqdn=~s/\.$ad_zone$//i;
  684. $fqdn=~s/\.$//;
  685. if ($dns_cmd->{value}) {
  686. $fqdn_parent=lc($dns_cmd->{value});
  687. $fqdn_parent=~s/\.$ad_zone$//i;
  688. $fqdn_parent=~s/\.$//;
  689. }
  690. #skip update unknown domain
  691. if ($fqdn =~/\./ or $fqdn_parent =~/\./) { next; }
  692. $fqdn = $fqdn.".".$ad_zone;
  693. $fqdn_parent = $fqdn_parent.".".$ad_zone;
  694. #remove cname
  695. if ($dns_cmd->{type} eq 'del') {
  696. delete_dns_cname($fqdn_parent,$fqdn,$ad_zone,$ad_dns,$hdb);
  697. }
  698. #create cname
  699. if ($dns_cmd->{type} eq 'add') {
  700. create_dns_cname($fqdn_parent,$fqdn,$ad_zone,$ad_dns,$hdb);
  701. }
  702. }
  703. if ($dns_cmd->{name_type}=~/^a$/i) {
  704. $fqdn=lc($dns_cmd->{name});
  705. $fqdn=~s/\.$ad_zone$//i;
  706. $fqdn=~s/\.$//;
  707. if (!$dns_cmd->{value}) { next; }
  708. $fqdn_ip=lc($dns_cmd->{value});
  709. #skip update unknown domain
  710. if ($fqdn =~/\./) { next; }
  711. $fqdn = $fqdn.".".$ad_zone;
  712. #dns update disabled?
  713. my $maybe_update_dns=( $enable_ad_dns_update and $office_networks->match_string($fqdn_ip) );
  714. if (!$maybe_update_dns) {
  715. db_log_info($hdb,"FOUND Auth_id: $auth_id. DNS update disabled.");
  716. next;
  717. }
  718. #get aliases
  719. my @aliases = get_records_sql($hdb,"SELECT * FROM User_auth_alias WHERE auth_id=".$auth_id);
  720. #remove A & PTR
  721. if ($dns_cmd->{type} eq 'del') {
  722. #remove aliases
  723. if (@aliases and scalar @aliases) {
  724. foreach my $alias (@aliases) {
  725. delete_dns_cname($fqdn,$alias->{alias},$ad_zone,$ad_dns,$hdb) if ($alias->{alias});
  726. delete_dns_hostname($fqdn,$alias->{alias},$ad_zone,$ad_dns,$hdb) if ($alias->{alias});
  727. }
  728. }
  729. #remove main record
  730. delete_dns_hostname($fqdn,$fqdn_ip,$ad_zone,$ad_dns,$hdb);
  731. delete_dns_ptr($fqdn,$fqdn_ip,$ad_zone,$ad_dns,$hdb);
  732. }
  733. #create A & PTR
  734. if ($dns_cmd->{type} eq 'add') {
  735. my @dns_record=ResolveNames($fqdn,$dns_server);
  736. $static_exists = (scalar @dns_record>0);
  737. if ($static_exists) {
  738. $static_ref = join(' ',@dns_record);
  739. foreach my $dns_a (@dns_record) {
  740. if ($dns_a=~/^$fqdn_ip$/) { $static_ok = 1; }
  741. }
  742. db_log_debug($hdb,"Dns record for static record $fqdn: $static_ref");
  743. }
  744. #skip update if already exists
  745. if ($static_ok) {
  746. db_log_debug($hdb,"Static record for $fqdn [$static_ok] correct.");
  747. next;
  748. }
  749. #create record
  750. create_dns_hostname($fqdn,$fqdn_ip,$ad_zone,$ad_dns,$hdb);
  751. create_dns_ptr($fqdn,$fqdn_ip,$ad_zone,$ad_dns,$hdb);
  752. #create aliases
  753. if (@aliases and scalar @aliases) {
  754. foreach my $alias (@aliases) {
  755. create_dns_cname($fqdn,$alias->{alias},$ad_zone,$ad_dns,$hdb) if ($alias->{alias});
  756. }
  757. }
  758. }
  759. }
  760. };
  761. if ($@) { log_error("Error dns commands: $@"); }
  762. }
  763. }
  764. #---------------------------------------------------------------------------------------------------------------
  765. sub update_dns_record_by_dhcp {
  766. my $hdb = shift;
  767. my $dhcp_record = shift;
  768. my $auth_record = shift;
  769. return if (!$config_ref{enable_dns_updates});
  770. my $ad_zone = get_option($hdb,33);
  771. my $ad_dns = get_option($hdb,3);
  772. $update_hostname_from_dhcp = get_option($hdb,46) || 0;
  773. my $subnets_dhcp = get_subnets_ref($hdb);
  774. my $enable_ad_dns_update = ($ad_zone and $ad_dns and $update_hostname_from_dhcp);
  775. log_debug("Dhcp record: ".Dumper($dhcp_record));
  776. log_debug("Subnets: ".Dumper($subnets_dhcp->{$dhcp_record->{network}->{subnet}}));
  777. log_debug("enable_ad_dns_update: ".$enable_ad_dns_update);
  778. 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);
  779. 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});
  780. if (!$maybe_update_dns) {
  781. db_log_debug($hdb,"FOUND Auth_id: $auth_record->{id}. DNS update don't needed.");
  782. return 0;
  783. }
  784. log_debug("DNS update enabled.");
  785. #update dns block
  786. my $fqdn_static;
  787. if ($auth_record->{dns_name}) {
  788. $fqdn_static=lc($auth_record->{dns_name});
  789. if ($fqdn_static!~/\.$ad_zone$/i) {
  790. $fqdn_static=~s/\.$//;
  791. $fqdn_static=lc($fqdn_static.'.'.$ad_zone);
  792. }
  793. }
  794. my $fqdn=lc(trim($dhcp_record->{hostname_utf8}));
  795. if ($fqdn!~/\.$ad_zone$/i) {
  796. $fqdn=~s/\.$//;
  797. $fqdn=lc($fqdn.'.'.$ad_zone);
  798. }
  799. db_log_debug($hdb,"FOUND Auth_id: $auth_record->{id} dns_name: $fqdn_static dhcp_hostname: $fqdn");
  800. #check exists static dns name
  801. my $static_exists = 0;
  802. my $dynamic_exists = 0;
  803. my $static_ok = 0;
  804. my $dynamic_ok = 0;
  805. my $static_ref;
  806. my $dynamic_ref;
  807. if ($fqdn_static ne '') {
  808. my @dns_record=ResolveNames($fqdn_static,$dns_server);
  809. $static_exists = (scalar @dns_record>0);
  810. if ($static_exists) {
  811. $static_ref = join(' ',@dns_record);
  812. foreach my $dns_a (@dns_record) {
  813. if ($dns_a=~/^$dhcp_record->{ip}$/) { $static_ok = $dns_a; }
  814. }
  815. }
  816. } else { $static_ok = 1; }
  817. if ($fqdn ne '') {
  818. my @dns_record=ResolveNames($fqdn,$dns_server);
  819. $dynamic_exists = (scalar @dns_record>0);
  820. if ($dynamic_exists) {
  821. $dynamic_ref = join(' ',@dns_record);
  822. foreach my $dns_a (@dns_record) {
  823. if ($dns_a=~/^$dhcp_record->{ip}$/) { $dynamic_ok = $dns_a; }
  824. }
  825. }
  826. }
  827. db_log_debug($hdb,"Dns record for static record $fqdn_static: $static_ok");
  828. db_log_debug($hdb,"Dns record for dhcp-hostname $fqdn: $dynamic_ok");
  829. if ($fqdn_static ne '') {
  830. if (!$static_ok) {
  831. db_log_info($hdb,"Static record mismatch! Expected $fqdn_static => $dhcp_record->{ip}, recivied: $static_ref");
  832. if (!$static_exists) {
  833. db_log_info($hdb,"Static dns hostname defined but not found. Create it ($fqdn_static => $dhcp_record->{ip})!");
  834. create_dns_hostname($fqdn_static,$dhcp_record->{ip},$ad_zone,$ad_dns,$hdb);
  835. }
  836. } else {
  837. db_log_debug($hdb,"Static record for $fqdn_static [$static_ok] correct.");
  838. }
  839. }
  840. if ($fqdn ne '' and $dynamic_ok ne '') { db_log_debug($hdb,"Dynamic record for $fqdn [$dynamic_ok] correct. No changes required."); }
  841. if ($fqdn ne '' and !$dynamic_ok) {
  842. #log event without email alert
  843. log_error("Dynamic record mismatch! Expected: $fqdn => $dhcp_record->{ip}, recivied: $dynamic_ref. Checking the status.");
  844. #check exists hostname
  845. my $another_hostname_exists = 0;
  846. my $hostname_filter = ' LOWER(dns_name) REGEXP("^'.lc($dhcp_record->{hostname_utf8}).'\.*$")';
  847. if ($fqdn_static ne '' and $fqdn !~/$fqdn_static/) {
  848. $hostname_filter = $hostname_filter . ' or LOWER(dns_name) REGEXP("^'.lc($auth_record->{dns_name}).'\.*$")';
  849. }
  850. #check exists another records with some static hostname
  851. my $filter_sql = 'SELECT * FROM User_auth WHERE id<>'.$auth_record->{id}.' and deleted=0 and ('.$hostname_filter.') ORDER BY last_found DESC';
  852. db_log_debug($hdb,"Search dhcp hostname by: ".$filter_sql);
  853. my $name_record = get_record_sql($hdb,$filter_sql);
  854. if ($name_record->{dns_name} =~/^$fqdn$/i or $name_record->{dns_name} =~/^$dhcp_record->{hostname_utf8}$/i) {
  855. $another_hostname_exists = 1;
  856. }
  857. if (!$another_hostname_exists) {
  858. if ($fqdn_static and $fqdn_static ne '') {
  859. if ($fqdn_static!~/$fqdn/) {
  860. db_log_info($hdb,"Hostname from dhcp request $fqdn differs from static dns hostname $fqdn_static. Ignore dynamic binding!");
  861. # delete_dns_hostname($fqdn,$dhcp_record->{ip},$ad_zone,$ad_dns,$hdb);
  862. # create_dns_hostname($fqdn,$dhcp_record->{ip},$ad_zone,$ad_dns,$hdb);
  863. }
  864. } else {
  865. db_log_info($hdb,"Rewrite aliases if exists for $fqdn => $dhcp_record->{ip}");
  866. #get and remove aliases
  867. my @aliases = get_records_sql($hdb,"SELECT * FROM User_auth_alias WHERE auth_id=".$auth_record->{id});
  868. if (@aliases and scalar @aliases) {
  869. foreach my $alias (@aliases) {
  870. delete_dns_cname($fqdn_static,$alias->{alias},$ad_zone,$ad_dns,$hdb) if ($alias->{alias});
  871. }
  872. }
  873. db_log_info($hdb,"Static dns hostname not defined. Create dns record by dhcp request. $fqdn => $dhcp_record->{ip}");
  874. create_dns_hostname($fqdn,$dhcp_record->{ip},$ad_zone,$ad_dns,$hdb);
  875. if (@aliases and scalar @aliases) {
  876. foreach my $alias (@aliases) {
  877. create_dns_cname($fqdn_static,$alias->{alias},$ad_zone,$ad_dns,$hdb) if ($alias->{alias});
  878. }
  879. }
  880. }
  881. } else {
  882. 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.");
  883. }
  884. }
  885. #end update dns block
  886. }
  887. #------------------------------------------------------------------------------------------------------------
  888. sub apply_device_lock {
  889. my $db = shift;
  890. my $device_id = shift;
  891. my $iteration = shift || 0;
  892. $iteration++;
  893. if ($iteration>2) { return 0; }
  894. 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);
  895. if (!$dev) { return 0; }
  896. if (!$dev->{'discovery_locked'}) { return set_lock_discovery($db,$device_id); }
  897. #if timestamp undefined, set and return
  898. if (!$dev->{'locked_timestamp'}) { return set_lock_discovery($db,$device_id); }
  899. #wait for discovery
  900. my $wait_time = $dev->{'locked_timestamp'} + 30 - time();
  901. if ($wait_time<0) { return set_lock_discovery($db,$device_id); }
  902. sleep($wait_time);
  903. return apply_device_lock($db,$device_id,$iteration);
  904. }
  905. #------------------------------------------------------------------------------------------------------------
  906. sub set_lock_discovery {
  907. my $db = shift;
  908. my $device_id = shift;
  909. my $new;
  910. $new->{'discovery_locked'} = 1;
  911. $new->{'locked_timestamp'} = GetNowTime();
  912. if (update_record($db,'devices',$new,'id='.$device_id)) { return 1; }
  913. return 0;
  914. }
  915. #------------------------------------------------------------------------------------------------------------
  916. sub unset_lock_discovery {
  917. my $db = shift;
  918. my $device_id = shift;
  919. my $new;
  920. $new->{'discovery_locked'} = 0;
  921. $new->{'locked_timestamp'} = GetNowTime();
  922. if (update_record($db,'devices',$new,'id='.$device_id)) { return 1; }
  923. return 0;
  924. }
  925. #------------------------------------------------------------------------------------------------------------
  926. sub create_dns_cname {
  927. my $fqdn = shift;
  928. my $alias = shift;
  929. my $zone = shift;
  930. my $server = shift;
  931. my $db = shift;
  932. #skip update domain controllers
  933. if (!$db) {
  934. log_info("DNS-UPDATE: Zone $zone Server: $server CNAME: $alias for $fqdn");
  935. } else {
  936. db_log_info($db,"DNS-UPDATE: Zone $zone Server: $server CNAME: $alias for $fqdn ");
  937. }
  938. my $ad_zone = get_option($db,33);
  939. my $nsupdate_file = "/tmp/".$fqdn."-nsupdate";
  940. my @add_dns;
  941. if ($config_ref{dns_server_type}=~/windows/i) {
  942. push(@add_dns,"gsstsig");
  943. push(@add_dns,"server $server");
  944. push(@add_dns,"zone $zone");
  945. push(@add_dns,"update add $alias 3600 cname $fqdn.");
  946. push(@add_dns,"send");
  947. write_to_file($nsupdate_file,\@add_dns);
  948. do_exec('/usr/bin/kinit -k -t /opt/Eye/scripts/cfg/dns_updater.keytab dns_updater@'.uc($ad_zone).' && /usr/bin/nsupdate "'.$nsupdate_file.'"');
  949. }
  950. if ($config_ref{dns_server_type}=~/bind/i) {
  951. push(@add_dns,"server $server");
  952. push(@add_dns,"zone $zone");
  953. push(@add_dns,"update add $alias 3600 cname $fqdn.");
  954. push(@add_dns,"send");
  955. write_to_file($nsupdate_file,\@add_dns);
  956. do_exec('/usr/bin/nsupdate -k /etc/bind/rndc.key "'.$nsupdate_file.'"');
  957. }
  958. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  959. }
  960. #---------------------------------------------------------------------------------------------------------------
  961. sub delete_dns_cname {
  962. my $fqdn = shift;
  963. my $alias = shift;
  964. my $zone = shift;
  965. my $server = shift;
  966. my $db = shift;
  967. if (!$db) {
  968. log_info("DNS-UPDATE: Delete => Zone $zone Server: $server CNAME: $alias for $fqdn ");
  969. } else {
  970. db_log_info($db,"DNS-UPDATE: Delete => Zone $zone Server: $server CNAME: $alias for $fqdn");
  971. }
  972. my $ad_zone = get_option($db,33);
  973. my $nsupdate_file = "/tmp/".$fqdn."-nsupdate";
  974. my @add_dns;
  975. if ($config_ref{dns_server_type}=~/windows/i) {
  976. push(@add_dns,"gsstsig");
  977. push(@add_dns,"server $server");
  978. push(@add_dns,"zone $zone");
  979. push(@add_dns,"update delete $alias cname ");
  980. push(@add_dns,"send");
  981. write_to_file($nsupdate_file,\@add_dns);
  982. do_exec('/usr/bin/kinit -k -t /opt/Eye/scripts/cfg/dns_updater.keytab dns_updater@'.uc($ad_zone).' && /usr/bin/nsupdate "'.$nsupdate_file.'"');
  983. }
  984. if ($config_ref{dns_server_type}=~/bind/i) {
  985. push(@add_dns,"server $server");
  986. push(@add_dns,"zone $zone");
  987. push(@add_dns,"update delete $alias cname");
  988. push(@add_dns,"send");
  989. write_to_file($nsupdate_file,\@add_dns);
  990. do_exec('/usr/bin/nsupdate -k /etc/bind/rndc.key "'.$nsupdate_file.'"');
  991. }
  992. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  993. }
  994. #------------------------------------------------------------------------------------------------------------
  995. sub create_dns_hostname {
  996. my $fqdn = shift;
  997. my $ip = shift;
  998. my $zone = shift;
  999. my $server = shift;
  1000. my $db = shift;
  1001. #skip update domain controllers
  1002. if ($fqdn=~/^dc[0-9]{1,2}\./i) { return; }
  1003. if (!$db) {
  1004. log_info("DNS-UPDATE: Zone $zone Server: $server A: $fqdn IP: $ip");
  1005. } else {
  1006. db_log_info($db,"DNS-UPDATE: Zone $zone Server: $server A: $fqdn IP: $ip");
  1007. }
  1008. my $ad_zone = get_option($db,33);
  1009. my $nsupdate_file = "/tmp/".$fqdn."-nsupdate";
  1010. my @add_dns;
  1011. if ($config_ref{dns_server_type}=~/windows/i) {
  1012. push(@add_dns,"gsstsig");
  1013. push(@add_dns,"server $server");
  1014. push(@add_dns,"zone $zone");
  1015. push(@add_dns,"update add $fqdn 3600 A $ip");
  1016. push(@add_dns,"send");
  1017. write_to_file($nsupdate_file,\@add_dns);
  1018. do_exec('/usr/bin/kinit -k -t /opt/Eye/scripts/cfg/dns_updater.keytab dns_updater@'.uc($ad_zone).' && /usr/bin/nsupdate "'.$nsupdate_file.'"');
  1019. }
  1020. if ($config_ref{dns_server_type}=~/bind/i) {
  1021. push(@add_dns,"server $server");
  1022. push(@add_dns,"zone $zone");
  1023. push(@add_dns,"update add $fqdn 3600 A $ip");
  1024. push(@add_dns,"send");
  1025. write_to_file($nsupdate_file,\@add_dns);
  1026. do_exec('/usr/bin/nsupdate -k /etc/bind/rndc.key "'.$nsupdate_file.'"');
  1027. }
  1028. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  1029. }
  1030. #---------------------------------------------------------------------------------------------------------------
  1031. sub delete_dns_hostname {
  1032. my $fqdn = shift;
  1033. my $ip = shift;
  1034. my $zone = shift;
  1035. my $server = shift;
  1036. my $db = shift;
  1037. #skip update domain controllers
  1038. if ($fqdn=~/^dc[0-9]{1,2}\./i) { return; }
  1039. if (!$db) {
  1040. log_info("DNS-UPDATE: Delete => Zone $zone Server: $server A: $fqdn IP: $ip");
  1041. } else {
  1042. db_log_info($db,"DNS-UPDATE: Delete => Zone $zone Server: $server A: $fqdn IP: $ip");
  1043. }
  1044. my $ad_zone = get_option($db,33);
  1045. my $nsupdate_file = "/tmp/".$fqdn."-nsupdate";
  1046. my @add_dns;
  1047. if ($config_ref{dns_server_type}=~/windows/i) {
  1048. push(@add_dns,"gsstsig");
  1049. push(@add_dns,"server $server");
  1050. push(@add_dns,"zone $zone");
  1051. push(@add_dns,"update delete $fqdn A");
  1052. push(@add_dns,"send");
  1053. write_to_file($nsupdate_file,\@add_dns);
  1054. do_exec('/usr/bin/kinit -k -t /opt/Eye/scripts/cfg/dns_updater.keytab dns_updater@'.uc($ad_zone).' && /usr/bin/nsupdate "'.$nsupdate_file.'"');
  1055. }
  1056. if ($config_ref{dns_server_type}=~/bind/i) {
  1057. push(@add_dns,"server $server");
  1058. push(@add_dns,"zone $zone");
  1059. push(@add_dns,"update delete $fqdn A");
  1060. push(@add_dns,"send");
  1061. write_to_file($nsupdate_file,\@add_dns);
  1062. do_exec('/usr/bin/nsupdate -k /etc/bind/rndc.key "'.$nsupdate_file.'"');
  1063. }
  1064. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  1065. }
  1066. #---------------------------------------------------------------------------------------------------------------
  1067. sub create_dns_ptr {
  1068. my $fqdn = shift;
  1069. my $ip = shift;
  1070. my $ad_zone = shift;
  1071. my $server = shift;
  1072. my $db = shift;
  1073. my $radr;
  1074. my $zone;
  1075. #skip update domain controllers
  1076. if ($fqdn=~/^dc[0-9]{1,2}\./i) { return; }
  1077. if ($ip =~ /([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})(\/[0-9]{1,2}){0,1}/) {
  1078. return 0 if($1 > 255 || $2 > 255 || $3 > 255 || $4 > 255);
  1079. $radr = "$4.$3.$2.$1.in-addr.arpa";
  1080. $zone = "$3.$2.$1.in-addr.arpa";
  1081. }
  1082. if (!$radr or !$zone) { return 0; }
  1083. if (!$db) { return 0; }
  1084. db_log_info($db,"DNS-UPDATE: Zone $zone Server: $server A: $fqdn PTR: $ip");
  1085. my $nsupdate_file = "/tmp/".$radr."-nsupdate";
  1086. my @add_dns;
  1087. if ($config_ref{dns_server_type}=~/windows/i) {
  1088. push(@add_dns,"gsstsig");
  1089. push(@add_dns,"server $server");
  1090. push(@add_dns,"zone $zone");
  1091. push(@add_dns,"update add $radr 3600 PTR $fqdn.");
  1092. push(@add_dns,"send");
  1093. write_to_file($nsupdate_file,\@add_dns);
  1094. 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.'"';
  1095. do_exec($run_cmd);
  1096. }
  1097. if ($config_ref{dns_server_type}=~/bind/i) {
  1098. push(@add_dns,"server $server");
  1099. push(@add_dns,"zone $zone");
  1100. push(@add_dns,"update add $radr 3600 PTR $fqdn.");
  1101. push(@add_dns,"send");
  1102. write_to_file($nsupdate_file,\@add_dns);
  1103. my $run_cmd = '/usr/bin/nsupdate -k /etc/bind/rndc.key "'.$nsupdate_file.'"';
  1104. do_exec($run_cmd);
  1105. }
  1106. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  1107. }
  1108. #---------------------------------------------------------------------------------------------------------------
  1109. sub delete_dns_ptr {
  1110. my $fqdn = shift;
  1111. my $ip = shift;
  1112. my $ad_zone = shift;
  1113. my $server = shift;
  1114. my $db = shift;
  1115. my $radr;
  1116. my $zone;
  1117. #skip update domain controllers
  1118. if ($fqdn=~/^dc[0-9]{1,2}\./i) { return; }
  1119. if ($ip =~ /([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})(\/[0-9]{1,2}){0,1}/) {
  1120. return 0 if($1 > 255 || $2 > 255 || $3 > 255 || $4 > 255);
  1121. $radr = "$4.$3.$2.$1.in-addr.arpa";
  1122. $zone = "$3.$2.$1.in-addr.arpa";
  1123. }
  1124. if (!$radr or !$zone) { return 0; }
  1125. if (!$db) { return 0 ; }
  1126. db_log_info($db,"DNS-UPDATE: Delete => Zone $zone Server: $server A: $fqdn PTR: $ip");
  1127. my $nsupdate_file = "/tmp/".$radr."-nsupdate";
  1128. my @add_dns;
  1129. if ($config_ref{dns_server_type}=~/windows/i) {
  1130. push(@add_dns,"gsstsig");
  1131. push(@add_dns,"server $server");
  1132. push(@add_dns,"zone $zone");
  1133. push(@add_dns,"update delete $radr PTR");
  1134. push(@add_dns,"send");
  1135. write_to_file($nsupdate_file,\@add_dns);
  1136. 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.'"';
  1137. do_exec($run_cmd);
  1138. }
  1139. if ($config_ref{dns_server_type}=~/bind/i) {
  1140. push(@add_dns,"server $server");
  1141. push(@add_dns,"zone $zone");
  1142. push(@add_dns,"update delete $radr PTR");
  1143. push(@add_dns,"send");
  1144. write_to_file($nsupdate_file,\@add_dns);
  1145. my $run_cmd = '/usr/bin/nsupdate -k /etc/bind/rndc.key "'.$nsupdate_file.'"';
  1146. do_exec($run_cmd);
  1147. }
  1148. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  1149. }
  1150. #---------------------------------------------------------------------------------------------------------------
  1151. sub new_user {
  1152. my $db = shift;
  1153. my $user_info = shift;
  1154. my $user;
  1155. if ($user_info->{mac}) {
  1156. $user->{login}=mac_splitted($user_info->{mac});
  1157. } else {
  1158. $user->{login}=$user_info->{ip};
  1159. }
  1160. if ($user_info->{dhcp_hostname}) { $user->{fio}=$user_info->{dhcp_hostname}; }
  1161. if (!$user->{fio}) { $user->{fio}=$user_info->{ip}; }
  1162. my $login_count = get_count_records($db,"User_list","(login LIKE '".$user->{login}."(%)') OR (login='".$user->{login}."')");
  1163. if ($login_count) { $login_count++; $user->{login} .="(".$login_count.")"; }
  1164. $user->{ou_id} = $user_info->{ou_id};
  1165. my $ou_info = get_record_sql($db,"SELECT * FROM OU WHERE id=".$user_info->{'ou_id'});
  1166. if ($ou_info) {
  1167. $user->{'enabled'} = $ou_info->{'enabled'};
  1168. $user->{'queue_id'} = $ou_info->{'queue_id'};
  1169. $user->{'filter_group_id'} = $ou_info->{'filter_group_id'};
  1170. }
  1171. my $result = insert_record($db,"User_list",$user);
  1172. if ($result and $config_ref{auto_mac_rule} and $user_info->{mac}) {
  1173. my $auth_rule;
  1174. $auth_rule->{user_id} = $result;
  1175. $auth_rule->{type} = 2;
  1176. $auth_rule->{rule} = mac_splitted($user_info->{mac});
  1177. insert_record($db,"auth_rules",$auth_rule);
  1178. }
  1179. return $result;
  1180. }
  1181. #---------------------------------------------------------------------------------------------------------------
  1182. sub get_ip_subnet {
  1183. my $db = shift;
  1184. my $ip = shift;
  1185. if (!$ip) { return; }
  1186. my $ip_aton = StrToIp($ip);
  1187. 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)");
  1188. return $user_subnet;
  1189. }
  1190. #---------------------------------------------------------------------------------------------------------------
  1191. sub find_mac_in_subnet {
  1192. my $db = shift;
  1193. my $ip = shift;
  1194. my $mac = shift;
  1195. if (!$ip or !$mac) { return; }
  1196. my $ip_subnet = get_ip_subnet($db, $ip);
  1197. if (!$ip_subnet) { return; }
  1198. 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");
  1199. my $auth_count = 0;
  1200. my $result;
  1201. $result->{'count'} = 0;
  1202. foreach my $row (@t_auth) {
  1203. next if (!$row);
  1204. $auth_count++;
  1205. $result->{'count'} = $auth_count;
  1206. $result->{$auth_count} = $row->{'id'};
  1207. push(@{$result->{'users_id'}}, $row->{'user_id'});
  1208. }
  1209. return $result;
  1210. }
  1211. #---------------------------------------------------------------------------------------------------------------
  1212. sub resurrection_auth {
  1213. my $db = shift;
  1214. my $ip_record = shift;
  1215. my $ip = $ip_record->{'ip'};
  1216. my $mac = $ip_record->{'mac'};
  1217. my $action = $ip_record->{'type'};
  1218. my $hostname = $ip_record->{'hostname_utf8'};
  1219. my $client_id = $ip_record->{'client-id'};
  1220. if (!exists $ip_record->{ip_aton}) { $ip_record->{ip_aton}=StrToIp($ip); }
  1221. if (!exists $ip_record->{hotspot}) { $ip_record->{hotspot}=is_hotspot($db,$ip); }
  1222. my $ip_aton=$ip_record->{ip_aton};
  1223. my $timestamp=GetNowTime();
  1224. my $record=get_record_sql($db,'SELECT * FROM User_auth WHERE `deleted`=0 AND `ip_int`='.$ip_aton.' AND `mac`="'.$mac.'"');
  1225. my $new_record;
  1226. $new_record->{last_found}=$timestamp;
  1227. if ($client_id) { $new_record->{'client-id'} = $client_id; }
  1228. #auth found?
  1229. if ($record->{user_id}) {
  1230. #update timestamp and return
  1231. if ($action!~/arp/i) {
  1232. $new_record->{dhcp_action}=$action;
  1233. $new_record->{dhcp_time}=$timestamp;
  1234. if ($hostname) { $new_record->{dhcp_hostname} = $hostname; }
  1235. update_record($db,'User_auth',$new_record,"id=$record->{id}");
  1236. } else {
  1237. update_record($db,'User_auth',$new_record,"id=$record->{id}");
  1238. }
  1239. return $record->{id};
  1240. }
  1241. my $user_subnet=$office_networks->match_string($ip);
  1242. if ($user_subnet->{static}) {
  1243. db_log_warning($db,"Unknown ip+mac found in static subnet! Abort create record for ip: $ip mac: [".$mac."]");
  1244. return 0;
  1245. }
  1246. #search changed mac
  1247. $record=get_record_sql($db,'SELECT * FROM User_auth WHERE `ip_int`='.$ip_aton." and deleted=0");
  1248. if ($record->{id}) {
  1249. #if found record with same ip but another mac
  1250. if (!$record->{mac}) {
  1251. db_log_verbose($db,"use empty auth record...");
  1252. $new_record->{mac}=$mac;
  1253. if ($action!~/arp/i) {
  1254. $new_record->{dhcp_action}=$action;
  1255. $new_record->{dhcp_time}=$timestamp;
  1256. if ($hostname) { $new_record->{dhcp_hostname} = $hostname; }
  1257. update_record($db,'User_auth',$new_record,"id=$record->{id}");
  1258. } else {
  1259. update_record($db,'User_auth',$new_record,"id=$record->{id}");
  1260. }
  1261. return $record->{id};
  1262. }
  1263. if ($record->{mac}) {
  1264. 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});
  1265. my $disable_record;
  1266. $disable_record->{deleted}="1";
  1267. update_record($db,'User_auth',$disable_record,"id=".$record->{id});
  1268. }
  1269. }
  1270. #default user
  1271. my $new_user_info=get_new_user_id($db,$ip,$mac,$hostname);
  1272. my $new_user_id;
  1273. if ($new_user_info->{user_id}) { $new_user_id = $new_user_info->{user_id}; }
  1274. if (!$new_user_id) { $new_user_id = new_user($db,$new_user_info); }
  1275. my $mac_exists=find_mac_in_subnet($db,$ip,$mac);
  1276. #disable dhcp for same mac in one ip subnet
  1277. if ($mac_exists and $mac_exists->{'count'}) { $new_record->{dhcp}=0; }
  1278. #seek old auth with same ip and mac
  1279. my $auth_exists=get_count_records($db,'User_auth',"ip_int=".$ip_aton." and mac='".$mac."'");
  1280. $new_record->{ip_int}=$ip_aton;
  1281. $new_record->{ip}=$ip;
  1282. $new_record->{mac}=$mac;
  1283. $new_record->{user_id}=$new_user_id;
  1284. $new_record->{save_traf}="$save_detail";
  1285. $new_record->{deleted}="0";
  1286. $new_record->{dhcp_action}=$action;
  1287. $new_record->{dhcp_time}=$timestamp;
  1288. if ($auth_exists) {
  1289. #found ->Resurrection old record
  1290. my $resurrection_id = get_id_record($db,'User_auth',"ip_int=".$ip_aton." and mac='".$mac."'");
  1291. if (!$ip_record->{hotspot}) { db_log_warning($db,"Resurrection auth_id: $resurrection_id with ip: $ip and mac: $mac"); }
  1292. else { db_log_info($db,"Resurrection auth_id: $resurrection_id with ip: $ip and mac: $mac"); }
  1293. update_record($db,'User_auth',$new_record,"id=$resurrection_id");
  1294. } else {
  1295. #not found ->create new record
  1296. 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"); }
  1297. insert_record($db,'User_auth',$new_record);
  1298. }
  1299. #filter and status
  1300. my $cur_auth_id=get_id_record($db,'User_auth',"ip='$ip' and mac='$mac' and deleted=0 ORDER BY last_found DESC");
  1301. if ($cur_auth_id) {
  1302. my $user_record=get_record_sql($db,"SELECT * FROM User_list WHERE id=".$new_user_id);
  1303. if ($user_record) {
  1304. $new_record->{ou_id}=$user_record->{ou_id};
  1305. $new_record->{comments}=$user_record->{fio};
  1306. $new_record->{filter_group_id}=$user_record->{filter_group_id};
  1307. $new_record->{queue_id}=$user_record->{queue_id};
  1308. $new_record->{enabled}="$user_record->{enabled}";
  1309. update_record($db,'User_auth',$new_record,"id=$cur_auth_id");
  1310. }
  1311. } else { return; }
  1312. return $cur_auth_id;
  1313. }
  1314. #---------------------------------------------------------------------------------------------------------------
  1315. sub new_auth {
  1316. my $db = shift;
  1317. my $ip = shift;
  1318. my $ip_aton=StrToIp($ip);
  1319. my $record=get_record_sql($db,'SELECT id FROM User_auth WHERE `deleted`=0 AND `ip_int`='.$ip_aton);
  1320. if ($record->{id}) { return $record->{id}; }
  1321. #default user
  1322. my $new_user_info=get_new_user_id($db,$ip,undef,undef);
  1323. my $new_user_id;
  1324. if ($new_user_info->{user_id}) { $new_user_id = $new_user_info->{user_id}; }
  1325. if ($new_user_info->{ou_id}) { $new_user_id = new_user($db,$new_user_info); }
  1326. my $user_record=get_record_sql($db,"SELECT * FROM User_list WHERE id=".$new_user_id);
  1327. my $timestamp=GetNowTime();
  1328. my $new_record;
  1329. $new_record->{ip_int}=$ip_aton;
  1330. $new_record->{ip}=$ip;
  1331. $new_record->{user_id}=$new_user_id;
  1332. $new_record->{save_traf}="$save_detail";
  1333. $new_record->{deleted}="0";
  1334. $new_record->{dhcp_action}='netflow';
  1335. $new_record->{ou_id}=$user_record->{ou_id};
  1336. $new_record->{filter_group_id}=$user_record->{filter_group_id};
  1337. $new_record->{queue_id}=$user_record->{queue_id};
  1338. $new_record->{enabled}="$user_record->{enabled}";
  1339. if ($user_record->{fio}) { $new_record->{comments}=$user_record->{fio}; }
  1340. my $cur_auth_id=insert_record($db,'User_auth',$new_record);
  1341. db_log_warning($db,"New ip created by netflow! ip: $ip") if ($cur_auth_id);
  1342. return $cur_auth_id;
  1343. }
  1344. #---------------------------------------------------------------------------------------------------------------
  1345. sub get_option {
  1346. my $db=shift;
  1347. my $option_id=shift;
  1348. return if (!$option_id);
  1349. return if (!$db);
  1350. my $default_option = get_record_sql($db,'SELECT * FROM config_options WHERE id='.$option_id);
  1351. my $config_options = get_record_sql($db,'SELECT * FROM config WHERE option_id='.$option_id);
  1352. my $result;
  1353. if (!$config_options) {
  1354. if ($default_option->{'type'}=~/^(int|bool)/i) { $result = $default_option->{'default_value'}*1; };
  1355. if ($default_option->{'type'}=~/^(string|text)/i) { $result = $default_option->{'default_value'}; }
  1356. if ($default_option->{'type'}=~/^list/i) { $result = $default_option->{'default_value'}; }
  1357. return $result;
  1358. }
  1359. $result = $config_options->{'value'};
  1360. return $result;
  1361. }
  1362. #---------------------------------------------------------------------------------------------------------------
  1363. sub init_option {
  1364. my $db=shift;
  1365. $last_refresh_config = time();
  1366. $config_ref{version}='';
  1367. my $version_record = get_record_sql($db,"SELECT version FROM version WHERE version is NOT NULL");
  1368. if ($version_record) { $config_ref{version}=$version_record->{version}; }
  1369. $config_ref{dbh}=$db;
  1370. $config_ref{save_detail}=get_option($db,23);
  1371. $config_ref{add_unknown_user}=get_option($db,22);
  1372. $config_ref{dhcp_server}=get_option($db,5);
  1373. $config_ref{snmp_default_version}=get_option($db,9);
  1374. $config_ref{snmp_default_community}=get_option($db,11);
  1375. $config_ref{KB}=get_option($db,1);
  1376. if ($config_ref{KB} ==0) { $config_ref{KB}=1000; }
  1377. if ($config_ref{KB} ==1) { $config_ref{KB}=1024; }
  1378. $config_ref{admin_email}=get_option($db,21);
  1379. $config_ref{sender_email}=get_option($db,52);
  1380. $config_ref{send_email}=get_option($db,51);
  1381. $config_ref{history}=get_option($db,26);
  1382. $config_ref{history_dhcp}=get_option($db,27);
  1383. $config_ref{router_login}=get_option($db,28);
  1384. $config_ref{router_password}=get_option($db,29);
  1385. $config_ref{router_port}=get_option($db,30);
  1386. $config_ref{org_name}=get_option($db,32);
  1387. $config_ref{domain_name}=get_option($db,33);
  1388. $config_ref{connections_history}=get_option($db,35);
  1389. $config_ref{debug}=get_option($db,34);
  1390. $config_ref{log_level} = get_option($db,53);
  1391. if ($config_ref{debug}) { $config_ref{log_level} = 255; }
  1392. $config_ref{urgent_sync}=get_option($db,50);
  1393. $config_ref{ignore_hotspot_dhcp_log} = get_option($db,44);
  1394. $config_ref{ignore_update_dhcp_event} = get_option($db,45);
  1395. $config_ref{update_hostname_from_dhcp} = get_option($db,46);
  1396. $config_ref{history_log_day}=get_option($db,47);
  1397. $config_ref{history_syslog_day} = get_option($db,48);
  1398. $config_ref{history_trafstat_day} = get_option($db,49);
  1399. $config_ref{enable_quotes} = get_option($db,54);
  1400. $config_ref{netflow_step} = get_option($db,55);
  1401. $config_ref{traffic_ipstat_history} = get_option($db,56);
  1402. $config_ref{nagios_url} = get_option($db,57);
  1403. $config_ref{cacti_url} = get_option($db,58);
  1404. $config_ref{torrus_url} = get_option($db,59);
  1405. $config_ref{wiki_url} = get_option($db,60);
  1406. $config_ref{stat_url} = get_option($db,62);
  1407. $config_ref{wiki_path} = get_option($db,61);
  1408. $config_ref{auto_mac_rule} = get_option($db,64);
  1409. #network configuration mode
  1410. $config_ref{config_mode}=get_option($db,68);
  1411. #auto clean old user record
  1412. $config_ref{clean_empty_user}=get_option($db,69);
  1413. #dns_server_type
  1414. $config_ref{dns_server}=get_option($db,3);
  1415. $config_ref{dns_server_type}=get_option($db,70);
  1416. $config_ref{enable_dns_updates}=get_option($db,71);
  1417. #$save_detail = 1; id=23
  1418. $save_detail=get_option($db,23);
  1419. #$add_unknown_user = 1; id=22
  1420. $add_unknown_user=get_option($db,22);
  1421. #$dns_server='192.168.2.12'; id=3
  1422. $dns_server=get_option($db,3);
  1423. #$dhcp_server='192.168.2.12'; id=5
  1424. $dhcp_server=get_option($db,5);
  1425. #$snmp_default_version='2'; id=9
  1426. $snmp_default_version=get_option($db,9);
  1427. #$snmp_default_community='public'; id=11
  1428. $snmp_default_community=get_option($db,11);
  1429. #$KB=1024; id=1
  1430. $KB=$config_ref{KB};
  1431. #$admin_email; id=21
  1432. $admin_email=get_option($db,21);
  1433. #sender email
  1434. $sender_email=get_option($db,52);
  1435. #send email
  1436. $send_email=get_option($db,51);
  1437. #$history=15; id=26
  1438. $history=get_option($db,26);
  1439. #$history_dhcp=7; id=27
  1440. $history_dhcp=get_option($db,27);
  1441. #$router_login="admin"; id=28
  1442. $router_login=get_option($db,28);
  1443. #$router_password="admin"; id=29
  1444. $router_password=get_option($db,29);
  1445. #$router_port=23; id=30
  1446. $router_port=get_option($db,30);
  1447. #32
  1448. $org_name=get_option($db,32);
  1449. #33
  1450. $domain_name=get_option($db,33);
  1451. #35
  1452. $connections_history=get_option($db,35);
  1453. #debug
  1454. $debug=get_option($db,34);
  1455. #log level
  1456. $log_level = get_option($db,53);
  1457. if ($debug) { $log_level = 255; }
  1458. #urgent sync access
  1459. $urgent_sync=get_option($db,50);
  1460. $ignore_hotspot_dhcp_log = get_option($db,44);
  1461. $ignore_update_dhcp_event = get_option($db,45);
  1462. $update_hostname_from_dhcp = get_option($db,46);
  1463. $history_log_day=get_option($db,47);
  1464. $history_syslog_day = get_option($db,48);
  1465. $history_trafstat_day = get_option($db,49);
  1466. my $ou = get_record_sql($db,"SELECT id FROM OU WHERE default_users = 1");
  1467. if (!$ou) { $default_user_ou_id = 0; } else { $default_user_ou_id = $ou->{'id'}; }
  1468. $ou = get_record_sql($db,"SELECT id FROM OU WHERE default_hotspot = 1");
  1469. if (!$ou) { $default_hotspot_ou_id = $default_user_ou_id; } else { $default_hotspot_ou_id = $ou->{'id'}; }
  1470. @subnets=get_records_sql($db,'SELECT * FROM subnets ORDER BY ip_int_start');
  1471. if (defined $office_networks) { undef $office_networks; }
  1472. if (defined $free_networks) { undef $free_networks; }
  1473. if (defined $vpn_networks) { undef $vpn_networks; }
  1474. if (defined $hotspot_networks) { undef $hotspot_networks; }
  1475. if (defined $all_networks) { undef $all_networks; }
  1476. $office_networks = new Net::Patricia;
  1477. $free_networks = new Net::Patricia;
  1478. $vpn_networks = new Net::Patricia;
  1479. $hotspot_networks = new Net::Patricia;
  1480. $all_networks = new Net::Patricia;
  1481. @office_network_list=();
  1482. @free_network_list=();
  1483. @free_network_list=();
  1484. @vpn_network_list=();
  1485. @hotspot_network_list=();
  1486. @all_network_list=();
  1487. foreach my $net (@subnets) {
  1488. next if (!$net->{subnet});
  1489. $subnets_ref{$net->{subnet}}=$net;
  1490. if ($net->{office}) {
  1491. push(@office_network_list,$net->{subnet});
  1492. $office_networks->add_string($net->{subnet},$net);
  1493. }
  1494. if ($net->{free}) {
  1495. push(@free_network_list,$net->{subnet});
  1496. $free_networks->add_string($net->{subnet},$net);
  1497. }
  1498. if ($net->{vpn}) {
  1499. push(@vpn_network_list,$net->{subnet});
  1500. $vpn_networks->add_string($net->{subnet},$net);
  1501. }
  1502. if ($net->{hotspot}) {
  1503. push(@hotspot_network_list,$net->{subnet});
  1504. push(@all_network_list,$net->{subnet});
  1505. $hotspot_networks->add_string($net->{subnet},$net);
  1506. }
  1507. push(@all_network_list,$net->{subnet});
  1508. $all_networks->add_string($net->{subnet},$net);
  1509. }
  1510. }
  1511. #---------------------------------------------------------------------------------------------------------------
  1512. sub get_subnets_ref {
  1513. my $db = shift;
  1514. my @list=get_records_sql($db,'SELECT * FROM subnets ORDER BY ip_int_start');
  1515. my $list_ref;
  1516. foreach my $net (@list) {
  1517. next if (!$net->{subnet});
  1518. $list_ref->{$net->{subnet}}=$net;
  1519. }
  1520. return $list_ref;
  1521. }
  1522. #---------------------------------------------------------------------------------------------------------------
  1523. sub get_device_by_ip {
  1524. my $db = shift;
  1525. my $ip = shift;
  1526. my $netdev=get_record_sql($db,'SELECT * FROM devices WHERE ip="'.$ip.'"');
  1527. if ($netdev and $netdev->{id}>0) { return $netdev; }
  1528. my $auth_rec=get_record_sql($db,'SELECT user_id FROM User_auth WHERE ip="'.$ip.'" and deleted=0');
  1529. if ($auth_rec and $auth_rec->{user_id}>0) {
  1530. $netdev=get_record_sql($db,'SELECT * FROM devices WHERE user_id='.$auth_rec->{user_id});
  1531. return $netdev;
  1532. }
  1533. return;
  1534. }
  1535. #---------------------------------------------------------------------------------------------------------------
  1536. sub GetUnixTimeByStr {
  1537. my $time_str = shift;
  1538. $time_str =~s/\//-/g;
  1539. $time_str = trim($time_str);
  1540. my ($sec,$min,$hour,$day,$mon,$year) = (localtime())[0,1,2,3,4,5];
  1541. $year+=1900;
  1542. $mon++;
  1543. if ($time_str =~/^([0-9]{2,4})\-([0-9]{1,2})-([0-9]{1,2})\s+/) {
  1544. $year = $1; $mon = $2; $day = $3;
  1545. }
  1546. if ($time_str =~/([0-9]{1,2})\:([0-9]{1,2})\:([0-9]{1,2})$/) {
  1547. $hour = $1; $min = $2; $sec = $3;
  1548. }
  1549. my $result = mktime($sec,$min,$hour,$day,$mon-1,$year-1900);
  1550. return $result;
  1551. }
  1552. #---------------------------------------------------------------------------------------------------------------
  1553. sub GetTimeStrByUnixTime {
  1554. my $time = shift || time();
  1555. my ($sec, $min, $hour, $mday, $mon, $year) = (localtime($time))[0,1,2,3,4,5];
  1556. my $result = strftime("%Y-%m-%d %H:%M:%S",$sec, $min, $hour, $mday, $mon, $year);
  1557. return $result;
  1558. }
  1559. #---------------------------------------------------------------------------------------------------------------
  1560. sub Set_Variable {
  1561. my $db = shift;
  1562. my $name = shift || $MY_NAME;
  1563. my $value = shift || $$;
  1564. my $timeshift = shift || 60;
  1565. Del_Variable($db,$name);
  1566. my $clean_variables = time() + $timeshift;
  1567. my ($sec,$min,$hour,$day,$month,$year,$zone) = localtime($clean_variables);
  1568. $month++;
  1569. $year += 1900;
  1570. my $clean_str=sprintf "%04d-%02d-%02d %02d:%02d:%02d",$year,$month,$day,$hour,$min,$sec;
  1571. my $clean_variables_date=$db->quote($clean_str);
  1572. do_sql($db,"INSERT INTO variables(name,value,clear_time) VALUES('".$name."','".$value."',".$clean_variables_date.");");
  1573. }
  1574. #---------------------------------------------------------------------------------------------------------------
  1575. sub Get_Variable {
  1576. my $db = shift;
  1577. my $name = shift || $MY_NAME;
  1578. my $variable=get_record_sql($db,'SELECT `value` FROM `variables` WHERE name="'.$name.'"');
  1579. if (!$variable and $variable->{'value'}) { return $variable->{'value'}; }
  1580. return;
  1581. }
  1582. #---------------------------------------------------------------------------------------------------------------
  1583. sub Del_Variable {
  1584. my $db = shift;
  1585. my $name = shift || $MY_NAME;
  1586. do_sql($db,"DELETE FROM `variables` WHERE name='".$name."';");
  1587. }
  1588. #---------------------------------------------------------------------------------------------------------------
  1589. sub recalc_quotes {
  1590. my $db = shift;
  1591. my $calc_id = shift || $$;
  1592. return if (!get_option($db,54));
  1593. clean_variables($db);
  1594. return if (Get_Variable($db,'RECALC'));
  1595. my $timeshift = get_option($db,55);
  1596. if ($timeshift >5 ) { $timeshift=$timeshift-1; }
  1597. Set_Variable($db,'RECALC',$calc_id,time()+$timeshift*60);
  1598. my $now = DateTime->now(time_zone=>'local');
  1599. my $day_start = $db->quote($now->ymd("-")." 00:00:00");
  1600. my $day_dur = DateTime::Duration->new( days => 1 );
  1601. my $tomorrow = $now+$day_dur;
  1602. my $day_stop = $db->quote($tomorrow->ymd("-")." 00:00:00");
  1603. $now->set(day=>1);
  1604. my $month_start=$db->quote($now->ymd("-")." 00:00:00");
  1605. my $month_dur = DateTime::Duration->new( months => 1 );
  1606. my $next_month = $now + $month_dur;
  1607. $next_month->set(day=>1);
  1608. my $month_stop = $db->quote($next_month->ymd("-")." 00:00:00");
  1609. #get user limits
  1610. 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";
  1611. my @authlist_ref = get_records_sql($db,$user_auth_list_sql);
  1612. my %user_stats;
  1613. my %auth_info;
  1614. foreach my $row (@authlist_ref) {
  1615. $auth_info{$row->{auth_id}}{user_id}=$row->{id};
  1616. $auth_info{$row->{auth_id}}{day_limit}=$row->{auth_day};
  1617. $auth_info{$row->{auth_id}}{month_limit}=$row->{auth_month};
  1618. $auth_info{$row->{auth_id}}{day}=0;
  1619. $auth_info{$row->{auth_id}}{month}=0;
  1620. $user_stats{$row->{id}}{day_limit}=$row->{day_quota};
  1621. $user_stats{$row->{id}}{month_limit}=$row->{month_quota};
  1622. $user_stats{$row->{id}}{day}=0;
  1623. $user_stats{$row->{id}}{month}=0;
  1624. }
  1625. #recalc quotes - global
  1626. #day
  1627. my $day_sql="SELECT User_stats.auth_id, SUM( byte_in + byte_out ) AS traf_all FROM User_stats
  1628. WHERE User_stats.`timestamp`>= $day_start AND User_stats.`timestamp`< $day_stop GROUP BY User_stats.auth_id";
  1629. my @day_stats = get_records_sql($db,$day_sql);
  1630. foreach my $row (@day_stats) {
  1631. my $user_id=$auth_info{$row->{auth_id}}{user_id};
  1632. $auth_info{$row->{auth_id}}{day}=$row->{traf_all};
  1633. $user_stats{$user_id}{day}+=$row->{traf_all};
  1634. }
  1635. #month
  1636. my $month_sql="SELECT User_stats.auth_id, SUM( byte_in + byte_out ) AS traf_all FROM User_stats
  1637. WHERE User_stats.`timestamp`>= $month_start AND User_stats.`timestamp`< $month_stop GROUP BY User_stats.auth_id";
  1638. my @month_stats = get_records_sql($db,$month_sql);
  1639. foreach my $row (@month_stats) {
  1640. my $user_id=$auth_info{$row->{auth_id}}{user_id};
  1641. $auth_info{$row->{auth_id}}{month}=$row->{traf_all};
  1642. $user_stats{$user_id}{month}+=$row->{traf_all};
  1643. }
  1644. foreach my $auth_id (keys %auth_info) {
  1645. next if (!$auth_info{$auth_id}{day_limit});
  1646. next if (!$auth_info{$auth_id}{month_limit});
  1647. my $day_limit=$auth_info{$auth_id}{day_limit}*$KB*$KB;
  1648. my $month_limit=$auth_info{$auth_id}{month_limit}*$KB*$KB;
  1649. my $blocked_d=($auth_info{$auth_id}{day}>$day_limit);
  1650. my $blocked_m=($auth_info{$auth_id}{month}>$month_limit);
  1651. if ($blocked_d or $blocked_m) {
  1652. my $history_msg;
  1653. 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; }
  1654. 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; }
  1655. do_sql($db,"UPDATE User_auth set blocked=1, changed=1 where id=$auth_id");
  1656. db_log_verbose($db,$history_msg);
  1657. }
  1658. }
  1659. foreach my $user_id (keys %user_stats) {
  1660. next if (!$user_stats{$user_id}{day_limit});
  1661. next if (!$user_stats{$user_id}{month_limit});
  1662. my $day_limit=$user_stats{$user_id}{day_limit}*$KB*$KB;
  1663. my $month_limit=$user_stats{$user_id}{month_limit}*$KB*$KB;
  1664. my $blocked_d=($user_stats{$user_id}{day}>$day_limit);
  1665. my $blocked_m=($user_stats{$user_id}{month}>$month_limit);
  1666. if ($blocked_d or $blocked_m) {
  1667. my $history_msg;
  1668. 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; }
  1669. 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; }
  1670. do_sql($db,"UPDATE User_user set blocked=1 where id=$user_id");
  1671. do_sql($db,"UPDATE User_auth set blocked=1, changed=1 where user_id=$user_id");
  1672. db_log_verbose($db,$history_msg);
  1673. }
  1674. }
  1675. Del_Variable($db,'RECALC');
  1676. }
  1677. #---------------------------------------------------------------------------------------------------------------
  1678. sub clean_variables {
  1679. my $db = shift;
  1680. #clean temporary variables
  1681. my $clean_variables = time();
  1682. my ($sec,$min,$hour,$day,$month,$year,$zone) = localtime($clean_variables);
  1683. $month++;
  1684. $year += 1900;
  1685. my $now_str=sprintf "%04d-%02d-%02d %02d:%02d:%02d",$year,$month,$day,$hour,$min,$sec;
  1686. my $clean_variables_date=$db->quote($now_str);
  1687. do_sql($db,"DELETE FROM `variables` WHERE clear_time<=$clean_variables_date");
  1688. }
  1689. #---------------------------------------------------------------------------------------------------------------
  1690. $dbh=init_db();
  1691. init_option($dbh);
  1692. clean_variables($dbh);
  1693. Set_Variable($dbh);
  1694. 1;
  1695. }